<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

 <title>Bayesian Statistics Self-Learning</title>
 <link href="https://bayesian-statistics-self-learning.pages.dev/atom.xml" rel="self"/>
 <link href="https://bayesian-statistics-self-learning.pages.dev/"/>
 <updated>2026-12-05T03:51:20+00:00</updated>
 <id>https://bayesian-statistics-self-learning.pages.dev</id>
 <author>
   <name>Your Name</name>
   <email>your.email@example.com</email>
 </author>

 
 <entry>
   <title>Bài 8.5: Ứng dụng hiện đại của kiểm tra mô hình và ra quyết định Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter08/08_05_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter08/08_05_modern_applications</id>
   <content type="html">&lt;p&gt;Từ những khái niệm kiểm tra mô hình (PPC), tiêu chí thông tin (WAIC/PSIS-LOO), kết hợp mô hình (Stacking) cho đến phân tích quyết định theo hàm tổn thất, toàn bộ Chương 8 tạo thành “bộ khung vận hành khép kín” của thống kê Bayes hiện đại — được Andrew Gelman và cộng sự gọi là &lt;strong&gt;Bayesian Workflow&lt;/strong&gt;. Trong các tổ chức công nghệ, tài chính và y sinh hàng đầu, chính quy trình kiểm tra – so sánh – quyết định này mới là yếu tố giúp mô hình Bayes trụ vững trước dữ liệu thực tế đầy nhiễu và thay đổi liên tục.&lt;/p&gt;

&lt;p&gt;Bài tổng kết Chương 8 này minh họa cách bốn mảnh ghép ấy phối hợp nhịp nhàng trong thử nghiệm sản phẩm trực tuyến, quản trị rủi ro và triển khai mô hình ở quy mô sản xuất.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài học tùy chọn này, bạn sẽ nhìn nhận PPC, LOO/WAIC và phân tích quyết định như một quy trình vận hành thực tế, thay vì phần phụ lục sau khi khớp mô hình. Bạn sẽ kết nối được kiểm tra hậu nghiệm với hiệu chuẩn dựa trên mô phỏng (simulation-based calibration), so sánh mô hình với độ bất định của chính hiệu chênh LOO, và quy tắc hành động Bayes với tối ưu hóa Bayes (Bayesian optimization) cùng bài toán bandit.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bayesian-workflow-trong-mlops-thử-nghiệm-ab-và-quản-trị-rủi-ro&quot;&gt;Kiến thức cần nhớ: Bayesian Workflow trong MLOps, Thử nghiệm A/B và Quản trị Rủi ro&lt;/h2&gt;

&lt;p&gt;Ba trụ cột ứng dụng khép lại Chương 8:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra mô hình tự động trong MLOps (Continuous PPC &amp;amp; Pareto-\(k\) Monitoring):&lt;/strong&gt; Khi dữ liệu thực tế trôi dạt theo thời gian (&lt;em&gt;data drift&lt;/em&gt;), các kiểm tra PPC định kỳ và theo dõi tỷ lệ điểm có Pareto \(\hat k &amp;gt; 0.7\) đóng vai trò hệ thống cảnh báo sớm trước khi dự báo bị sai lệch nghiêm trọng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thử nghiệm A/B Bayes với Tổn thất Kỳ vọng (Expected Loss Stopping Rule):&lt;/strong&gt; Thay vì chờ đủ cỡ mẫu cố định để kiểm định \(p &amp;lt; 0.05\), các nền tảng A/B hiện đại dừng thí nghiệm ngay khi &lt;em&gt;tổn thất kỳ vọng của việc chọn phương án đang dẫn đầu&lt;/em&gt; giảm xuống dưới một ngưỡng chấp nhận được (ví dụ \(&amp;lt; 0.1\%\) tỷ lệ chuyển đổi).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quyết định đa mục tiêu dưới bất định:&lt;/strong&gt; Kết hợp Stacking (giảm rủi ro chọn nhầm mô hình) với hàm tổn thất bất đối xứng giúp các hệ thống tín dụng, tồn kho và y tế tối ưu hóa trực tiếp KPI thực tế thay vì chỉ tối ưu sai số học thuật.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-có&quot;&gt;Kiến thức cần có&lt;/h2&gt;

&lt;p&gt;Các bài 8.1–8.4 đã trình bày PPC, các tiêu chí thông tin, chiến lược so sánh mô hình và ra quyết định dưới hàm mất mát. Bài học này không định nghĩa lại ELPD, mà cho thấy các công cụ đó đang được hoàn thiện như thế nào trong nghiên cứu giai đoạn 2022–2025 và trong các thư viện tối ưu hóa hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;mở-đầu&quot;&gt;Mở đầu&lt;/h2&gt;

&lt;p&gt;Chương 8 xuất phát từ một thói quen phổ biến nhưng dễ gây sai lầm: thấy chuỗi MCMC hội tụ là dừng lại. Trong môi trường kỹ thuật phần mềm và dữ liệu, thói quen đó thường biến thành tâm lý yên tâm chỉ vì các chỉ báo hội tụ đều hiển thị trạng thái đạt. Tuy nhiên, một thuật toán lấy mẫu có thể lấy mẫu chính xác từ một mô hình sai, hoặc lấy mẫu sai từ một mô hình đúng; và một hiệu chênh \(\Delta\mathrm{ELPD}\) có thể đảo dấu khi tính lại sai số. Trọng tâm của bài học này là tách bạch ba câu hỏi mà các nhóm sản phẩm thường trộn lẫn: mô hình có sinh được dữ liệu giống thực tế không, mô hình nào dự báo tốt hơn khi tính cả độ bất định của phép so sánh, và cuối cùng ta nên &lt;em&gt;hành động&lt;/em&gt; ra sao?&lt;/p&gt;

&lt;h2 id=&quot;phát-triển-khái-niệm&quot;&gt;Phát triển khái niệm&lt;/h2&gt;

&lt;p&gt;PPC đặt câu hỏi liệu dữ liệu mô phỏng \(y^{\mathrm{rep}}\) sinh từ \(p(y\mid\theta)\) với \(\theta\sim p(\theta\mid y)\) có tái tạo được cấu trúc của dữ liệu quan sát \(y\) hay không. LOO ước lượng kỳ vọng mật độ dự báo dạng log trên một điểm dữ liệu mới. Lý thuyết quyết định chọn hành động tối ưu:&lt;/p&gt;

\[a^*(y)=\arg\min_a\int L(a,\theta)\,p(\theta\mid y)\,d\theta.\]

&lt;p&gt;Ba công cụ này không thay thế nhau. Một mô hình có điểm LOO tốt hơn vẫn có thể thất bại ở PPC phần đuôi; và một hành động tối ưu vẫn có thể dựa trên mô hình có điểm log score thấp hơn nếu hàm mất mát mang tính bất đối xứng.&lt;/p&gt;

&lt;h2 id=&quot;mô-hình-như-câu-chuyện-sinh-dữ-liệu&quot;&gt;Mô hình như câu chuyện sinh dữ liệu&lt;/h2&gt;

&lt;h3 id=&quot;1-hiệu-chuẩn-dựa-trên-mô-phỏng-sbc-như-kiểm-thử-phần-mềm-và-suy-luận&quot;&gt;1. Hiệu chuẩn dựa trên mô phỏng (SBC) như kiểm thử phần mềm và suy luận&lt;/h3&gt;

&lt;p&gt;Modrák et al. (2025) hoàn thiện khung hiệu chuẩn dựa trên mô phỏng (simulation-based calibration — SBC): rút \(\theta\) từ tiên nghiệm, sinh dữ liệu \(y\), khớp lại mô hình rồi kiểm tra phân bố thứ hạng của các đại lượng kiểm định trong hậu nghiệm. Nhóm tác giả chỉ ra rằng nếu chỉ kiểm tra thứ hạng của riêng tham số, ta có thể bỏ sót cả một lớp lỗi — kể cả trường hợp hậu nghiệm trùng với tiên nghiệm — trong khi hàm hợp lý đồng thời là một đại lượng kiểm định rất nhạy. Trong công nghiệp, SBC đóng vai trò như kiểm thử đơn vị (unit test) cho mô hình PyMC hoặc Stan trước khi đưa vào thử nghiệm A/B hay định giá. PPC của bài 8.1 kiểm tra mô hình trên dữ liệu thật, còn SBC kiểm tra &lt;em&gt;chính thuật toán suy luận&lt;/em&gt; trên dữ liệu sinh từ mô hình đó.&lt;/p&gt;

&lt;h3 id=&quot;2-độ-bất-định-của-bản-thân-phép-so-sánh-loo&quot;&gt;2. Độ bất định của bản thân phép so sánh LOO&lt;/h3&gt;

&lt;p&gt;Sivula, Magnusson, Matamoros và Vehtari (2025) chỉ ra rằng xấp xỉ chuẩn cho hiệu chênh LOO thường bị lệch khi hai mô hình dự báo gần giống nhau, khi mô hình bị đặc tả sai hoặc khi cỡ mẫu nhỏ. Độ lệch (skewness) của sai số ước lượng thậm chí có thể không triệt tiêu khi \(n\to\infty\) trong một số trường hợp. Hệ quả thực tế rất rõ: không nên công bố bảng xếp hạng mô hình như một thứ tự tuyệt đối nếu sai số chuẩn của \(\Delta\mathrm{ELPD}\) lấn át bản thân độ chênh lệch. Bài 8.3 đã nhấn mạnh so sánh mô hình là ra quyết định dưới độ bất định; nghiên cứu này định lượng trực tiếp phần độ bất định đó.&lt;/p&gt;

&lt;h3 id=&quot;3-tối-ưu-hóa-bayes-bayesian-optimization-như-lý-thuyết-quyết-định-trên-hàm-tốn-kém&quot;&gt;3. Tối ưu hóa Bayes (Bayesian optimization) như lý thuyết quyết định trên hàm tốn kém&lt;/h3&gt;

&lt;p&gt;Khi \(\theta\) là một cấu hình siêu tham số hoặc một thí nghiệm phòng lab, mỗi lần đánh giá hàm mục tiêu \(f(\theta)\) đều rất tốn kém. Tối ưu hóa Bayes đặt một phân phối hậu nghiệm — thường là quá trình Gauss (Gaussian process) — lên hàm \(f\), rồi chọn điểm đánh giá tiếp theo bằng cách tối thiểu hóa mất mát kỳ vọng (ví dụ qua tiêu chí expected improvement). Đây chính là nguyên lý của bài 8.4 áp dụng cho không gian hành động liên tục. Thư viện BoTorch (Balandat et al., 2020; hệ sinh thái 2022–2026) triển khai quy tắc này bằng mô phỏng Monte Carlo trên hậu nghiệm, hỗ trợ tối ưu đa mục tiêu và có ràng buộc. AutoML nhờ vậy là một ứng dụng trực tiếp của hành động Bayes để chọn mô hình và siêu tham số thay cho tìm kiếm lưới mù quáng.&lt;/p&gt;

&lt;h3 id=&quot;4-bài-toán-bandit-và-thí-nghiệm-thích-nghi&quot;&gt;4. Bài toán bandit và thí nghiệm thích nghi&lt;/h3&gt;

&lt;p&gt;Thompson sampling — từng xuất hiện như ứng dụng của tiên nghiệm liên hợp ở Chương 2 — được đặt đúng vào vị trí của nó: một cách xấp xỉ tuần tự cho hành động Bayes khi hàm mất mát là độ hối tiếc (regret). Các nền tảng nội dung, quảng cáo và thử nghiệm lâm sàng thích nghi liên tục cập nhật \(p(\theta\mid y)\) rồi chọn phương án (arm) tiếp theo. Quyết định ở đây không phải “bác bỏ \(H_0\)”, mà là tiếp tục thử nghiệm, dừng lại hay điều chỉnh tỷ lệ phân bổ lưu lượng. PPC vẫn giữ vai trò thiết yếu: nếu mô hình tỷ lệ chuyển đổi sai ở phần đuôi, thuật toán bandit có thể dồn lưu lượng vào một phương án kém hiệu quả.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-quyết-định-ab-test-bằng-tổn-thất-kỳ-vọng-expected-loss&quot;&gt;Video ngắn: Quyết định A/B Test bằng Tổn thất Kỳ vọng (Expected Loss)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch08-05a-bayesian-ab-expected-loss.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): khi cỡ mẫu tăng từ 30 → 420, vùng rủi ro đỏ thu hẹp dần đưa Expected Loss xuống dưới ngưỡng 0.5% để chốt dừng thí nghiệm.&lt;/p&gt;

&lt;h2 id=&quot;diễn-giải-và-nhận-định&quot;&gt;Diễn giải và nhận định&lt;/h2&gt;

&lt;p&gt;Một kết quả PPC tốt không đồng nghĩa với bằng chứng nhân quả. Một hiệu chênh LOO lớn hơn hai lần sai số chuẩn vẫn có thể chỉ là so sánh giữa hai mô hình cùng bị đặc tả sai. Giá trị expected improvement cao không bảo đảm điểm đánh giá kế tiếp chắc chắn tốt hơn, mà chỉ có nghĩa rằng &lt;em&gt;dưới phân phối hậu nghiệm hiện tại&lt;/em&gt;, giá trị thông tin dự kiến vượt chi phí đánh giá. Cần giữ tách bạch ba lớp diễn giải: phê bình cơ chế sinh dữ liệu, so sánh năng lực dự báo và lựa chọn hành động.&lt;/p&gt;

&lt;h2 id=&quot;ứng-dụng&quot;&gt;Ứng dụng&lt;/h2&gt;

&lt;p&gt;Kiểm thử mô hình trước khi đưa vào vận hành, lựa chọn mô hình dự báo cho dữ liệu bảng và chuỗi thời gian, tinh chỉnh siêu tham số và phân bổ thí nghiệm là bốn mảng ứng dụng nổi bật của Chương 8 trong khoa học máy tính và khoa học dữ liệu hiện nay.&lt;/p&gt;

&lt;h2 id=&quot;giới-hạn-và-hướng-mở-rộng&quot;&gt;Giới hạn và hướng mở rộng&lt;/h2&gt;

&lt;p&gt;SBC đòi hỏi khớp lại mô hình rất nhiều lần nên tốn chi phí tính toán. LOO giả định đóng góp của các quan sát có thể tách tích gần như độc lập. Tối ưu hóa Bayes phụ thuộc mạnh vào tiên nghiệm trên hàm \(f\) và dễ đưa ra lựa chọn thiếu thận trọng nếu mô hình nhiễu bị đặc tả sai. Khóa học không có chương riêng về quá trình Gauss, nên bài này chỉ sử dụng GP như một phân phối hậu nghiệm phục vụ ra quyết định; khi mở rộng sang thống kê phi tham số, bạn sẽ thấy hạt nhân của tối ưu hóa Bayes chính là mô hình này.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tính-tổn-thất-kỳ-vọng-khi-chọn-sai-expected-loss-trong-ab-testing-bayes&quot;&gt;Giải thích: Tính “Tổn thất kỳ vọng khi chọn sai” (Expected Loss) trong A/B Testing Bayes&lt;/h2&gt;

&lt;p&gt;Một trong những ứng dụng thực chiến phổ biến nhất của Chương 8 là quy tắc dừng A/B testing dựa trên &lt;strong&gt;Expected Loss&lt;/strong&gt;. Hãy đọc chậm 3 bước tính trên \(S\) mẫu hậu nghiệm \((p_A^{(s)}, p_B^{(s)})\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Với mỗi mẫu hậu nghiệm \(s\), tính thiệt hại nếu ta chọn phương án B mà thực ra A mới tốt hơn:&lt;/strong&gt; \(\text{loss}_B^{(s)} = \max(0,\; p_A^{(s)} - p_B^{(s)})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lấy trung bình trên toàn bộ \(S\) mẫu hậu nghiệm:&lt;/strong&gt; \(\mathrm{EL}(B) = \frac{1}{S}\sum_{s=1}^S \max(0,\; p_A^{(s)} - p_B^{(s)})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh \(\mathrm{EL}(B)\) với ngưỡng rủi ro kinh doanh \(\varepsilon\):&lt;/strong&gt; Nếu \(\mathrm{EL}(B) &amp;lt; \varepsilon\), ta có thể tự tin tung ra phương án B ngay cả khi \(P(p_B &amp;gt; p_A \mid y)\) chưa đạt 99%, vì &lt;em&gt;ngay cả nếu B thua A, mức thiệt hại kỳ vọng cũng không đáng kể&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-tính-expected-loss-trên-4-mẫu-hậu-nghiệm-ab&quot;&gt;Ví dụ tính toán làm từng bước: Tính Expected Loss trên 4 mẫu hậu nghiệm A/B&lt;/h3&gt;

&lt;p&gt;Giả sử ta có 4 mẫu hậu nghiệm rút từ tỷ lệ chuyển đổi của giao diện cũ (A) và giao diện mới (B), với ngưỡng rủi ro chấp nhận \(\varepsilon = 0.005\) (0.5 điểm phần trăm):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Mẫu \(s\)&lt;/th&gt;
      &lt;th&gt;\(p_A^{(s)}\)&lt;/th&gt;
      &lt;th&gt;\(p_B^{(s)}\)&lt;/th&gt;
      &lt;th&gt;\(p_B^{(s)} &amp;gt; p_A^{(s)}\)?&lt;/th&gt;
      &lt;th&gt;Thiệt hại nếu chọn B: \(\max(0, p_A^{(s)} - p_B^{(s)})\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;\(0.100\)&lt;/td&gt;
      &lt;td&gt;\(0.112\)&lt;/td&gt;
      &lt;td&gt;Có&lt;/td&gt;
      &lt;td&gt;\(0.000\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;\(0.105\)&lt;/td&gt;
      &lt;td&gt;\(0.115\)&lt;/td&gt;
      &lt;td&gt;Có&lt;/td&gt;
      &lt;td&gt;\(0.000\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;\(0.108\)&lt;/td&gt;
      &lt;td&gt;\(0.104\)&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;\(0.004\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;\(0.098\)&lt;/td&gt;
      &lt;td&gt;\(0.110\)&lt;/td&gt;
      &lt;td&gt;Có&lt;/td&gt;
      &lt;td&gt;\(0.000\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Trung bình&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(0.1028\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(0.1103\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(75\%\) thắng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(\mathrm{EL}(B) = 0.004 / 4 = 0.0010\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Dù xác suất B thắng A mới là \(75\%\), tổn thất kỳ vọng nếu chọn B chỉ là \(0.0010\) (\(0.10\%\)), nhỏ hơn nhiều so với ngưỡng chịu rủi ro \(\varepsilon = 0.50\%\) — đủ cơ sở định lượng để triển khai B sớm và thu lợi nhuận sớm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Chỉ nhìn xác suất \(P(p_B &amp;gt; p_A \mid y)\) mà bỏ qua &lt;em&gt;độ lớn&lt;/em&gt; của chênh lệch \(p_A - p_B\). Xác suất thắng 75% với rủi ro thua nhỏ xíu khác hoàn toàn với xác suất thắng 75% nhưng nếu thua thì mất 20% doanh thu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Ở bảng trên, nếu ta thử chọn giữ lại phương án cũ A, tổn thất kỳ vọng sẽ là \(\mathrm{EL}(A) = \frac{0.012 + 0.010 + 0 + 0.012}{4} = 0.0085\) — lớn gấp &lt;strong&gt;8.5 lần&lt;/strong&gt; so với chọn B!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ysITaNRUQUU&quot;&gt;#164 Bayesian Workflow, with Andrew Gelman, Aki Vehtari &amp;amp; Richard McElreath&lt;/a&gt; — Learning Bayesian Statistics, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Cuộc thảo luận của Andrew Gelman, Aki Vehtari và Richard McElreath về quy trình Bayes, kết nối kiểm tra mô hình với so sánh và ra quyết định.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[BITESIZE&lt;/td&gt;
          &lt;td&gt;Understanding Simulation-Based Calibration, with Teemu Säilynoja](https://www.youtube.com/watch?v=EC1bvP65rjs) — Learning Bayesian Statistics, English. Giải thích hiệu chuẩn dựa trên mô phỏng (SBC), bổ trợ cho phần kiểm thử thuật toán suy luận.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vLx6lUlZ0fc&quot;&gt;Uncertainty in Bayesian leave-one-out cross-validation based model comparison&lt;/a&gt; — Aki Vehtari, English. Phân tích độ bất định khi so sánh mô hình bằng LOO, làm rõ vì sao không nên đọc hiệu chênh ELPD như một bảng xếp hạng cứng.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Trên một mô hình định giá, hãy phân biệt trường hợp không đạt ở PPC phần đuôi phải với trường hợp không đạt ở SBC. Trường hợp nào buộc bạn sửa &lt;em&gt;mã suy luận&lt;/em&gt;, trường hợp nào buộc bạn sửa &lt;em&gt;câu chuyện sinh dữ liệu&lt;/em&gt;?&lt;/li&gt;
  &lt;li&gt;Hai mô hình có \(\Delta\mathrm{ELPD}=1.2\) với sai số chuẩn 1.5. Dựa trên Sivula et al. (2025), bạn sẽ trình bày kết luận như thế nào trên slide báo cáo cho giám đốc sản phẩm?&lt;/li&gt;
  &lt;li&gt;Viết hàm mất mát cho một vòng tối ưu hóa Bayes khi mỗi thí nghiệm tiêu tốn một ngân sách cố định và bạn chỉ còn năm lần đánh giá. Tập hành động và trạng thái thế giới trong bài toán này là gì?&lt;/li&gt;
  &lt;li&gt;Một thuật toán bandit nội dung khai thác quá sớm một tiêu đề giật gân (clickbait). Phép kiểm tra PPC nào sẽ phát hiện sai lệch của mô hình phần thưởng, và quy tắc quyết định nào sẽ thận trọng hơn Thompson sampling thuần túy?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 6–7, 9.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 10, 13.&lt;/li&gt;
  &lt;li&gt;Modrák, M., et al. (2025). Simulation-based calibration checking for Bayesian computation. &lt;em&gt;Bayesian Analysis&lt;/em&gt;, 20(2), 461–488. &lt;a href=&quot;https://arxiv.org/abs/2211.02383&quot;&gt;arXiv:2211.02383&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Sivula, T., Magnusson, M., Matamoros, A. A., &amp;amp; Vehtari, A. (2025). Uncertainty in Bayesian leave-one-out cross-validation based model comparison. &lt;em&gt;Bayesian Analysis&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2008.10296&quot;&gt;arXiv:2008.10296&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Balandat, M., et al. (2020). BoTorch: A framework for efficient Monte-Carlo Bayesian optimization. &lt;em&gt;NeurIPS&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/1910.06403&quot;&gt;arXiv:1910.06403&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Russo, D., et al. (2018). A tutorial on Thompson sampling. &lt;em&gt;Foundations and Trends in Machine Learning&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://python.arviz.org/en/stable/api/generated/arviz.plot_ppc.html&quot;&gt;ArviZ posterior predictive checks&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://mc-stan.org/docs/stan-users-guide/posterior-predictive-checks.html&quot;&gt;Stan Workflow / SBC notes&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 7.4: Ứng dụng hiện đại của prior, regularization và học sâu Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter07/07_04_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter07/07_04_modern_applications</id>
   <content type="html">&lt;p&gt;Từ ý tưởng đặt prior Gaussian lên vài hệ số hồi quy, nguyên lý điều chuẩn Bayes ngày nay mở rộng lên tận những mạng nơ-ron sâu hàng triệu tham số: kỹ thuật &lt;em&gt;weight decay&lt;/em&gt; (AdamW) mang dáng dấp prior Gaussian, &lt;em&gt;Monte Carlo Dropout&lt;/em&gt; (Gal &amp;amp; Ghahramani, 2016) được chứng minh là một xấp xỉ biến phân của quá trình Bayes sâu, còn &lt;em&gt;Deep Ensembles&lt;/em&gt; và &lt;em&gt;Laplace Approximation&lt;/em&gt; trở thành vũ khí chuẩn để đo độ bất định trong xe tự lái và chẩn đoán y khoa bằng AI.&lt;/p&gt;

&lt;p&gt;Bài tổng kết Chương 7 này kết nối điều chuẩn Bayes cổ điển với &lt;strong&gt;Học sâu Bayes (Bayesian Deep Learning)&lt;/strong&gt; và các kỹ thuật hiệu chỉnh bất định hiện đại.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài học tùy chọn này, bạn sẽ nhìn nhận weight decay, horseshoe, xấp xỉ Laplace và deep ensemble như những cách khác nhau để đặt phân phối tiên nghiệm lên các mô hình quá linh hoạt. Mục tiêu không phải là ghi nhớ tên thuật toán, mà là thấy rằng vấn đề quá khớp ở Chương 7 chính là động lực dẫn đến học sâu Bayes (Bayesian deep learning): khi mạng nơ-ron có quá nhiều tham số, ta cần một phân phối trên tập các hàm thay vì chỉ một nghiệm tối ưu điểm duy nhất.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-từ-điều-chuẩn-cổ-điển-đến-học-sâu-bayes-bdl&quot;&gt;Kiến thức cần nhớ: Từ Điều chuẩn Cổ điển đến Học sâu Bayes (BDL)&lt;/h2&gt;

&lt;p&gt;Ba trụ cột sau nối liền Chương 7 với nghiên cứu học máy hiện đại:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mạng nơ-ron Bayes (BNN) &amp;amp; Suy diễn xấp xỉ:&lt;/strong&gt; Đặt phân phối prior \(p(\mathbf{w})\) lên toàn bộ trọng số mạng. Vì MCMC đầy đủ (HMC) quá đắt đỏ ở hàng triệu chiều, thực hành hiện đại dùng các phép xấp xỉ nhanh như &lt;strong&gt;Variational Inference (Bayes by Backprop)&lt;/strong&gt;, &lt;strong&gt;Last-Layer Laplace Approximation&lt;/strong&gt; và &lt;strong&gt;SWAG&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tách biệt hai loại bất định (Aleatoric vs. Epistemic):&lt;/strong&gt; Trong thị giác máy tính và y khoa, mô hình cần phân biệt giữa &lt;em&gt;dữ liệu mờ/nhiễu&lt;/em&gt; (aleatoric — không sửa được bằng cách thu thêm dữ liệu) và &lt;em&gt;mẫu nằm ngoài vùng đã học&lt;/em&gt; (epistemic — nơi các mạng con trong ensemble bất đồng mạnh, cảnh báo con người can thiệp).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Deep Ensembles như xấp xỉ đa đỉnh (Multi-Modal Posterior):&lt;/strong&gt; Huấn luyện độc lập \(M\) mạng nơ-ron với khởi tạo ngẫu nhiên khác nhau giúp khám phá nhiều cực tiểu khác nhau của bề mặt hàm mất mát, thường cho độ hiệu chỉnh bất định rất cao trên dữ liệu ngoài phân phối (&lt;em&gt;out-of-distribution&lt;/em&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-có&quot;&gt;Kiến thức cần có&lt;/h2&gt;

&lt;p&gt;Các bài 7.1–7.3 đã kết nối phân phối tiên nghiệm với điều chuẩn, đánh đổi độ lệch – phương sai và chọn biến. Bài học này không nhắc lại lý thuyết co rút hệ số, mà cho thấy cùng tư duy đó đang được vận dụng trong mạng nơ-ron và các mô hình dữ liệu bảng nhiều chiều giai đoạn 2021–2024.&lt;/p&gt;

&lt;h2 id=&quot;mở-đầu&quot;&gt;Mở đầu&lt;/h2&gt;

&lt;p&gt;Chương 7 bắt đầu bằng một sự đánh đổi quen thuộc: mô hình quá linh hoạt sẽ khớp cả nhiễu, còn quá cứng nhắc sẽ bỏ sót tín hiệu. Trong học sâu, sự đánh đổi này bị khuếch đại lên rất nhiều. Hàng triệu trọng số có thể khớp hoàn toàn tập huấn luyện mà vẫn khái quát hóa tốt, nhưng mức độ tự tin mà mạng gắn cho dự báo thường không phản ánh đúng xác suất thực tế. Vì thế, câu hỏi trung tâm không còn là “có nên thêm biến hay không?”, mà chuyển thành “liệu ta có thể duy trì một phân phối hậu nghiệm — dù chỉ trên lớp cuối — đủ trung thực để nhận biết khi nào mô hình không chắc chắn?”.&lt;/p&gt;

&lt;h2 id=&quot;phát-triển-khái-niệm&quot;&gt;Phát triển khái niệm&lt;/h2&gt;

&lt;p&gt;Một tiên nghiệm chuẩn trên hệ số:&lt;/p&gt;

\[\beta_j\sim\mathcal N(0,\tau^2),\]

&lt;p&gt;tương đương với weight decay: ước lượng MAP chính là nghiệm tối ưu có phạt \(L_2\). Các tiên nghiệm horseshoe và spike-and-slab đi xa hơn khi cho phép phần lớn hệ số tiến gần về 0 nhưng vẫn giữ lại một ít hệ số lớn, biến việc chọn biến thành một phần của suy luận hậu nghiệm thay vì một bước lọc tách rời. Khi \(\beta\) trở thành hàng triệu trọng số của mạng nơ-ron, ta không thể chạy MCMC đầy đủ. Các phương pháp xấp xỉ giai đoạn 2021–2024 — như xấp xỉ Laplace, suy luận Bayes ở lớp cuối (last-layer Bayes) và ensemble — là những cách khác nhau để giữ lại một phần thông tin của phân phối hậu nghiệm \(p(\theta\mid y)\).&lt;/p&gt;

&lt;h2 id=&quot;mô-hình-như-câu-chuyện-sinh-dữ-liệu&quot;&gt;Mô hình như câu chuyện sinh dữ liệu&lt;/h2&gt;

&lt;h3 id=&quot;1-điều-chuẩn-dưới-dạng-tiên-nghiệm-trong-glm-và-mô-hình-nông&quot;&gt;1. Điều chuẩn dưới dạng tiên nghiệm trong GLM và mô hình nông&lt;/h3&gt;

&lt;p&gt;Câu chuyện sinh dữ liệu vẫn giữ nguyên: dữ liệu xuất phát từ một hàm tương đối đơn giản cộng thêm nhiễu. Một tiên nghiệm hẹp thể hiện niềm tin rằng hàm mục tiêu không biến thiên quá gấp khúc. Trong bài toán chấm điểm tín dụng hoặc xếp hạng trên dữ liệu bảng, đây thường vẫn là lựa chọn phù hợp, đặc biệt khi Grinsztajn et al. (2022) chỉ ra rằng các mô hình cây và mô hình tuyến tính có điều chuẩn vẫn cạnh tranh tốt với mạng học sâu. Do đó, kiến thức Chương 7 không hề lỗi thời trong kỷ nguyên học sâu; ngược lại, học sâu khiến vai trò của tiên nghiệm càng trở nên &lt;em&gt;thiết yếu hơn&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;2-xấp-xỉ-laplace-và-lớp-cuối-hậu-nghiệm-cục-bộ-với-chi-phí-thấp&quot;&gt;2. Xấp xỉ Laplace và lớp cuối: Hậu nghiệm cục bộ với chi phí thấp&lt;/h3&gt;

&lt;p&gt;Daxberger et al. (2021) xây dựng khung Laplace Redux: bắt đầu từ nghiệm MAP, xấp xỉ phân phối hậu nghiệm bằng phân phối chuẩn dựa trên ma trận Hessian (hoặc các xấp xỉ của nó), qua đó chuyển một mạng đã huấn luyện thành mô hình Bayes với rất ít thay đổi về mã nguồn. Harrison, Willes và Snoek (2024) phát triển lớp cuối Bayes biến phân (Variational Bayesian Last Layers — VBLL) dưới dạng một hàm mất mát xác định, không cần lấy mẫu, với chi phí tính toán chỉ tăng theo bình phương số chiều của lớp cuối. Trong cách tiếp cận này, câu chuyện sinh dữ liệu được thu gọn có chủ đích: bộ biểu diễn đặc trưng được coi là đã học cố định, còn độ bất định tập trung ở lớp đầu ra. Điều chuẩn ở đây thể hiện dưới dạng một phân phối trên siêu phẳng quyết định.&lt;/p&gt;

&lt;h3 id=&quot;3-mạng-nơ-ron-bayes-có-cần-ngẫu-nhiên-hóa-toàn-bộ-trọng-số&quot;&gt;3. Mạng nơ-ron Bayes có cần ngẫu nhiên hóa toàn bộ trọng số?&lt;/h3&gt;

&lt;p&gt;Sharma, Farquhar, Nalisnick và Rainforth (2023) đặt ra một câu hỏi gắn trực tiếp với tinh thần của Chương 7: liệu ngẫu nhiên hóa toàn bộ trọng số (full stochasticity) có phải cách duy nhất để tránh quá khớp và thu được phân phối dự báo giàu thông tin hay không? Nhóm tác giả chứng minh rằng các mạng chỉ ngẫu nhiên hóa một phần vẫn là bộ xấp xỉ phổ quát cho phân phối điều kiện, và thực nghiệm không cho thấy lợi ích rõ rệt của việc đặt biến ngẫu nhiên lên mọi trọng số. Sự đánh đổi ở đây mở rộng sang chi phí bộ nhớ và tính trung thực của suy luận, chứ không chỉ là sai số dự báo. Bài toán chọn biến của bài 7.3 lúc này xuất hiện trở lại dưới dạng lựa chọn &lt;em&gt;tầng nào&lt;/em&gt; của mạng cần đặt phân phối tiên nghiệm.&lt;/p&gt;

&lt;h3 id=&quot;4-deep-ensemble-như-một-xấp-xỉ-bayes-thực-dụng&quot;&gt;4. Deep ensemble như một xấp xỉ Bayes thực dụng&lt;/h3&gt;

&lt;p&gt;Deep ensemble — huấn luyện nhiều mạng độc lập từ các điểm khởi tạo khác nhau — vẫn là chuẩn đối chiếu mạnh về ước lượng bất định trong công nghiệp. Wilson và Izmailov lập luận rằng phương pháp này có thể được hiểu như xấp xỉ một phân phối hỗn hợp quanh nhiều đỉnh (mode) của hậu nghiệm. Dù không thay thế được MCMC chuẩn như trong khảo sát của Izmailov et al. (2021), deep ensemble là cách thực dụng để nắm bắt sự đa dạng của hậu nghiệm khi HMC không khả thi về mặt tính toán. Nhìn nhận ensemble như nhiều nghiệm MAP dưới một tiên nghiệm ẩn rồi lấy trung bình dự báo vẫn giữ trọn tinh thần Chương 7: giảm phương sai bằng cách không đặt toàn bộ niềm tin vào một ước lượng điểm duy nhất.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-học-sâu-bayes-bất-định-aleatoric-vs-epistemic-trên-vùng-lạ-ood&quot;&gt;Video ngắn: Học sâu Bayes: Bất định Aleatoric vs Epistemic trên Vùng lạ OOD&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch07-04a-bdl-aleatoric-epistemic.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 15 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): minh họa 5 mô hình đồng thuận cao trong vùng đã học (ID) và tách rẽ mạnh ngoài phân phối (OOD) để cảnh báo khi AI đang đoán mò.&lt;/p&gt;

&lt;h2 id=&quot;diễn-giải-và-nhận-định&quot;&gt;Diễn giải và nhận định&lt;/h2&gt;

&lt;p&gt;Một xấp xỉ Laplace hẹp quanh nghiệm MAP có thể bỏ sót các mode khác của hậu nghiệm. Một mô hình Bayes lớp cuối vẫn có thể tự tin sai lầm nếu không gian đặc trưng phía trước bị suy biến (feature collapse). Ngay cả khi các mô hình trong một ensemble đồng thuận với nhau, điều đó không chứng minh giả thuyết là đúng vì chúng có thể cùng chia sẻ một sai số hệ thống. Phân phối tiên nghiệm chỉ phát huy đúng tác dụng khi giúp mô hình &lt;em&gt;dè dặt hơn&lt;/em&gt; trên những vùng dữ liệu thưa, chứ không phải khi giữ độ tự tin luôn ở mức cao.&lt;/p&gt;

&lt;h2 id=&quot;ứng-dụng&quot;&gt;Ứng dụng&lt;/h2&gt;

&lt;p&gt;Chấm điểm dữ liệu bảng, phát hiện dữ liệu ngoài phân phối (out-of-distribution) và ước lượng độ bất định trong các mạng phân loại là ba lĩnh vực mà điều chuẩn Bayes đã trở thành kỹ thuật triển khai thực tế.&lt;/p&gt;

&lt;h2 id=&quot;giới-hạn-và-hướng-mở-rộng&quot;&gt;Giới hạn và hướng mở rộng&lt;/h2&gt;

&lt;p&gt;Xấp xỉ Laplace chỉ có giá trị cục bộ. VBLL giả định lớp cuối tuyến tính trên bộ đặc trưng cố định. Deep ensemble làm tăng chi phí huấn luyện theo số lượng mô hình thành phần. Không có phương pháp nào thay thế được nhu cầu kiểm chứng mô hình sẽ trình bày ở Chương 8. Bài học này không nhằm mở rộng thành một chương riêng về học sâu, mà chỉ cho thấy cách tư duy về tiên nghiệm từ bài 7.1 đã đi vào các kiến trúc mạng hiện đại theo những hướng tiếp cận thực dụng.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tách-độ-bất-định-aleatoric-và-epistemic-bằng-định-luật-tổng-phương-sai&quot;&gt;Giải thích: Tách độ bất định Aleatoric và Epistemic bằng định luật tổng phương sai&lt;/h2&gt;

&lt;p&gt;Với một tổ hợp gồm \(M\) mô hình (từ mẫu MCMC, MC Dropout hoặc Deep Ensemble), mỗi mô hình \(m\) dự đoán một trung bình \(\mu_m\) và một phương sai nhiễu dữ liệu \(\sigma_m^2\). Ta tách tổng bất định dự báo theo đúng định luật tổng phương sai (&lt;em&gt;Law of Total Variance&lt;/em&gt;):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Trung bình dự báo chung:&lt;/strong&gt; \(\bar\mu = \frac{1}{M}\sum_{m=1}^M \mu_m\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bất định Aleatoric (nhiễu dữ liệu trung bình):&lt;/strong&gt; \(\sigma_{\text{ale}}^2 = \frac{1}{M}\sum_{m=1}^M \sigma_m^2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bất định Epistemic (độ bất đồng giữa các mô hình):&lt;/strong&gt; \(\sigma_{\text{epi}}^2 = \frac{1}{M}\sum_{m=1}^M (\mu_m - \bar\mu)^2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng phương sai dự báo:&lt;/strong&gt; \(\sigma_{\text{total}}^2 = \sigma_{\text{ale}}^2 + \sigma_{\text{epi}}^2\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-so-sánh-ảnh-trong-phân-phối-id-và-ảnh-lạ-ngoài-phân-phối-ood&quot;&gt;Ví dụ tính toán làm từng bước: So sánh ảnh trong phân phối (ID) và ảnh lạ ngoài phân phối (OOD)&lt;/h3&gt;

&lt;p&gt;Giả sử một Deep Ensemble gồm \(M = 3\) mạng dự đoán độ tuổi sinh học trên hai ca (A: dữ liệu quen thuộc; B: dữ liệu lạ ngoài phân phối):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Ca dự đoán&lt;/th&gt;
      &lt;th&gt;Dự báo \((\mu_1, \mu_2, \mu_3)\)&lt;/th&gt;
      &lt;th&gt;Phương sai nhiễu \((\sigma_1^2, \sigma_2^2, \sigma_3^2)\)&lt;/th&gt;
      &lt;th&gt;\(\sigma_{\text{ale}}^2\)&lt;/th&gt;
      &lt;th&gt;\(\sigma_{\text{epi}}^2\)&lt;/th&gt;
      &lt;th&gt;Tổng \(\mathrm{SD} = \sqrt{\sigma_{\text{ale}}^2 + \sigma_{\text{epi}}^2}\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Ca A (quen thuộc)&lt;/td&gt;
      &lt;td&gt;\((40, 41, 39)\)&lt;/td&gt;
      &lt;td&gt;\((4.0, 4.0, 4.0)\)&lt;/td&gt;
      &lt;td&gt;\(4.00\)&lt;/td&gt;
      &lt;td&gt;\(\frac{0+1+1}{3} \approx 0.67\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{4.67} \approx 2.16\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Ca B (ngoài phân phối)&lt;/td&gt;
      &lt;td&gt;\((30, 40, 50)\)&lt;/td&gt;
      &lt;td&gt;\((4.0, 4.0, 4.0)\)&lt;/td&gt;
      &lt;td&gt;\(4.00\)&lt;/td&gt;
      &lt;td&gt;\(\frac{100+0+100}{3} \approx 66.67\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{70.67} \approx 8.41\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Ở Ca B, dù trung bình dự báo vẫn là \(40\) và nhiễu dữ liệu \(\sigma_{\text{ale}}^2 = 4.0\) không đổi, bất định epistemic tăng vọt gấp &lt;strong&gt;100 lần&lt;/strong&gt; (từ \(0.67\) lên \(66.67\)) — tín hiệu rõ ràng để hệ thống từ chối tự động ra quyết định và chuyển cho chuyên gia kiểm tra.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhầm rằng giá trị xác suất &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;softmax&lt;/code&gt; cao (ví dụ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.98&lt;/code&gt;) của một mạng nơ-ron chuẩn đồng nghĩa với độ chắc chắn cao trên ảnh ngoài phân phối. Mạng nơ-ron điểm thường rất tự tin sai trên dữ liệu lạ nếu không có cơ chế ước lượng bất định epistemic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu ta thu thập thêm rất nhiều dữ liệu huấn luyện quanh vùng của Ca B, thành phần nào sẽ giảm về gần 0? Chính là \(\sigma_{\text{epi}}^2\) (về gần 0), còn \(\sigma_{\text{ale}}^2 = 4.00\) vẫn giữ nguyên.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=RckG_kNv1Kc&quot;&gt;The Bayesian interpretation of weight decay 43 Machine Learning&lt;/a&gt; — Professor tutorials, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giải thích weight decay dưới góc nhìn tiên nghiệm trên trọng số, nối trực tiếp điều chuẩn với mạng nơ-ron.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dj-FKXxy7HQ&quot;&gt;Uncertainty estimation and Bayesian Neural Networks - Marcin Możejko&lt;/a&gt; — PyData, English. Trình bày ước lượng bất định bằng mạng nơ-ron Bayes, củng cố vai trò của tiên nghiệm đối với các mô hình có độ linh hoạt cao.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=veYq6EWZyVc&quot;&gt;MIT 6.S191: Uncertainty in Deep Learning&lt;/a&gt; — Alexander Amini, English. Giới thiệu các phương pháp lượng hóa bất định trong học sâu, bao gồm họ phương pháp ensemble.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Biểu diễn lại weight decay dưới dạng một phân phối tiên nghiệm. Khi giảm \(\tau\), bạn đang đặt giả định gì về hàm sinh dữ liệu và chấp nhận loại độ lệch (bias) nào?&lt;/li&gt;
  &lt;li&gt;Một nhóm kỹ sư chỉ áp dụng suy luận Bayes ở lớp cuối để tiết kiệm chi phí tính toán. Dựa trên kết quả của Sharma et al. (2023), hãy lập luận khi nào cách làm này là đủ và khi nào các tầng đặc trưng xác định sẽ che giấu độ bất định.&lt;/li&gt;
  &lt;li&gt;So sánh tiên nghiệm horseshoe trên 20 biến dự báo với dropout trên một mạng nơ-ron: thành phần nào đang được co rút, và thành phần nào đang được che giấu dưới dạng thủ thuật tối ưu?&lt;/li&gt;
  &lt;li&gt;Laplace Redux sử dụng ma trận Hessian tại nghiệm MAP. Hãy mô tả một phân phối hậu nghiệm có hai mode và giải thích xấp xỉ Laplace sẽ bỏ sót điều gì.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 14–15.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 17–18.&lt;/li&gt;
  &lt;li&gt;Daxberger, E., et al. (2021). Laplace Redux — effortless Bayesian deep learning. &lt;em&gt;NeurIPS&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Harrison, J., Willes, J., &amp;amp; Snoek, J. (2024). Variational Bayesian last layers. &lt;em&gt;ICLR&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2404.11599&quot;&gt;arXiv:2404.11599&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Sharma, M., Farquhar, S., Nalisnick, E., &amp;amp; Rainforth, T. (2023). Do Bayesian neural networks need to be fully stochastic? &lt;em&gt;AISTATS&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2211.06291&quot;&gt;arXiv:2211.06291&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Izmailov, P., Vikram, S., Hoffman, M. D., &amp;amp; Wilson, A. G. (2021). What are Bayesian neural network posteriors really like? &lt;em&gt;ICML&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 6.4: Ứng dụng hiện đại của GLM Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter06/06_04_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter06/06_04_modern_applications</id>
   <content type="html">&lt;p&gt;Hồi quy logistic và hồi quy Poisson Bayes không hề là những mô hình “cũ kỹ” bị học sâu thay thế: trong bảo hiểm định phí (actuarial pricing), dịch tễ học y khoa, hệ thống chấm điểm tín dụng và mô hình quảng cáo trực tuyến quy mô hàng tỷ lượt hiển thị, &lt;strong&gt;GLM Bayes&lt;/strong&gt; (đặc biệt khi kết hợp cấu trúc phân cấp) vẫn là tiêu chuẩn vàng nhờ ba ưu thế hiếm có: diễn giải được từng hệ số, định lượng trọn vẹn bất định và ổn định ngay cả khi dữ liệu theo phân khúc bị thưa.&lt;/p&gt;

&lt;p&gt;Bài tổng kết Chương 6 này trình bày cách GLM Bayes vận hành trong các hệ thống hiện đại và cách kết hợp nó với các kỹ thuật mở rộng như hồi quy phân cấp và spline phi tuyến.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài học tùy chọn này, bạn sẽ biết cách lựa chọn một mô hình GLM Bayes xuất phát từ &lt;em&gt;câu chuyện sinh dữ liệu của biến kết quả&lt;/em&gt;, thay vì mặc định áp dụng hồi quy tuyến tính cho mọi bài toán. Bạn cũng sẽ nhận ra cách hồi quy logistic, hồi quy Poisson và các họ mô hình liên quan đang được triển khai trong tín dụng, dịch tễ học và đo lường marketing, đồng thời hiểu rằng phân phối hậu nghiệm của xác suất hay cường độ đếm cần được kết hợp với chi phí quyết định.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-glm-bayes-trong-định-phí-dịch-tễ-và-hệ-thống-quảng-cáo&quot;&gt;Kiến thức cần nhớ: GLM Bayes trong Định phí, Dịch tễ và Hệ thống Quảng cáo&lt;/h2&gt;

&lt;p&gt;Ba trụ cột ứng dụng cho thấy sức mạnh thực tiễn của GLM Bayes:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình hai phần cho dữ liệu có cấu trúc phức tạp (Hurdle &amp;amp; Zero-Inflated GLMs):&lt;/strong&gt; Dữ liệu chi phí bảo hiểm hoặc mua hàng thường có tỷ lệ số 0 rất lớn. Các hệ thống hiện đại ghép một mô hình Logistic (xác suất có phát sinh sự kiện) với một mô hình Gamma hoặc Negative Binomial (độ lớn khi có sự kiện).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GLM phân cấp (Hierarchical GLMs):&lt;/strong&gt; Trong dự đoán tỷ lệ nhấp chuột (CTR) hay tỷ lệ tái nhập viện theo từng bệnh viện, GLM Bayes phân cấp chia sẻ thông tin giữa các nhóm ít dữ liệu và nhiều dữ liệu (&lt;em&gt;partial pooling&lt;/em&gt;), giảm mạnh sai số dự báo.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu chuẩn xác suất cho ra quyết định tự động:&lt;/strong&gt; Vì GLM Bayes xuất ra toàn bộ phân phối hậu nghiệm của xác suất/tốc độ, hệ thống có thể tính trực tiếp xác suất vượt ngưỡng rủi ro thay vì chỉ dùng điểm ước lượng đơn lẻ.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-có&quot;&gt;Kiến thức cần có&lt;/h2&gt;

&lt;p&gt;Các bài 6.1–6.3 đã trình bày hồi quy logistic, hồi quy Poisson và đánh giá GLM. Bài học này không nhắc lại các hàm liên kết, mà kết nối trực tiếp những mô hình đó với các hệ thống ứng dụng thực tế giai đoạn 2022–2026.&lt;/p&gt;

&lt;h2 id=&quot;mở-đầu&quot;&gt;Mở đầu&lt;/h2&gt;

&lt;p&gt;Chương 6 ra đời vì giả định phân phối Gaussian của Chương 4 không phù hợp với dữ liệu nhị phân và dữ liệu đếm. Trong thực tế triển khai sản phẩm, hạn chế này xuất hiện ngay ở các bài toán quen thuộc: một giao dịch có vỡ nợ hay không, số đơn hàng phát sinh trong một giờ, hay số ca bệnh bị báo cáo trễ. Nếu vẫn tối ưu bình phương tối thiểu, ta đang áp đặt một cơ chế sinh dữ liệu không phù hợp với bản chất của quan sát. Vấn đề cốt lõi của bài học này là chọn đúng họ phân phối cho dữ liệu quan sát trước khi nghĩ đến mạng nơ-ron sâu hay hạ tầng đặc trưng phức tạp.&lt;/p&gt;

&lt;h2 id=&quot;phát-triển-khái-niệm&quot;&gt;Phát triển khái niệm&lt;/h2&gt;

&lt;p&gt;Một mô hình GLM Bayes giữ cấu trúc tuyến tính trên một thang đo phù hợp:&lt;/p&gt;

\[g(\mathbb E[y_i\mid x_i])=x_i^\top\beta,\]

&lt;p&gt;sau đó đặt phân phối tiên nghiệm lên \(\beta\) và suy luận phân phối hậu nghiệm. Với hồi quy logistic, \(g\) là hàm logit và \(y\) tuân theo phân phối Bernoulli. Với hồi quy Poisson, \(g\) là hàm log và \(y\) là dữ liệu đếm. Phân phối hậu nghiệm không trực tiếp trả về một nhãn phân lớp cứng, mà trả về một phân phối xác suất cho xác suất sự kiện hoặc cường độ đếm. Ngưỡng phân loại chỉ xuất hiện ở bước sau, khi hàm mất mát xác định rõ chi phí của dương tính giả so với âm tính giả.&lt;/p&gt;

&lt;h2 id=&quot;mô-hình-như-câu-chuyện-sinh-dữ-liệu&quot;&gt;Mô hình như câu chuyện sinh dữ liệu&lt;/h2&gt;

&lt;h3 id=&quot;1-hồi-quy-logistic-bayes-cho-tín-dụng-gian-lận-và-rủi-ro-lâm-sàng&quot;&gt;1. Hồi quy logistic Bayes cho tín dụng, gian lận và rủi ro lâm sàng&lt;/h3&gt;

&lt;p&gt;Trong câu chuyện sinh dữ liệu, mỗi hồ sơ có một xác suất xảy ra sự kiện hiếm là \(\theta(x)=\mathrm{logit}^{-1}(x^\top\beta)\), và nhãn quan sát được sinh ra như phép thử Bernoulli với xác suất đó. Phân phối tiên nghiệm trên \(\beta\) giúp xác suất không bị đẩy cực đoan về 0 hoặc 1 khi gặp một tổ hợp đặc trưng chưa từng xuất hiện — đúng với tinh thần điều chuẩn (regularization) sẽ được trình bày ở Chương 7. Trong thực tế, điều doanh nghiệp cần từ phân phối hậu nghiệm không chỉ là độ chính xác phân lớp cao nhất, mà là một xác suất đã được hiệu chỉnh để làm cơ sở đặt hạn mức, tính phí bảo hiểm hoặc thiết lập ngưỡng phê duyệt. Nghiên cứu của Grinsztajn, Oyallon và Varoquaux (2022) cho thấy trên nhiều tập dữ liệu dạng bảng không đồng nhất, các mô hình nông vẫn vượt trội hơn mạng học sâu; do đó một mô hình logistic Bayes được đặc tả tốt vẫn là lựa chọn rất phù hợp.&lt;/p&gt;

&lt;h3 id=&quot;2-hồi-quy-poisson-và-negative-binomial-cho-dự-báo-nhu-cầu-và-nowcasting&quot;&gt;2. Hồi quy Poisson và Negative Binomial cho dự báo nhu cầu và nowcasting&lt;/h3&gt;

&lt;p&gt;Số đơn hàng, số cuộc gọi và số ca bệnh theo ngày đều là dữ liệu đếm. Mô hình Poisson giả định phương sai bằng trung bình, nhưng dữ liệu dịch tễ và thương mại thường cần mô hình Negative Binomial để xử lý hiện tượng quá phân tán. Trong bối cảnh dịch bệnh, bài toán ước lượng hiện thời (nowcasting) phải vừa ước lượng cường độ dịch vừa hiệu chỉnh độ trễ khai báo. Mô hình Bayes phân cấp theo các khu vực địa lý thực chất là mở rộng của GLM ở Chương 6 với hệ số chặn thay đổi theo nhóm. Phân phối dự báo hậu nghiệm cho tuần kế tiếp không chỉ là một con số duy nhất, mà là một dải bất định giúp kho vận và bệnh viện lập kế hoạch dự phòng.&lt;/p&gt;

&lt;h3 id=&quot;3-media-mix-modeling-như-một-glm-nhân-quả-có-tiên-nghiệm&quot;&gt;3. Media mix modeling như một GLM nhân quả có tiên nghiệm&lt;/h3&gt;

&lt;p&gt;Google Meridian (2024) là một khung mô hình hóa hỗn hợp tiếp thị (marketing mix modeling) theo hướng Bayes: doanh số được mô hình hóa như hàm của các kênh truyền thông đã qua biến đổi trễ quảng cáo (adstock) và lợi suất giảm dần, kết hợp với các yếu tố ngoài truyền thông, cùng phân phối tiên nghiệm có thể hiệu chỉnh bằng kết quả thí nghiệm. Việc suy luận sử dụng MCMC/NUTS. Hàm hợp lý gần với hồi quy chuẩn, nhưng tinh thần vẫn là GLM mở rộng với các biến đổi phi tuyến của mức độ phơi nhiễm. Tài liệu của Meridian nhấn mạnh mục tiêu chính là suy luận nhân quả về ROI, chứ không phải tối thiểu hóa sai số dự báo trên tập kiểm tra (hold-out) — điều này nhắc lại phân biệt quan trọng từ Chương 5 và 6 rằng cùng một họ mô hình có thể phục vụ hai câu hỏi khác nhau.&lt;/p&gt;

&lt;h3 id=&quot;4-đánh-giá-glm-ưu-tiên-độ-hiệu-chỉnh-trước-nhãn-cứng&quot;&gt;4. Đánh giá GLM: ưu tiên độ hiệu chỉnh trước nhãn cứng&lt;/h3&gt;

&lt;p&gt;Bài 6.3 đã lưu ý rằng ma trận nhầm lẫn không trung tính về chi phí. Trong tín dụng, bỏ sót một khoản vay vỡ nợ thường tốn kém hơn từ chối nhầm một khách hàng tốt. Trong dịch tễ học, bỏ sót một ổ dịch nghiêm trọng hơn cảnh báo thừa. Vì vậy, phân phối hậu nghiệm của \(\theta(x)\) cần được kiểm tra bằng biểu đồ độ tin cậy (reliability diagram), thay vì chỉ dựa vào accuracy. Một mô hình GLM có độ phân tách vừa phải nhưng hiệu chỉnh tốt vẫn có thể dẫn đến quyết định hợp lý hơn.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-mô-hình-hai-phần-logistic--poisson-dự-báo-doanh-thu-kỳ-vọng&quot;&gt;Video ngắn: Mô hình Hai phần (Logistic + Poisson): Dự báo Doanh thu Kỳ vọng&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch06-04a-two-part-hurdle-glm.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 15 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): kết hợp xác suất mua hàng p = 25% (Logistic) với số đơn kỳ vọng λ = 3.2 (Poisson) thành doanh thu kỳ vọng 160k/khách trong bài toán TMĐT.&lt;/p&gt;

&lt;h2 id=&quot;diễn-giải-và-nhận-định&quot;&gt;Diễn giải và nhận định&lt;/h2&gt;

&lt;p&gt;Hệ số trong hồi quy logistic biểu thị mức thay đổi trên thang log-odds, không phải mức thay đổi cố định trên thang xác suất. Hệ số trong hồi quy Poisson biểu thị mức thay đổi trên thang log-cường độ. Khoảng hậu nghiệm của ROI truyền thông đã gộp chung độ bất định của hiệu ứng adstock, các biến nhiễu và quá trình lấy mẫu. Tuy nhiên, không một khoảng hậu nghiệm nào tự động trở thành quyết định cho đến khi hàm mất mát được xác định rõ.&lt;/p&gt;

&lt;h2 id=&quot;ứng-dụng&quot;&gt;Ứng dụng&lt;/h2&gt;

&lt;p&gt;Phê duyệt tín dụng, phát hiện gian lận, dự báo nhu cầu, nowcasting và phân bổ ngân sách quảng cáo là năm lĩnh vực mà GLM Bayes đã trở thành thành phần vận hành thực tế, không còn dừng ở ví dụ trong sách giáo khoa.&lt;/p&gt;

&lt;h2 id=&quot;giới-hạn-và-hướng-mở-rộng&quot;&gt;Giới hạn và hướng mở rộng&lt;/h2&gt;

&lt;p&gt;Meridian lưu ý rằng hiệu năng dự báo tốt trên tập hold-out không chứng minh ước lượng hiệu ứng truyền thông là đúng. Hồi quy Poisson sẽ kém phù hợp khi dữ liệu có quá nhiều giá trị 0 (zero-inflation). Hồi quy logistic tuyến tính cũng không tự nắm bắt được các tương tác phức tạp nếu ta không chủ động đưa chúng vào mô hình. Chương 7 sẽ tiếp tục đặt câu hỏi nên chọn phân phối tiên nghiệm nào để giữ mô hình GLM khỏi quá khớp khi số lượng biến giải thích tăng lên.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tính-lợi-ích-kỳ-vọng-từ-một-dự-báo-glm-bayes-trong-bài-toán-thực-tế&quot;&gt;Giải thích: Tính lợi ích kỳ vọng từ một dự báo GLM Bayes trong bài toán thực tế&lt;/h2&gt;

&lt;p&gt;Trong ứng dụng sản phẩm, đầu ra của GLM Bayes hiếm khi dừng ở bảng hệ số; nó được đưa thẳng vào phương trình kỳ vọng giá trị theo 3 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Dự báo xác suất sự kiện \(p_i\)&lt;/strong&gt; (từ mô hình Logistic) và &lt;strong&gt;mức độ tác động \(v_i\)&lt;/strong&gt; (từ mô hình Gamma/Poisson hoặc giá trị nghiệp vụ).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính giá trị kỳ vọng có điều kiện&lt;/strong&gt; \(\mathbb{E}[\text{Giá trị}] = p_i \cdot v_i\) trên từng mẫu hậu nghiệm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh với chi phí hành động \(C\)&lt;/strong&gt; và chỉ hành động khi lợi ích ròng kỳ vọng dương (hoặc xác suất sinh lời vượt ngưỡng an toàn).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-mô-hình-hai-phần-logistic--poisson-ước-lượng-doanh-thu-kỳ-vọng&quot;&gt;Ví dụ tính toán làm từng bước: Mô hình hai phần (Logistic + Poisson) ước lượng doanh thu kỳ vọng&lt;/h3&gt;

&lt;p&gt;Một sàn thương mại điện tử dùng GLM hai phần để ước lượng số đơn hàng kỳ vọng trong tháng tới của một phân khúc khách hàng mới:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Thành phần Logistic ước lượng xác suất khách hàng có mua ít nhất 1 đơn là \(p_{\text{mua}} = 0.35\) (với khoảng tin cậy 95%: \([0.25, 0.45]\)).&lt;/li&gt;
  &lt;li&gt;Thành phần Poisson cắt cụt (hoặc trung bình số đơn khi đã mua) ước lượng \(\lambda_{\text{khi mua}} = 2.4\) đơn, giá trị trung bình mỗi đơn là \(500\text{ nghìn VNĐ}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Bước tính&lt;/th&gt;
      &lt;th&gt;Công thức&lt;/th&gt;
      &lt;th&gt;Giá trị ước lượng&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Số đơn kỳ vọng mỗi khách&lt;/td&gt;
      &lt;td&gt;\(p_{\text{mua}} \times \lambda_{\text{khi mua}}\)&lt;/td&gt;
      &lt;td&gt;\(0.35 \times 2.4 = 0.84\text{ đơn}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Doanh thu kỳ vọng mỗi khách&lt;/td&gt;
      &lt;td&gt;\(0.84 \times 500\text{ nghìn}\)&lt;/td&gt;
      &lt;td&gt;\(420\text{ nghìn VNĐ}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Ngưỡng chi phí marketing tối đa (nếu biên lợi nhuận 20%)&lt;/td&gt;
      &lt;td&gt;\(0.20 \times 420\text{ nghìn}\)&lt;/td&gt;
      &lt;td&gt;\(84\text{ nghìn VNĐ/khách}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Dùng một mô hình hồi quy tuyến tính Gaussian duy nhất cho dữ liệu có 65% giá trị bằng 0 — kết quả vừa dự báo số âm vô nghĩa vừa bỏ sót cơ chế tách biệt giữa “có mua hay không” và “mua bao nhiêu”.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu ta xét kịch bản thận trọng ở cận dưới 95% của xác suất mua (\(p_{\text{mua}} = 0.25\)), doanh thu kỳ vọng giảm xuống \(0.25 \times 2.4 \times 500 = 300\text{ nghìn VNĐ}\), kéo ngân sách marketing an toàn xuống \(60\text{ nghìn VNĐ/khách}\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Explaining generalized linear models (GLMs)&lt;/td&gt;
          &lt;td&gt;VNT #15](https://www.youtube.com/watch?v=1fZeBafD1nw) — Very Normal, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giải thích cách chọn GLM theo kiểu biến kết quả, thay cho thói quen dùng hồi quy tuyến tính cho mọi bài toán.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=J4zNmGqttVo&quot;&gt;GLM Intro - 4 - Link Function&lt;/a&gt; — Meerkat Statistics, English. Trình bày vai trò của hàm liên kết trong việc nối kỳ vọng của biến kết quả với phần dự báo tuyến tính, hỗ trợ cho logistic và Poisson trong thực tế.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zffwg0xDOgE&quot;&gt;Statistical Rethinking 2023 - 19 - Generalized Linear Madness&lt;/a&gt; — Richard McElreath, English. Phân tích các biến thể GLM ngoài khuôn mẫu sách giáo khoa, mở rộng góc nhìn về các họ mô hình gần logistic và Poisson.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Một mô hình dự đoán vỡ nợ đạt accuracy 98% do chỉ có 2% hồ sơ thực sự vỡ nợ. Trung bình hậu nghiệm của \(\theta(x)\) trên nhóm rủi ro cao là 0.15. Vì sao chỉ số accuracy đang che khuất đúng đối tượng mà GLM Bayes quan tâm?&lt;/li&gt;
  &lt;li&gt;Viết câu chuyện sinh dữ liệu cho số đơn hàng mỗi giờ tại một nhà kho. Khi nào bạn nên chuyển từ Poisson sang Negative Binomial, và phân phối dự báo hậu nghiệm sẽ thay đổi hình dạng như thế nào?&lt;/li&gt;
  &lt;li&gt;Tài liệu Meridian khuyến nghị không lấy sai số dự báo trên tập hold-out làm tiêu chí chính. Hãy liên hệ khuyến nghị này với sự khác biệt giữa dự báo và suy luận nhân quả ở Chương 5.&lt;/li&gt;
  &lt;li&gt;Hãy chọn một ngưỡng cho mô hình hồi quy logistic khi chi phí âm tính giả cao gấp mười lần dương tính giả. Ngoài ước lượng điểm \(\hat\beta\), bạn cần thêm thông tin nào từ phân phối hậu nghiệm?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 16.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 21–22.&lt;/li&gt;
  &lt;li&gt;Grinsztajn, L., Oyallon, E., &amp;amp; Varoquaux, G. (2022). Why do tree-based models still outperform deep learning on typical tabular data? &lt;em&gt;NeurIPS&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Google. (2024). &lt;em&gt;Meridian&lt;/em&gt;: Bayesian marketing mix modeling. &lt;a href=&quot;https://developers.google.com/meridian/docs/causal-inference/bayesian-inference&quot;&gt;Bayesian inference&lt;/a&gt;; &lt;a href=&quot;https://github.com/google/meridian&quot;&gt;GitHub&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://mc-stan.org/docs/stan-users-guide/index.html&quot;&gt;Stan User’s Guide, GLM chapters&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.pymc.io/projects/docs/en/stable/learn/core_notebooks/GLM_linear.html&quot;&gt;PyMC GLM examples&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 5.5: Ứng dụng hiện đại của hồi quy đa biến và tư duy nhân quả</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter05/05_05_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter05/05_05_modern_applications</id>
   <content type="html">&lt;p&gt;Trong kỷ nguyên dữ liệu lớn, nhiều đội ngũ kỹ thuật tin vào một trực giác nghe có vẻ rất an toàn: “cứ đổ tất cả các cột dữ liệu có sẵn vào mô hình hồi quy hoặc mạng nơ-ron, thuật toán sẽ tự lọc cái gì quan trọng”. Thế nhưng làn sóng nghiên cứu suy luận nhân quả giai đoạn 2022–2026 đã chứng minh điều ngược lại: khi bạn có 10 triệu dòng dữ liệu, một biến kiểm soát đặt sai chỗ không hề tự biến mất — nó chỉ làm &lt;strong&gt;khoảng tin cậy quanh kết luận sai co lại đến mức trông như chân lý tuyệt đối&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài tùy chọn này, bạn sẽ biết cách đọc hệ số trong mô hình nhiều biến dự báo như một phát biểu nhân quả có điều kiện, thay vì đánh giá tầm quan trọng chỉ dựa vào dấu sao ý nghĩa thống kê trên bảng kết quả. Bạn cũng sẽ thấy hiện tượng gây nhiễu (confounding), đa cộng tuyến và hiệu ứng tương tác không phải là “lỗi” của hồi quy, mà là đặc trưng tự nhiên của dữ liệu ứng dụng hiện đại như thử nghiệm A/B trên nền tảng thị trường (marketplace), hệ gợi ý và hồ sơ y tế dọc theo thời gian.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-biến-kiểm-soát-tốtxấu-học-cấu-trúc-đồ-thị-và-gây-nhiễu-theo-thời-gian&quot;&gt;Kiến thức cần nhớ: Biến kiểm soát tốt/xấu, Học cấu trúc đồ thị và Gây nhiễu theo thời gian&lt;/h2&gt;

&lt;p&gt;Ba chủ đề hiện đại của bài học là sự mở rộng trực tiếp các khái niệm Chương 5 lên hệ thống dữ liệu quy mô lớn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hệ phân loại Good &amp;amp; Bad Controls (Cinelli–Forney–Pearl):&lt;/strong&gt; Việc thêm một hiệp biến \(Z\) vào hồi quy có thể làm giảm thiên lệch (nếu \(Z\) đóng đường cửa sau), giữ nguyên thiên lệch nhưng tăng phương sai (nếu \(Z\) chỉ gây nhiễu cho \(X\) — biến công cụ), hoặc &lt;em&gt;tạo ra thiên lệch mới&lt;/em&gt; (nếu \(Z\) là biến trung gian hoặc collider).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học cấu trúc DAG bằng tối ưu liên tục (DAGMA):&lt;/strong&gt; Thay vì duyệt tổ hợp siêu mũ qua mọi đồ thị có hướng, các thuật toán hiện đại biểu diễn ma trận kề có trọng số \(W\) với ràng buộc đại số trơn \(h(W) = -\log\det(sI - W \circ W) + d\log s = 0\) để đảm bảo không chu trình, song kết quả vẫn bị giới hạn bởi tính tương đương Markov (&lt;em&gt;Markov equivalence class&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gây nhiễu biến thiên theo thời gian (Time-varying Confounding):&lt;/strong&gt; Trong y tế dọc (như MIMIC) hay nền tảng số, điều trị ở ngày \(t\) ảnh hưởng đến chỉ số sức khỏe ngày \(t+1\), và chỉ số ấy lại quyết định liều điều trị ngày \(t+2\) — vừa là biến trung gian cho quá khứ vừa là biến gây nhiễu cho tương lai, đòi hỏi các kiến trúc chuyên biệt như Causal Transformer.
    &lt;h2 id=&quot;kiến-thức-cần-có&quot;&gt;Kiến thức cần có&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Các bài 5.1–5.4 đã trình bày hồi quy đa biến, DAG, đa cộng tuyến và hiệu ứng tương tác. Bài này không nhắc lại định nghĩa đường cửa sau (backdoor), mà đặt chính những khái niệm đó vào các nghiên cứu và hệ thống thực tế giai đoạn 2022–2026.&lt;/p&gt;

&lt;h2 id=&quot;mở-đầu&quot;&gt;Mở đầu&lt;/h2&gt;

&lt;p&gt;Chương 5 mở ra từ một tình huống quen thuộc: thêm biến mới có thể làm tăng \(R^2\), nhưng lại làm sai lệch câu chuyện về tác động nhân quả. Trong khoa học máy tính và sản phẩm số, cái giá của sai lầm này còn lớn hơn. Một nền tảng có thể đưa hàng trăm đặc trưng (feature) vào mô hình xếp hạng rồi cho rằng mình đã “kiểm soát mọi thứ”. Nếu trong số đó có biến trung gian hoặc collider, hệ số của biến can thiệp sẽ không còn phản ánh đúng hiệu ứng mục tiêu. Thông điệp xuyên suốt bài này là: tập dữ liệu càng nhiều cột thì đồ thị nhân quả DAG càng cần thiết, chứ không hề thừa.&lt;/p&gt;

&lt;h2 id=&quot;phát-triển-khái-niệm&quot;&gt;Phát triển khái niệm&lt;/h2&gt;

&lt;p&gt;Trong phương trình hồi quy đa biến:&lt;/p&gt;

\[y_i=\alpha+\sum_j\beta_j x_{ij}+\varepsilon_i\]

&lt;p&gt;hệ số \(\beta_j\) chỉ mang ý nghĩa nhân quả khi tập biến kiểm soát đã chặn được toàn bộ các đường cửa sau mà không mở ra đường phi nhân quả mới. Cinelli, Forney và Pearl (2022) hệ thống hóa vấn đề này dưới khái niệm &lt;em&gt;good and bad controls&lt;/em&gt;: không phải mọi hiệp biến có liên quan đều nên đưa vào phương trình. Trong khi đó, hiệu ứng tương tác cho thấy bản thân \(\beta_j\) có thể là hàm theo một biến khác; còn đa cộng tuyến không gây thiên lệch nhân quả mà làm mở rộng bất định hậu nghiệm khi nhiều cột cùng phản ánh một nguồn thông tin.&lt;/p&gt;

&lt;h2 id=&quot;mô-hình-trong-các-hệ-thống-hiện-đại&quot;&gt;Mô hình trong các hệ thống hiện đại&lt;/h2&gt;

&lt;h3 id=&quot;1-biến-kiểm-soát-đúng-và-sai-good-and-bad-controls-trong-thử-nghiệm-sản-phẩm&quot;&gt;1. Biến kiểm soát đúng và sai (Good and Bad Controls) trong thử nghiệm sản phẩm&lt;/h3&gt;

&lt;p&gt;Cơ chế sinh dữ liệu của một thử nghiệm A/B trên nền tảng thị trường (marketplace) thường chứa sẵn yếu tố gây nhiễu do hành vi chủ động của người dùng và tương tác cung – cầu hai phía. Đưa biến “số lượt nhấp sau khi thấy biến thể” vào mô hình phân tích doanh thu là một biến kiểm soát sai (bad control) nếu lượt nhấp nằm trên con đường nhân quả từ can thiệp tới doanh thu. Cinelli et al. (2022) cung cấp một hệ thống các DAG mẫu cho thấy trực giác “kiểm soát càng nhiều càng sạch” dễ thất bại ra sao. Thực hành đúng là vẽ DAG trước khi chọn đặc trưng từ kho dữ liệu, rồi mới xác định mô hình hồi quy Bayes cần điều kiện hóa trên tập biến nào.&lt;/p&gt;

&lt;h3 id=&quot;2-học-cấu-trúc-dag-từ-dữ-liệu-và-giới-hạn-của-tối-ưu-hóa&quot;&gt;2. Học cấu trúc DAG từ dữ liệu và giới hạn của tối ưu hóa&lt;/h3&gt;

&lt;p&gt;Bello, Aragam và Ravikumar (2022) chuyển bài toán học DAG thành một bài toán tối ưu liên tục (DAGMA) bằng đặc trưng không chu trình dựa trên log-determinant của ma trận M. Đây là bước tiến đáng chú ý về mặt thuật toán: thay vì chỉ giả định đồ thị, ta tìm cách ước lượng nó từ dữ liệu. Tuy vậy, cách tiếp cận này vẫn phụ thuộc vào các giả định sinh dữ liệu cụ thể — thường là mô hình phương trình cấu trúc cộng tính với nhiễu độc lập. Một DAG học từ nhật ký nhấp chuột không tự động tương đương với cấu trúc nhân quả nghiệp vụ; người phân tích vẫn phải chịu trách nhiệm về các yếu tố gây nhiễu không quan sát được.&lt;/p&gt;

&lt;h3 id=&quot;3-causal-transformer-cho-dữ-liệu-kết-cục-theo-thời-gian&quot;&gt;3. Causal Transformer cho dữ liệu kết cục theo thời gian&lt;/h3&gt;

&lt;p&gt;Melnychuk, Frauen và Feuerriegel (2022) đề xuất kiến trúc &lt;em&gt;Causal Transformer&lt;/em&gt; nhằm ước lượng kết cục phản thực trên dữ liệu dọc theo thời gian, chẳng hạn phác đồ điều trị trong cơ sở dữ liệu y tế MIMIC. Trong bối cảnh này, các hiệp biến thay đổi theo thời gian, quyết định điều trị và kết cục tác động qua lại liên tục qua nhiều mốc thời gian, tạo ra hiện tượng gây nhiễu biến thiên theo thời gian. Bản thân kiến trúc transformer không tự xóa bỏ confounding; mô hình phải dùng hàm mất mát đối kháng để học một biểu diễn vừa dự đoán tốt kết cục vừa không dự đoán được việc gán điều trị hiện tại. Đây chính là phiên bản học sâu của nguyên tắc Chương 5: muốn ước lượng đúng tác động điều trị thì phải chặn đường gây nhiễu, chứ không chỉ tăng độ sâu mạng nơ-ron.&lt;/p&gt;

&lt;h3 id=&quot;4-tương-tác-và-đa-cộng-tuyến-trong-hệ-thống-cá-nhân-hóa&quot;&gt;4. Tương tác và đa cộng tuyến trong hệ thống cá nhân hóa&lt;/h3&gt;

&lt;p&gt;Trong hệ gợi ý, phát biểu “hiệu quả của mã giảm giá phụ thuộc vào mức độ gắn bó của người dùng” chính là một hiệu ứng tương tác. Trong khi đó, hai vector nhúng (embedding) gần cộng tuyến sẽ tạo ra phân phối hậu nghiệm rất rộng cho từng hệ số riêng lẻ dù dự báo tổng thể vẫn chính xác — đúng như hiện tượng đã phân tích ở Bài 5.3. Về mặt thực hành sản phẩm, không nên cố diễn giải từng tọa độ embedding như một cơ chế độc lập, mà nên tập trung vào chất lượng dự báo và các tương tác giữa những khái niệm có ý nghĩa nghiệp vụ rõ ràng.&lt;/p&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-thiệt-hại-khi-đưa-biến-trung-gian-bad-control-vào-phân-tích-ab-test&quot;&gt;Giải thích: Tính tay thiệt hại khi đưa biến trung gian (bad control) vào phân tích A/B test&lt;/h3&gt;

&lt;p&gt;Hãy kiểm chứng bằng hai dòng đại số lý do Cinelli et al. (2022) cảnh báo việc “kiểm soát mọi cột có sẵn” trong thử nghiệm sản phẩm:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cơ chế sinh dữ liệu thật của một thử nghiệm A/B ngẫu nhiên hóa:&lt;/strong&gt; Giao diện mới (\(X \in \{0, 1\}\)) tăng số lượt nhấp (\(M\)), và cả giao diện mới lẫn lượt nhấp đều làm tăng doanh thu (\(Y\)):
\(M = 2\,X + u_M, \qquad Y = 1\,X + 3\,M + u_Y,\)
với \(u_M, u_Y\) độc lập với \(X\) (nhờ ngẫu nhiên hóa).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng hiệu ứng nhân quả thật sự của giao diện mới:&lt;/strong&gt; Thay phương trình của \(M\) vào \(Y\):
\(Y = 1\,X + 3(2\,X + u_M) + u_Y = 7\,X + (3u_M + u_Y).\)
Nếu hồi quy đơn \(Y \sim X\) (không thêm \(M\)), hệ số ước lượng hội tụ về đúng &lt;strong&gt;+7 đơn vị doanh thu&lt;/strong&gt; (gồm 1 đơn vị trực tiếp và 6 đơn vị gián tiếp qua lượt nhấp).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sai lầm khi thêm cột &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lượt nhấp&lt;/code&gt; \(M\) làm biến kiểm soát:&lt;/strong&gt; Chạy hồi quy \(Y \sim X + M\) sẽ giữ cố định \(M\), khiến hệ số của \(X\) tụt từ &lt;strong&gt;+7&lt;/strong&gt; xuống chỉ còn &lt;strong&gt;+1&lt;/strong&gt;! Nếu thử nghiệm chạy trên 1 triệu người dùng, khoảng tin cậy hậu nghiệm 95% có thể hẹp tới \([0.99,\ 1.01]\) — cực kỳ chính xác về mặt số học, nhưng &lt;strong&gt;đánh mất 85.7% giá trị thật của tính năng&lt;/strong&gt; chỉ vì đưa nhầm một biến trung gian vào mô hình.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;video-ngắn-good-control-vs-bad-control-trong-ab-test-hiện-đại&quot;&gt;Video ngắn: Good Control vs Bad Control trong A/B Test Hiện đại&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch05-05a-good-vs-bad-controls.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 14 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): giải thích vì sao đưa biến trung gian sau can thiệp (lượt click) vào mô hình A/B test sẽ triệt tiêu sai tác động thật (+12% → 0%) của tính năng mới.&lt;/p&gt;

&lt;h2 id=&quot;diễn-giải-và-nhận-định&quot;&gt;Diễn giải và nhận định&lt;/h2&gt;

&lt;p&gt;Một khoảng hậu nghiệm hẹp cho \(\beta_{\text{xử lý}}\) sau khi đưa vào hàng chục biến kiểm soát không phải là bằng chứng nhân quả, vì rất có thể biến trung gian đã chặn mất một phần hiệu ứng hoặc collider đã tạo ra thiên lệch. Ngược lại, một khoảng rộng hơn thu được từ tập điều chỉnh tối thiểu hợp lệ lại có thể là ước lượng trung thực hơn. Trình tự đúng của Chương 5 luôn là: xác định cấu trúc DAG trước, đánh giá độ hẹp của khoảng ước lượng sau.&lt;/p&gt;

&lt;h2 id=&quot;ứng-dụng&quot;&gt;Ứng dụng&lt;/h2&gt;

&lt;p&gt;Thử nghiệm trên nền tảng thị trường, mô hình xếp hạng có kiểm soát, cá nhân hóa điều trị và diễn giải đặc trưng nhúng đều là bài toán hồi quy đa biến kết hợp với câu hỏi nhân quả. Góc nhìn Bayes bổ sung một thông tin mà OLS thường dễ làm mờ đi: mức độ bất định còn lại sau khi đã khai báo rõ cấu trúc mô hình.&lt;/p&gt;

&lt;h2 id=&quot;giới-hạn-và-hướng-mở-rộng&quot;&gt;Giới hạn và hướng mở rộng&lt;/h2&gt;

&lt;p&gt;Học DAG thuần túy từ dữ liệu quan sát không giải quyết được tính không nhận diện (non-identifiability) nếu thiếu giả định cấu trúc. Causal Transformer cũng đòi hỏi các giả định về thứ tự thời gian và tính cân bằng biểu diễn. Bài này chỉ giới thiệu cầu nối ứng dụng chứ không thay thế một học phần đầy đủ về suy luận nhân quả. Ở Chương 6, ta sẽ mở rộng họ hàm hợp lý cho các biến kết quả không tuân theo phân phối Chuẩn, nhưng các nguyên tắc về confounding vẫn giữ nguyên giá trị.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=IFgHw_E521U&quot;&gt;A Crash Course in Good and Bad Controls with Carlos Cinelli&lt;/a&gt; — Spark: a centre for social research innovation, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Giới thiệu ngắn gọn về biến kiểm soát đúng và sai, phù hợp với cách tiếp cận hệ số hồi quy như phát biểu nhân quả có điều kiện.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=uanZZLlzKHw&quot;&gt;Statistical Rethinking 2023 - 06 - Good &amp;amp; Bad Controls&lt;/a&gt; — Richard McElreath, English. Trình bày các sơ đồ good và bad controls, củng cố lập luận rằng confounding là vấn đề cấu trúc dữ liệu chứ không phải lỗi phần mềm.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=IajzIKW518M&quot;&gt;Causality: Closing Back Doors&lt;/a&gt; — Econometrics, Causality, and Coding with Dr. HK, English. Hướng dẫn cách đóng đường cửa sau trên DAG, kết nối tư duy nhân quả với hồi quy đa biến.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vẽ một DAG ba nút cho chuỗi “hiển thị quảng cáo \(\rightarrow\) nhấp chuột \(\rightarrow\) mua hàng”. Nếu mục tiêu là ước lượng tác động của việc hiển thị lên hành vi mua hàng, điều kiện hóa trên biến nhấp chuột là &lt;em&gt;good control&lt;/em&gt; hay &lt;em&gt;bad control&lt;/em&gt;? Giải thích vì sao.&lt;/li&gt;
  &lt;li&gt;Một mô hình cá nhân hóa có hai đặc trưng tương quan 0.97. Kết quả dự báo trên tập kiểm tra rất tốt, nhưng dấu của hai hệ số đảo chiều khi loại bỏ 1% dữ liệu. Bạn có nên diễn giải riêng từng hệ số không? Vì sao?&lt;/li&gt;
  &lt;li&gt;Việc &lt;em&gt;Causal Transformer&lt;/em&gt; giảm thiểu khả năng dự đoán biến điều trị từ biểu diễn ẩn đang nhằm xử lý dạng gây nhiễu nào đã học ở Bài 5.2?&lt;/li&gt;
  &lt;li&gt;Giả sử thuật toán DAGMA trả về một đồ thị từ nhật ký sản phẩm. Hãy nêu hai mũi tên nhân quả mà bạn sẽ không cho phép mô hình tự vẽ nếu không có cơ sở nghiệp vụ.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 5, 14.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 18.&lt;/li&gt;
  &lt;li&gt;Cinelli, C., Forney, A., &amp;amp; Pearl, J. (2022). A crash course in good and bad controls. &lt;em&gt;Sociological Methods &amp;amp; Research&lt;/em&gt;. &lt;a href=&quot;https://doi.org/10.1177/00491241221099552&quot;&gt;doi:10.1177/00491241221099552&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Bello, K., Aragam, B., &amp;amp; Ravikumar, P. (2022). DAGMA: Learning DAGs via M-matrices and a log-determinant acyclicity characterization. &lt;em&gt;NeurIPS&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2209.08011&quot;&gt;arXiv:2209.08011&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Melnychuk, V., Frauen, D., &amp;amp; Feuerriegel, S. (2022). Causal Transformer for estimating counterfactual outcomes. &lt;em&gt;ICML&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2204.07258&quot;&gt;arXiv:2204.07258&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 4.7: MCMC hiện đại — NUTS, HMC và hồi quy Bayes trong thực hành</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_07_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_07_modern_applications</id>
   <content type="html">&lt;p&gt;Trong gần nửa thế kỷ sau khi Metropolis–Hastings ra đời, thống kê Bayes vẫn bị giới hạn trong những mô hình nhỏ vì chi phí lấy mẫu quá đắt đỏ. Bước ngoặt chỉ thực sự xảy ra trong thập kỷ gần đây khi ba mảnh ghép hội tụ: thuật toán NUTS tự động điều chỉnh quỹ đạo Hamilton, vi phân tự động trên đồ thị tính toán, và các thư viện chạy song song hàng nghìn chuỗi trên GPU/TPU như BlackJAX hay NumPyro. Định lý Bayes không hề thay đổi, nhưng động cơ tính toán phía sau nó đã bước sang một kỷ nguyên hoàn toàn mới.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài tùy chọn này, bạn sẽ hiểu Hamiltonian Monte Carlo (HMC) và NUTS không phải phần phụ kỹ thuật đứng sau hồi quy tuyến tính Bayes, mà là giải pháp tất yếu khi phân phối hậu nghiệm không còn công thức dạng đóng. Bạn cũng sẽ biết cách đọc kết quả lấy mẫu từ Stan, PyMC hay NumPyro như một xấp xỉ số có kiểm soát cho đúng mô hình sinh dữ liệu đã thiết lập ở Chương 4.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-tập-điển-hình-nhiều-chiều-tích-phân-leapfrog-và-suy-luận-lai&quot;&gt;Kiến thức cần nhớ: Tập điển hình nhiều chiều, Tích phân Leapfrog và Suy luận lai&lt;/h2&gt;

&lt;p&gt;Để hiểu vì sao các bộ lấy mẫu giai đoạn 2022–2026 lại có hình hài như ngày nay, cần nhìn rõ ba trụ cột toán học:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tập điển hình (Typical Set) trong không gian nhiều chiều:&lt;/strong&gt; Ở 1 chiều, phần lớn khối lượng xác suất nằm quanh đỉnh mật độ (mode). Nhưng ở \(d = 100\) chiều, thể tích hình cầu tăng theo \(r^{d-1}\) nên xác suất tập trung trong một lớp vỏ mỏng nằm &lt;em&gt;cách xa&lt;/em&gt; đỉnh gọi là tập điển hình. Thuật toán tìm cực đại (MAP) bị hút vào đỉnh (nơi ít khối lượng xác suất), còn bước đi ngẫu nhiên dễ nhảy văng khỏi lớp vỏ mỏng đó; HMC dùng động lượng để lướt êm dọc theo đúng lớp vỏ này.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích phân bảo toàn thể tích (Symplectic Leapfrog Integrator):&lt;/strong&gt; Khi mô phỏng phương trình Hamilton rời rạc theo thời gian, phương pháp Euler thông thường làm năng lượng trôi dạt và phá vỡ tính thuận nghịch. Tích phân leapfrog (nửa bước động lượng – trọn bước vị trí – nửa bước động lượng) bảo toàn thể tích pha và gần như bảo toàn năng lượng \(H(\theta, r)\), giúp tỷ lệ chấp nhận Metropolis tiến sát 100% ngay cả khi bước nhảy rất xa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phối hợp Suy luận biến phân và MCMC (Pathfinder + NUTS):&lt;/strong&gt; Suy luận biến phân (VI) tối ưu nhanh phân kỳ Kullback–Leibler \(\mathrm{KL}(q \Vert p)\) để tìm một xấp xỉ Gaussian thô gần vùng tập điển hình; dùng nó làm điểm khởi động (warm-start) giúp NUTS bỏ qua giai đoạn dò đường tốn kém mà vẫn giữ nguyên tính chính xác tiệm cận của MCMC.
    &lt;h2 id=&quot;kiến-thức-cần-có&quot;&gt;Kiến thức cần có&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Các bài 4.1–4.6 đã xây dựng hồi quy tuyến tính như một mô hình sinh dữ liệu, trình bày cách chọn phân phối tiên nghiệm và suy luận hậu nghiệm với PyMC, còn Bài 4.2b đã giới thiệu nền tảng toán học của MCMC. Bài này không lặp lại thuật toán Metropolis mà tập trung vào cách các bộ lấy mẫu hiện đại vận hành trong giai đoạn 2022–2026 và lý do hồi quy tuyến tính vẫn là lớp mô hình được lấy mẫu phổ biến nhất.&lt;/p&gt;

&lt;h2 id=&quot;mở-đầu&quot;&gt;Mở đầu&lt;/h2&gt;

&lt;p&gt;Ngay khi mô hình có hệ số chặn, hệ số dốc, độ nhiễu và vài biến dự báo, tích giữa phân phối tiên nghiệm và hàm hợp lý không còn tính tích phân được bằng tay, trong khi phương pháp lưới ở Chương 2 bùng nổ về số ô tính toán. Rào cản không nằm ở tư duy Bayes, mà ở hình học nhiều chiều của phân phối hậu nghiệm. Câu hỏi trung tâm của bài là: khi không thể vẽ trực tiếp phân phối hậu nghiệm, ta dựa vào đâu để tin tưởng chuỗi số mà máy tính trả về?&lt;/p&gt;

&lt;h2 id=&quot;phát-triển-khái-niệm&quot;&gt;Phát triển khái niệm&lt;/h2&gt;

&lt;p&gt;Hamiltonian Monte Carlo sử dụng đạo hàm (gradient) của hàm mật độ log hậu nghiệm để đề xuất những bước di chuyển xa mà vẫn duy trì tỷ lệ chấp nhận cao. Biến thể NUTS (No-U-Turn Sampler) tự động dừng quỹ đạo khi nó bắt đầu quay ngược lại, giúp người dùng không phải tự chỉnh độ dài quỹ đạo bằng tay. Về bản chất, đại lượng mà bộ lấy mẫu đang xấp xỉ là kỳ vọng theo phân phối hậu nghiệm:&lt;/p&gt;

\[\mathbb E[g(\theta)\mid y]\approx\frac{1}{S}\sum_{s=1}^{S}g(\theta^{(s)}),\qquad \theta^{(s)}\sim p(\theta\mid y),\]

&lt;p&gt;chính là công cụ mà hồi quy Bayes dùng để tính ước lượng hệ số, khoảng tin cậy hậu nghiệm và dự báo. Phần mềm lấy mẫu không thay thế mô hình thống kê, mà thay thế phần tính tích phân thủ công.&lt;/p&gt;

&lt;h2 id=&quot;mô-hình-trong-thực-hành-hiện-đại&quot;&gt;Mô hình trong thực hành hiện đại&lt;/h2&gt;

&lt;h3 id=&quot;1-nuts-trong-stan-pymc-và-numpyro-cho-hồi-quy-phân-cấp&quot;&gt;1. NUTS trong Stan, PyMC và NumPyro cho hồi quy phân cấp&lt;/h3&gt;

&lt;p&gt;Cấu trúc sinh dữ liệu cốt lõi vẫn không đổi: tham số tuân theo phân phối tiên nghiệm, còn dữ liệu dao động theo phân phối Chuẩn quanh một siêu phẳng tuyến tính. Điểm khác biệt trong thực tế công nghiệp là siêu phẳng ấy thường có hệ số chặn thay đổi theo quốc gia, chiến dịch hoặc máy chủ. Tài liệu hướng dẫn của Stan cùng hệ sinh thái PyMC và NumPyro đều chọn NUTS làm mặc định vì đạo hàm của hàm mật độ log có thể tính chính xác bằng vi phân tự động (automatic differentiation). Khi đọc một khoảng tin cậy hậu nghiệm cho hệ số quảng cáo, thực chất bạn đang đọc bản tóm tắt của các mẫu NUTS chứ không phải công thức OLS.&lt;/p&gt;

&lt;h3 id=&quot;2-pathfinder-bước-khởi-động-ấm-thay-vì-thay-thế-mcmc&quot;&gt;2. Pathfinder: bước khởi động ấm thay vì thay thế MCMC&lt;/h3&gt;

&lt;p&gt;Zhang, Carpenter, Gelman và Vehtari (2022) đề xuất thuật toán Pathfinder: bám theo quỹ đạo tối ưu quasi-Newton, dựng các xấp xỉ Gaussian dọc theo đường đi rồi lấy mẫu từ xấp xỉ có phân kỳ KL nhỏ nhất. Trên nhiều phân phối hậu nghiệm, các mẫu này có chất lượng cao hơn ADVI và tốn ít chi phí hơn một chuỗi HMC ngắn, nên Stan và các thư viện trên nền JAX dùng Pathfinder để khởi động ấm cho NUTS. Ý nghĩa thực hành ở đây rất rõ: suy luận biến phân (variational inference) đóng vai trò tìm điểm xuất phát tốt cho MCMC, chứ không thay thế hoàn toàn việc lấy mẫu hậu nghiệm.&lt;/p&gt;

&lt;h3 id=&quot;3-blackjax-và-mcmc-dạng-mô-đun-trên-phần-cứng-tăng-tốc&quot;&gt;3. BlackJAX và MCMC dạng mô-đun trên phần cứng tăng tốc&lt;/h3&gt;

&lt;p&gt;Cabezas et al. (2024) xây dựng BlackJAX như một tập hợp các khối thuật toán thống kê cơ sở — bước Metropolis, động lực học Hamilton, cơ chế Langevin — viết trên JAX để biên dịch trực tiếp lên GPU và TPU. Khi đó, hồi quy Bayes không còn giới hạn ở vài chuỗi chạy tuần tự trên máy tính cá nhân, mà cùng một hàm mật độ log có thể chạy song song hàng nghìn chuỗi. Mô hình sinh dữ liệu giữ nguyên; điều thay đổi là quy mô năng lực tính toán.&lt;/p&gt;

&lt;h3 id=&quot;4-mcmc-cho-mạng-nơ-ron-bayes&quot;&gt;4. MCMC cho mạng nơ-ron Bayes&lt;/h3&gt;

&lt;p&gt;Izmailov, Vikram, Hoffman và Wilson (2021) khảo sát hình dạng thực sự của phân phối hậu nghiệm trong mạng nơ-ron Bayes khi chạy HMC quy mô lớn, thay vì mặc định tin vào dropout hay xấp xỉ Gaussian đường chéo. Kết quả cho thấy các phương pháp xấp xỉ phổ biến thường không tái tạo được đầy đủ phân phối hậu nghiệm thực, dù dự báo thu được vẫn có thể hữu ích. Bài học rút ra cho người học hồi quy tuyến tính rất rõ ràng: nếu HMC đã gặp thách thức hình học ngay trên vài chục hệ số có tương quan, thì MCMC cho học sâu chính là cùng một bài toán hình học đó ở quy mô lớn hơn. Chương 7 sẽ trình bày các phương pháp xấp xỉ nhẹ hơn cho bối cảnh này.&lt;/p&gt;

&lt;h3 id=&quot;giải-thích-chạy-tay-1-bước-tích-phân-leapfrog-trong-hmc&quot;&gt;Giải thích: Chạy tay 1 bước tích phân Leapfrog trong HMC&lt;/h3&gt;

&lt;p&gt;Vì sao HMC có thể đi một quãng đường dài mà xác suất chấp nhận vẫn gần bằng 1? Hãy tự tay tính đúng một bước leapfrog trên phân phối chuẩn hóa 1 chiều \(p(\theta \mid y) \propto \exp(-\theta^2/2)\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Thiết lập Hamiltonian:&lt;/strong&gt; Thế năng \(U(\theta) = -\log \tilde p(\theta) = \frac{1}{2}\theta^2\) nên gradient là \(\nabla U(\theta) = \theta\); động năng \(K(r) = \frac{1}{2}r^2\) (khối lượng đơn vị \(M = 1\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trạng thái xuất phát:&lt;/strong&gt; Giả sử chuỗi đang ở \(\theta_0 = 1.0\) và rút động lượng \(r_0 = 0.0\). Tổng năng lượng ban đầu:
\(H(\theta_0, r_0) = \frac{1}{2}(1.0)^2 + \frac{1}{2}(0.0)^2 = 0.5000.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thực hiện 1 bước leapfrog với kích thước bước khá lớn \(\epsilon = 0.5\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;em&gt;Nửa bước động lượng:&lt;/em&gt; \(r_{1/2} = r_0 - \frac{\epsilon}{2}\nabla U(\theta_0) = 0 - 0.25(1.0) = -0.25\).&lt;/li&gt;
      &lt;li&gt;&lt;em&gt;Trọn bước vị trí:&lt;/em&gt; \(\theta_1 = \theta_0 + \epsilon r_{1/2} = 1.0 + 0.5(-0.25) = 0.875\).&lt;/li&gt;
      &lt;li&gt;&lt;em&gt;Nửa bước động lượng cuối:&lt;/em&gt; \(r_1 = r_{1/2} - \frac{\epsilon}{2}\nabla U(\theta_1) = -0.25 - 0.25(0.875) = -0.46875\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra bảo toàn năng lượng và bước chấp nhận Metropolis:&lt;/strong&gt;
\(H(\theta_1, r_1) = \frac{1}{2}(0.875)^2 + \frac{1}{2}(-0.46875)^2 = 0.38281 + 0.10986 = 0.49268.\)
Độ lệch năng lượng chỉ là \(\Delta H = 0.49268 - 0.5000 = -0.00732\), nên xác suất chấp nhận \(\alpha = \min(1, e^{-\Delta H}) = \min(1, e^{+0.00732}) = 1\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Ngay cả với bước \(\epsilon = 0.5\) rất thô, tích phân leapfrog vẫn giữ năng lượng gần như bất biến — đó chính là bí mật toán học đằng sau hiệu năng vượt trội của NUTS trong Stan, PyMC và BlackJAX.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-hmc--nuts-lướt-trên-tập-điển-hình-nhờ-động-lượng&quot;&gt;Video ngắn: HMC &amp;amp; NUTS: Lướt trên Tập Điển hình nhờ Động lượng&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch04-07a-hmc-leapfrog-typical-set.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 19 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): đối chiếu bước đi dò dẫm của Random Walk với quỹ đạo Leapfrog có động lượng trong HMC/NUTS lướt mượt dọc vành đai Tập Điển hình.&lt;/p&gt;

&lt;h2 id=&quot;diễn-giải-và-nhận-định&quot;&gt;Diễn giải và nhận định&lt;/h2&gt;

&lt;p&gt;Một khoảng hậu nghiệm từ NUTS chỉ đáng tin khi các chuỗi đã trộn đều và bản thân mô hình không sai lệch thô bạo. Chỉ số \(\hat R\) gần 1 không chứng minh được mối quan hệ là nhân quả. Pathfinder có thể dừng ở một cực đại cục bộ (mode phụ) khiến NUTS khởi động lệch vùng, còn tốc độ của BlackJAX không làm một phân phối tiên nghiệm bất hợp lý trở nên vô hại. Hãy xem bộ lấy mẫu như một kính lúp: nó phóng đại trung thực đúng mô hình bạn đã khai báo, bao gồm cả những giả định chưa chuẩn xác về phần dư.&lt;/p&gt;

&lt;h2 id=&quot;ứng-dụng&quot;&gt;Ứng dụng&lt;/h2&gt;

&lt;p&gt;Hồi quy tuyến tính Bayes là nền tảng của mô hình phân bổ ngân sách truyền thông (media mix modeling), định giá và các mô hình phân cấp trong thử nghiệm A/B. MCMC hiện đại giúp các mô hình này tích hợp được phân phối tiên nghiệm thực chất và trả về phân phối hậu nghiệm đầy đủ thay vì chỉ dừng ở ước lượng điểm.&lt;/p&gt;

&lt;h2 id=&quot;giới-hạn-và-hướng-mở-rộng&quot;&gt;Giới hạn và hướng mở rộng&lt;/h2&gt;

&lt;p&gt;HMC đòi hỏi hàm mật độ log phải khả vi theo tham số; các bài toán có tham số rời rạc cần những phương pháp xử lý khác. Với các mô hình có kích thước rất lớn, thực hành vẫn cần đến suy luận biến phân (VI), xấp xỉ Laplace hoặc tổ hợp mô hình (ensemble). Bài này không đi sâu lại lý thuyết chuỗi Markov; Chương 5 sẽ tiếp tục mở rộng độ phức tạp của phân phối hậu nghiệm khi đưa thêm nhiều biến dự báo và tư duy nhân quả.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=a-wydhEuAm0&quot;&gt;The intuition behind the Hamiltonian Monte Carlo algorithm&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Giải thích trực giác HMC trước khi tiếp cận NUTS như cơ chế tự chọn độ dài quỹ đạo, nối tiếp bước chuyển từ Metropolis sang bộ lấy mẫu hiện đại.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jUSZboSq1zg&quot;&gt;Michael Betancourt: Scalable Bayesian Inference with Hamiltonian Monte Carlo&lt;/a&gt; — London Machine Learning Meetup, English. Michael Betancourt trình bày về suy luận Bayes quy mô lớn bằng Hamiltonian Monte Carlo.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KVpAziPblks&quot;&gt;#78 Exploring MCMC Sampler Algorithms, with Matt D. Hoffman&lt;/a&gt; — Learning Bayesian Statistics, English. Matt Hoffman, đồng tác giả của NUTS, trao đổi về các thuật toán lấy mẫu MCMC, bổ trợ cho phần diễn giải chuỗi mẫu từ PyMC và Stan.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Một đồng nghiệp nhận xét “PyMC đã hội tụ vì trace plot trông ổn”. Bạn sẽ yêu cầu thêm hai chỉ số chẩn đoán nào, và mỗi chỉ số kiểm tra khía cạnh hình học gì của chuỗi?&lt;/li&gt;
  &lt;li&gt;Giải thích bằng lời (không dùng mã nguồn) vì sao Pathfinder vừa là một phương pháp suy luận biến phân, vừa có thể đóng vai trò một bước trong quy trình MCMC.&lt;/li&gt;
  &lt;li&gt;Trong bài toán hồi quy giá nhà có sai số đuôi dày, NUTS vẫn chạy xong bình thường. Phân phối hậu nghiệm thu được đang xấp xỉ mô hình nào, và kiểm tra PPC sẽ chỉ ra dấu hiệu sai lệch gì?&lt;/li&gt;
  &lt;li&gt;Đọc trang tài liệu về NUTS của Stan hoặc NumPyro và chỉ ra một câu đề cập đến &lt;em&gt;target log density&lt;/em&gt;. Đối tượng đó tương ứng với thành phần toán học nào trong Bài 4.1?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 11–12.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 7, 17.&lt;/li&gt;
  &lt;li&gt;Zhang, L., Carpenter, B., Gelman, A., &amp;amp; Vehtari, A. (2022). Pathfinder: Parallel quasi-Newton variational inference. &lt;em&gt;JMLR&lt;/em&gt;, 23(306). &lt;a href=&quot;https://arxiv.org/abs/2108.03782&quot;&gt;arXiv:2108.03782&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Cabezas, A., Corenflos, A., Lao, J., Louf, R., et al. (2024). BlackJAX: Composable Bayesian inference in JAX. &lt;a href=&quot;https://arxiv.org/abs/2402.10797&quot;&gt;arXiv:2402.10797&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Izmailov, P., Vikram, S., Hoffman, M. D., &amp;amp; Wilson, A. G. (2021). What are Bayesian neural network posteriors really like? &lt;em&gt;ICML&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://mc-stan.org/docs/reference-manual/mcmc.html&quot;&gt;Stan HMC/NUTS&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://num.pyro.ai/en/stable/mcmc.html&quot;&gt;NumPyro inference&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.pymc.io/projects/docs/en/stable/learn/core_notebooks/pymc_overview.html&quot;&gt;PyMC sampling&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 2.7: Ứng dụng hiện đại của prior liên hợp và cập nhật Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_07_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_07_modern_applications</id>
   <content type="html">&lt;p&gt;Dù các mô hình học sâu ngày nay có hàng tỷ tham số, những cặp liên hợp giản dị như Beta–Binomial hay Gamma–Poisson vẫn đang chạy trong trái tim của nhiều hệ thống công nghiệp khổng lồ: từ thuật toán &lt;em&gt;Thompson Sampling&lt;/em&gt; phân bổ quảng cáo theo thời gian thực, hệ thống ước lượng tỷ lệ lỗi vi dịch vụ (microservices) đến các bộ lọc dự báo nhu cầu bán lẻ có hàng triệu mã hàng.&lt;/p&gt;

&lt;p&gt;Bài tổng kết Chương 2 này kết nối các khái niệm cốt lõi — prior, likelihood, posterior, liên hợp và xấp xỉ lưới — với cách kỹ sư dữ liệu ứng dụng chúng để ra quyết định nhanh, ổn định và có kiểm soát bất định trong thực tế.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài học tùy chọn này, bạn sẽ nhìn nhận prior liên hợp (conjugate prior) và xấp xỉ lưới (grid approximation) như những lựa chọn thiết kế hệ thống thực tế chứ không chỉ là kỹ thuật làm bài tập. Bạn có thể quan sát một hệ thống đang vận hành — như quảng cáo, xếp hạng hay giám sát sự cố — và chỉ ra likelihood đang giả định điều gì, họ prior nào giữ chi phí cập nhật ở mức thấp, và khi nào phép tính giải tích phải nhường chỗ cho mô phỏng.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-cập-nhật-liên-hợp-trong-hệ-thống-trực-tuyến-và-thử-nghiệm-thích-nghi&quot;&gt;Kiến thức cần nhớ: Cập nhật liên hợp trong hệ thống trực tuyến và Thử nghiệm thích nghi&lt;/h2&gt;

&lt;p&gt;Ba trụ cột ứng dụng dưới đây giải thích vì sao kiến thức Chương 2 có sức sống bền bỉ trong kỹ thuật hiện đại:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật trực tuyến chi phí \(O(1)\) (Streaming Conjugate Updates):&lt;/strong&gt; Trong các hệ thống thời gian thực xử lý hàng triệu sự kiện mỗi giây, không thể chạy MCMC lại từ đầu mỗi khi có một lượt nhấp chuột mới. Mô hình Beta–Binomial và Gamma–Poisson cho phép cập nhật hậu nghiệm tức thì chỉ bằng phép cộng số đếm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thompson Sampling (Multi-Armed Bandits):&lt;/strong&gt; Thay vì chia đều lưu lượng 50/50 trong suốt thí nghiệm A/B, thuật toán rút ngẫu nhiên một mẫu \(\tilde p_a \sim \text{Beta}(\alpha_a, \beta_a)\) từ hậu nghiệm của mỗi phương án và chọn phương án có mẫu lớn nhất — tự động giảm thiểu tổn thất cơ hội (&lt;em&gt;regret&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Làm trơn dữ liệu thưa (Empirical Bayes Shrinkage):&lt;/strong&gt; Khi xếp hạng hàng nghìn sản phẩm hay bài viết mới chỉ có vài lượt đánh giá, thay tỷ lệ thô bằng kỳ vọng hậu nghiệm giúp chống nhiễu mẫu nhỏ cực kỳ hiệu quả.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-có&quot;&gt;Kiến thức cần có&lt;/h2&gt;

&lt;p&gt;Các bài 2.1–2.6 đã xây dựng bộ khung gồm bốn thành phần: phân phối, likelihood, prior và posterior. Bài viết này không chứng minh lại tính liên hợp của Beta–Binomial hay Gamma–Poisson, mà tập trung trả lời vì sao các cặp này vẫn xuất hiện trong các hệ thống khoa học máy tính quy mô lớn và vì sao empirical Bayes thường được dùng để chọn tham số cho prior.&lt;/p&gt;

&lt;h2 id=&quot;mở-đầu&quot;&gt;Mở đầu&lt;/h2&gt;

&lt;p&gt;Khi đã quen với việc cập nhật phân phối Beta bằng cách đếm số lần thành công, một câu hỏi tự nhiên nảy ra: vì sao một nền tảng có hàng triệu người dùng vẫn cần đến posterior dạng đóng? Câu trả lời nằm ở yêu cầu độ trễ thấp và số lượng thực thể rất lớn. Một hệ thống quảng cáo hay xếp hạng có thể phải cập nhật xác suất chuyển đổi cho hàng triệu mục sau mỗi phút. Chạy chuỗi MCMC cho từng mục là quá chậm, trong khi phép cập nhật liên hợp chỉ cần cộng số đếm vào \((\alpha,\beta)\) nên chạy gần như tức thời. Bài toán đặt ra vì thế vừa mang tính hiệu năng vừa mang tính thống kê: các công thức giải tích vẫn giữ vị trí quan trọng ở những nơi chúng đủ nhanh để duy trì suy luận trung thực ở quy mô lớn.&lt;/p&gt;

&lt;h2 id=&quot;phát-triển-khái-niệm&quot;&gt;Phát triển khái niệm&lt;/h2&gt;

&lt;p&gt;Prior liên hợp là họ phân phối đóng dưới phép nhân với likelihood: posterior thu được vẫn thuộc cùng họ đó. Với xác suất chuyển đổi \(\theta\) và dữ liệu nhị thức, prior Beta cho:&lt;/p&gt;

\[\theta\mid y \sim \mathrm{Beta}(\alpha+y,\ \beta+n-y).\]

&lt;p&gt;Trên các bảng điều khiển phân tích, chính phép cộng số đếm này thường được gọi là “làm mượt” (smoothing). Phương pháp &lt;strong&gt;empirical Bayes&lt;/strong&gt; ước lượng \(\alpha\) và \(\beta\) từ toàn bộ tập hợp các mục thay vì chỉ hỏi một chuyên gia đơn lẻ, nhờ đó một mục mới hoặc hiếm dữ liệu có thể mượn thông tin từ toàn hệ thống. Khi likelihood không còn thuộc họ mũ hoặc khi cấu trúc prior phân cấp phá vỡ tính liên hợp, xấp xỉ lưới ở Bài 2.6 là trực giác hình học cuối cùng trước khi chuyển sang Hamiltonian Monte Carlo.&lt;/p&gt;

&lt;h2 id=&quot;mô-hình-như-câu-chuyện-sinh-dữ-liệu&quot;&gt;Mô hình như câu chuyện sinh dữ liệu&lt;/h2&gt;

&lt;h3 id=&quot;1-ước-lượng-tỷ-lệ-betabinomial-trong-quảng-cáo-và-xếp-hạng&quot;&gt;1. Ước lượng tỷ lệ Beta–Binomial trong quảng cáo và xếp hạng&lt;/h3&gt;

&lt;p&gt;Xét mỗi mẫu quảng cáo, mỗi cặp truy vấn–mục, hoặc mỗi nội dung gợi ý có một xác suất nhấp hay chuyển đổi chưa biết \(\theta_i\). Cấu trúc dữ liệu rất gọn: \(n_i\) lượt hiển thị và \(y_i\) lượt thành công. Một prior Beta dùng chung — với siêu tham số được ước lượng bằng empirical Bayes — sẽ kéo ước lượng của các mục ít dữ liệu, nhiều nhiễu về gần mức trung bình chung của hệ thống. Nhờ vậy, một mục mới chỉ có 1 lượt nhấp trên 2 lượt hiển thị sẽ không bị đánh giá là có tỷ lệ chuyển đổi 50%. Trung bình hậu nghiệm:&lt;/p&gt;

\[\hat\theta_i=\frac{\alpha+y_i}{\alpha+\beta+n_i}\]

&lt;p&gt;đóng vai trò điểm xếp hạng có thể cập nhật liên tục chỉ bằng phép cộng số nguyên. Chẳng hạn, PinnerFormer của Pinterest (Pancha et al., 2022) là mô hình tuần tự biểu diễn hành vi người dùng, nhưng tầng phục vụ (serving layer) vẫn cần các ước lượng tỷ lệ ổn định cho từng mục; làm mượt liên hợp vì thế vẫn là lớp suy luận Bayes chi phí thấp đứng nền cho các bộ xếp hạng phức tạp hơn.&lt;/p&gt;

&lt;h4 id=&quot;video-ngắn-5-sao-1-lượt-vs-48-sao-50-lượt-co-cụm-bayes-lật-ngược-thứ-hạng&quot;&gt;Video ngắn: 5 Sao (1 lượt) vs 4.8 Sao (50 lượt): Co cụm Bayes lật ngược Thứ hạng!&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch02-07a-five-star-shrinkage-thompson.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): dùng Prior Beta(8,2) so sánh trực tiếp hai đường hậu nghiệm: sản phẩm 1/1 bị kéo về 81.8% (rộng) trong khi sản phẩm 48/50 đạt 93.3% (hẹp, thắng áp đảo).&lt;/p&gt;

&lt;h3 id=&quot;2-thompson-sampling-lấy-mẫu-từ-posterior-để-ra-quyết-định&quot;&gt;2. Thompson sampling: lấy mẫu từ posterior để ra quyết định&lt;/h3&gt;

&lt;p&gt;Russo et al. (2018) hệ thống hóa một nguyên lý đang được triển khai hằng ngày trên nhiều nền tảng: nếu có thể lấy mẫu từ \(p(\theta\mid y)\), bạn có thể chọn hành động tối ưu bằng cách hành động như thể giá trị vừa lấy mẫu là tham số thực. Với bài toán bandit Beta–Binomial, thao tác lấy mẫu này chỉ tốn một dòng mã. Cơ chế sinh dữ liệu diễn ra tuần tự: posterior hôm nay trở thành prior ngày mai, còn hoạt động thăm dò (exploration) không phải quy tắc cảm tính mà là hệ quả tự nhiên của độ rộng posterior còn lại. Các hệ thống contextual bandit hiện đại thay phân phối Beta bằng posterior của mô hình hồi quy, nhưng nguyên tắc quyết định — lấy mẫu rồi hành động — vẫn xuất phát từ chính cơ chế cập nhật ở Chương 2.&lt;/p&gt;

&lt;h3 id=&quot;3-giám-sát-số-đếm-bằng-gammapoisson&quot;&gt;3. Giám sát số đếm bằng Gamma–Poisson&lt;/h3&gt;

&lt;p&gt;Các sự kiện hạ tầng, suy giảm chất lượng luồng dữ liệu và số lượng sự cố thường được mô hình hóa bằng Poisson với prior Gamma trên cường độ. Sau mỗi chu kỳ đếm, posterior vẫn là phân phối Gamma, giúp hệ thống trực canh tính ngay khoảng dự báo hậu nghiệm mà không cần bộ lấy mẫu. Tuy nhiên, khi phương sai vượt quá trung bình (overdispersion), mô hình cần chuyển sang Negative Binomial và không còn giữ được dạng đóng liên hợp thuận tiện nữa. Khi đó, tư duy của Bài 2.6 phát huy tác dụng: quan sát posterior trên lưới, nhận ra phân phối bị lệch và chấp nhận rằng lời giải giải tích đã đạt giới hạn.&lt;/p&gt;

&lt;h3 id=&quot;4-khi-tính-liên-hợp-không-còn-đáp-ứng-từ-lưới-đến-lập-trình-xác-suất&quot;&gt;4. Khi tính liên hợp không còn đáp ứng: từ lưới đến lập trình xác suất&lt;/h3&gt;

&lt;p&gt;Các thư viện lập trình xác suất như Stan, PyMC và NumPyro đều coi mô hình liên hợp là trường hợp không cần tiêu tốn tài nguyên cho bộ lấy mẫu, còn các mô hình không liên hợp chính là lý do thuật toán NUTS ra đời. Xấp xỉ lưới vẫn giữ vai trò hình dung cốt lõi: nó cho thấy tích chưa chuẩn hóa \(p(y\mid\theta)p(\theta)\) như một bề mặt mật độ trên không gian tham số. Hamiltonian Monte Carlo (trình bày ở Chương 4) là công cụ dùng khi bề mặt đó có quá nhiều chiều để dựng lưới. Sau đó, Pathfinder (Zhang, Carpenter, Gelman và Vehtari, 2022) sử dụng quỹ đạo tối ưu quasi-Newton để dựng nhanh một xấp xỉ Gaussian quanh vùng mật độ cao đó, thường dùng làm bước khởi tạo (warm start). Các khái niệm của Chương 2 không bị thay thế, mà được tự động hóa bằng các công cụ tính toán hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;diễn-giải-và-nhận-định&quot;&gt;Diễn giải và nhận định&lt;/h2&gt;

&lt;p&gt;Một tỷ lệ đã qua phép co về trung bình (shrinkage) không phải là “CTR thực”, mà là trung bình hậu nghiệm dưới một giả định phân cấp; giả định này sẽ sai lệch nếu các mục không tương đương để chia sẻ thông tin (chẳng hạn mẫu quảng cáo thuộc các thị trường khác nhau hoặc truy vấn có mục đích khác nhau). Thompson sampling không triệt tiêu hoàn toàn độ hối tiếc (regret), mà giảm dần nó khi độ bất định của posterior thu hẹp. Tương tự, một khoảng dự báo Gamma bỏ qua điểm chuyển chế độ (changepoint) sẽ trông rất hẹp nhưng phản ứng chậm khi hệ thống thay đổi đột ngột. Mọi công thức dạng đóng đều ngầm giả định rằng quan sát kế tiếp vẫn tuân theo cùng một quy luật sinh dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;ứng-dụng&quot;&gt;Ứng dụng&lt;/h2&gt;

&lt;p&gt;Quảng cáo, hệ xếp hạng, giám sát độ tin cậy hệ thống và thử nghiệm tuần tự là bốn lĩnh vực đưa kiến thức Chương 2 trực tiếp vào vận hành thực tế. Chúng cũng vạch rõ ranh giới thiết kế: dùng prior liên hợp cho vòng tính toán lõi đòi hỏi tốc độ cao, và dùng mô phỏng cho những mô hình không còn biểu diễn gọn bằng công thức đóng.&lt;/p&gt;

&lt;h2 id=&quot;giới-hạn-và-hướng-mở-rộng&quot;&gt;Giới hạn và hướng mở rộng&lt;/h2&gt;

&lt;p&gt;Empirical Bayes chỉ ước lượng điểm các siêu tham số nên thường đánh giá thấp độ bất định của chính prior. Cách tiếp cận Bayes phân cấp đầy đủ — được mở ra qua tư duy đa mức ở Chương 5 — đặt phân phối hậu nghiệm lên chính \((\alpha,\beta)\). Trong khi đó, xấp xỉ lưới nhanh chóng mất khả thi khi số chiều vượt quá vài tham số. Bước tiến trung thực tiếp theo không phải là mở rộng bảng công thức liên hợp mà là sử dụng bộ lấy mẫu — trọng tâm của Chương 4.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-giải-bài-toán-5-sao-nhưng-chỉ-có-1-lượt-đánh-giá-bằng-co-cụm-bayes&quot;&gt;Giải thích: Giải bài toán “5 sao nhưng chỉ có 1 lượt đánh giá” bằng co cụm Bayes&lt;/h2&gt;

&lt;p&gt;Trong thương mại điện tử, một sản phẩm có 1/1 đánh giá tốt (100%) có thực sự đáng tin hơn sản phẩm có 90/100 đánh giá tốt (90%) không? Hãy đi qua 3 bước xử lý bằng prior liên hợp:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Ước lượng mức nền toàn sàn làm Prior:&lt;/strong&gt; Giả sử trung bình toàn sàn có tỷ lệ đánh giá tốt là \(80\%\), chọn prior \(\text{Beta}(8, 2)\) (cỡ mẫu ảo \(M = 10\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật hậu nghiệm cho từng sản phẩm:&lt;/strong&gt; Cộng số đánh giá tốt vào \(\alpha = 8\) và số đánh giá xấu vào \(\beta = 2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xếp hạng theo kỳ vọng hậu nghiệm (hoặc cận dưới 5% của hậu nghiệm):&lt;/strong&gt; Sản phẩm ít dữ liệu bị kéo về mức nền toàn sàn, còn sản phẩm nhiều dữ liệu giữ sát tỷ lệ thực tế của chính nó.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-xếp-hạng-2-sản-phẩm-với-prior-textbeta8-2&quot;&gt;Ví dụ tính toán làm từng bước: Xếp hạng 2 sản phẩm với Prior \(\text{Beta}(8, 2)\)&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Sản phẩm&lt;/th&gt;
      &lt;th&gt;Dữ liệu \((k / n)\)&lt;/th&gt;
      &lt;th&gt;Tỷ lệ thô (MLE)&lt;/th&gt;
      &lt;th&gt;Hậu nghiệm&lt;/th&gt;
      &lt;th&gt;Kỳ vọng hậu nghiệm \(\mathbb{E}[p \vert y]\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Sản phẩm A (mới)&lt;/td&gt;
      &lt;td&gt;\(1 / 1\)&lt;/td&gt;
      &lt;td&gt;\(100.0\%\)&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(9, 2)\)&lt;/td&gt;
      &lt;td&gt;\(9 / 11 \approx 81.8\%\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Sản phẩm B (uy tín)&lt;/td&gt;
      &lt;td&gt;\(90 / 100\)&lt;/td&gt;
      &lt;td&gt;\(90.0\%\)&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(98, 12)\)&lt;/td&gt;
      &lt;td&gt;\(98 / 110 \approx 89.1\%\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Thứ tự xếp hạng lập tức trở nên hợp lý: Sản phẩm B (\(89.1\%\)) đứng trên Sản phẩm A (\(81.8\%\)), khắc phục triệt để lỗi “nhiễu mẫu nhỏ” mà không cần đặt các luật lọc cứng nhắc tùy tiện.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Dùng cùng một prior toàn cục cho các danh mục hàng hóa có chất lượng nền hoàn toàn khác nhau — khi đó nên nâng cấp lên mô hình phân cấp (Chương 5) để mỗi danh mục có prior riêng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu Sản phẩm A tiếp tục nhận thêm 19 đánh giá tốt nữa (tổng 20/20), hậu nghiệm trở thành \(\text{Beta}(28, 2)\) với kỳ vọng \(28/30 \approx 93.3\%\) — lúc này bằng chứng đã đủ mạnh để vượt lên trên Sản phẩm B.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aPNrhR0dFi8&quot;&gt;What is a conjugate prior?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Ôn lại điều kiện để prior liên hợp mang lại phép cập nhật gọn, phù hợp với góc nhìn thiết kế hệ thống trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How to Estimate Rates with a Gamma-Poisson Bayesian Model&lt;/td&gt;
          &lt;td&gt;Conjugate Priors](https://www.youtube.com/watch?v=m8roQUqmybg) — Drawing Distributions, English. Minh họa cách mô hình Gamma–Poisson ước lượng tốc độ sự kiện, hỗ trợ ví dụ giám sát tần suất.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=GqSX-8AQL90&quot;&gt;Bayesian Updates and Conjugate Priors&lt;/a&gt; — Steve Brunton, English. Trình bày quá trình cập nhật liên hợp lặp lại khi dữ liệu đến liên tục, gắn với các hệ thống vận hành thời gian thực.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Hai mục có dữ liệu lượt nhấp \((y,n)=(1,2)\) và \((40,100)\). Với prior \(\mathrm{Beta}(2,98)\), trung bình hậu nghiệm của mục nào dịch chuyển mạnh hơn so với tỷ lệ thô, và quyết định sản phẩm nào được rút ra từ đó?&lt;/li&gt;
  &lt;li&gt;Viết câu chuyện sinh dữ liệu cho Thompson sampling với ba tiêu đề email: đại lượng nào quan sát được, đại lượng nào ẩn, và khi nào nên dừng giai đoạn thăm dò?&lt;/li&gt;
  &lt;li&gt;Một bộ giám sát Poisson–Gamma cho ước lượng cường độ rất hẹp sau một cuối tuần yên ắng, nhưng sang thứ Hai lưu lượng tăng gấp mười lần. Giả định nào của mô hình vừa bị phá vỡ?&lt;/li&gt;
  &lt;li&gt;Mở trang tài liệu khởi đầu của PyMC hoặc Stan, tìm một ví dụ liên hợp và một ví dụ không liên hợp; với ví dụ thứ hai, giải thích vì sao xấp xỉ lưới sẽ không khả thi.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 2–3.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 6.&lt;/li&gt;
  &lt;li&gt;Russo, D., Van Roy, B., Kazerouni, A., Osband, I., &amp;amp; Wen, Z. (2018). A tutorial on Thompson sampling. &lt;em&gt;Foundations and Trends in Machine Learning&lt;/em&gt;, 11(1), 1–96.&lt;/li&gt;
  &lt;li&gt;Pancha, N., Zhai, A., Leskovec, J., &amp;amp; Rosenberg, C. (2022). PinnerFormer: Sequence modeling for user representation at Pinterest. &lt;em&gt;KDD&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2205.04507&quot;&gt;arXiv:2205.04507&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Zhang, L., Carpenter, B., Gelman, A., &amp;amp; Vehtari, A. (2022). Pathfinder: Parallel quasi-Newton variational inference. &lt;em&gt;JMLR&lt;/em&gt;, 23(306), 1–49. &lt;a href=&quot;https://arxiv.org/abs/2108.03782&quot;&gt;arXiv:2108.03782&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://mc-stan.org/docs/stan-users-guide/index.html&quot;&gt;Stan User’s Guide&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.pymc.io/projects/docs/en/stable/learn/core_notebooks/pymc_overview.html&quot;&gt;PyMC overview&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://num.pyro.ai/en/stable/getting_started.html&quot;&gt;NumPyro getting started&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 1.5: Ứng dụng hiện đại của định lý Bayes trong khoa học máy tính</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_05_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_05_modern_applications</id>
   <content type="html">&lt;p&gt;Từ một định lý viết trên giấy thế kỷ 18, quy tắc Bayes ngày nay chạy âm thầm bên trong hàng tỷ thiết bị mỗi giây: bộ lọc thư rác chấm điểm từng email mới đến, hệ thống dẫn đường xe tự lái hợp nhất tín hiệu radar và camera theo bộ lọc Kalman/Bayes, còn các nền tảng thử nghiệm sản phẩm trực tuyến dùng cập nhật Bayes để ra quyết định nhanh mà không vướng lỗi &lt;em&gt;optional stopping&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Bài học này khép lại Chương 1 bằng cách nối nền tảng triết học và công thức Bayes với những kiến trúc thực chiến của khoa học máy tính hiện đại.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài học tùy chọn này, bạn sẽ nhìn định lý Bayes không chỉ như một công thức chẩn đoán trong sách giáo khoa, mà như quy tắc cập nhật niềm tin đang vận hành trong bộ lọc thư rác, hệ thống phát hiện gian lận và bài toán định lượng bất định của mô hình ngôn ngữ. Trọng tâm cần thay đổi nằm ở câu hỏi: không dừng ở “công thức viết thế nào?”, mà đặt câu hỏi “prior, likelihood và posterior nằm ở đâu trong một hệ thống thực tế?”.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-định-lý-bayes-trong-hệ-thống-thông-minh-và-khoa-học-máy-tính&quot;&gt;Kiến thức cần nhớ: Định lý Bayes trong Hệ thống Thông minh và Khoa học Máy tính&lt;/h2&gt;

&lt;p&gt;Ba trụ cột sau cho thấy cách định lý Bayes vượt ra khỏi sách giáo khoa để vận hành các hệ thống quy mô lớn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân loại xác suất &amp;amp; Lọc thông tin (Naive Bayes &amp;amp; Probabilistic Classifiers):&lt;/strong&gt; Chuyển bài toán phân loại văn bản, phát hiện gian lận hay chẩn đoán lỗi thành phép tính log-prior cộng tổng log-likelihood từng đặc trưng, cho tốc độ cập nhật trực tuyến cực nhanh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Suy luận trực tuyến &amp;amp; Lọc trạng thái (Recursive Bayesian Filtering):&lt;/strong&gt; Trong robot học, định vị GPS và theo dõi mục tiêu, trạng thái ẩn của hệ thống được cập nhật liên tục theo thời gian qua chu kỳ &lt;em&gt;Dự báo (Predict) → Cập nhật Bayes (Update)&lt;/em&gt; — trong đó bộ lọc Kalman là trường hợp tuyến tính – Gaussian kinh điển.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thử nghiệm thích nghi &amp;amp; Khám phá (Thompson Sampling / Bayesian Optimization):&lt;/strong&gt; Thay vì chia lưu lượng cố định kiểu cổ điển, các hệ thống gợi ý và tối ưu siêu tham số rút mẫu trực tiếp từ hậu nghiệm để tự động cân bằng giữa &lt;em&gt;khai thác&lt;/em&gt; phương án tốt nhất và &lt;em&gt;khám phá&lt;/em&gt; phương án còn nhiều bất định.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-có&quot;&gt;Kiến thức cần có&lt;/h2&gt;

&lt;p&gt;Bài viết kế thừa các bài 1.1–1.4, không lặp lại phần phê phán p-value hay so sánh Bayesian–frequentist mà đưa trực tiếp cùng một sơ đồ cập nhật vào các ứng dụng khoa học máy tính hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;mở-đầu&quot;&gt;Mở đầu&lt;/h2&gt;

&lt;p&gt;Chương 1 đã chỉ ra một mâu thuẫn cốt lõi: p-value trả lời một câu hỏi khác với điều người dùng cần, trong khi việc ra quyết định thực tế lại đòi hỏi xác suất của giả thuyết sau khi quan sát dữ liệu. Bộ lọc thư rác, cổng thanh toán và trợ lý hội thoại (chatbot) đều đối mặt với đúng bài toán này. Chúng phải chuyển một quan sát mới — một email, một giao dịch hay một câu trả lời vừa được sinh ra — thành niềm tin đã cập nhật đủ tin cậy để làm cơ sở hành động. Nếu chỉ dừng ở một điểm số xếp hạng, hệ thống vẫn chưa thể xác định nên giữ im lặng hay phát cảnh báo.&lt;/p&gt;

&lt;h2 id=&quot;phát-triển-khái-niệm&quot;&gt;Phát triển khái niệm&lt;/h2&gt;

&lt;p&gt;Định lý Bayes,&lt;/p&gt;

\[P(H\mid D)=\frac{P(D\mid H)P(H)}{P(D)},\]

&lt;p&gt;vẫn là phép nhân giữa prior và likelihood rồi chuẩn hóa. Trong các hệ thống thực tế, \(H\) có thể là “thư rác”, “giao dịch gian lận” hoặc “câu trả lời vừa sinh ra là đúng”, còn \(D\) là bằng chứng quan sát được. Thách thức chính không nằm ở phép biến đổi đại số, mà ở việc prior thay đổi theo bối cảnh (chẳng hạn tỷ lệ nền của thư rác biến động theo mùa) và sai lầm khi đọc likelihood như thể nó đã là posterior.&lt;/p&gt;

&lt;h2 id=&quot;mô-hình-như-câu-chuyện-sinh-dữ-liệu&quot;&gt;Mô hình như câu chuyện sinh dữ liệu&lt;/h2&gt;

&lt;h3 id=&quot;1-lọc-thư-rác-phát-hiện-lừa-đảo-và-phân-loại-có-hiệu-chỉnh&quot;&gt;1. Lọc thư rác, phát hiện lừa đảo và phân loại có hiệu chỉnh&lt;/h3&gt;

&lt;p&gt;Mô hình sinh cổ điển của Naive Bayes vẫn được vận dụng rộng rãi: mỗi từ hoặc đơn vị văn bản (token) được xem là bằng chứng có điều kiện về nhãn thư rác, sau đó các likelihood được nhân với nhau dưới giả định độc lập có điều kiện. Các hệ thống hiện đại thay từ điển rời rạc bằng các biểu diễn đặc hơn (dense representations), nhưng cấu trúc Bayes không thay đổi: prior là tỷ lệ nền của thư rác; likelihood trả lời câu hỏi “email kiểu này xuất hiện thường xuyên hơn dưới nhãn nào?”; còn posterior là xác suất email là thư rác &lt;em&gt;sau khi đã đọc nội dung&lt;/em&gt;. Nếu ngưỡng hành động bỏ qua tỷ lệ nền, hệ thống đang nhầm lẫn likelihood với posterior — đúng lỗi mà Bài 1.3 đã chỉ ra trong bài toán chẩn đoán y khoa.&lt;/p&gt;

&lt;h4 id=&quot;video-ngắn-bộ-lọc-spam-naive-bayes-nhân-tỷ-số-odds-qua-từng-từ-khóa&quot;&gt;Video ngắn: Bộ lọc Spam Naive Bayes: Nhân Tỷ số Odds qua từng Từ khóa&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-05a-naive-bayes-spam-odds.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 19 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): cập nhật thanh xác suất Spam và tỷ số Odds theo thời gian thực khi quét từ ‘MIỄN PHÍ’ (×8 → 66.7%) và ‘TRÚNG THƯỞNG’ (×5 → 90.9%).&lt;/p&gt;

&lt;h3 id=&quot;2-phát-hiện-gian-lận-thanh-toán-dưới-tỷ-lệ-nền-cực-thấp&quot;&gt;2. Phát hiện gian lận thanh toán dưới tỷ lệ nền cực thấp&lt;/h3&gt;

&lt;p&gt;Giao dịch gian lận chiếm tỷ lệ rất nhỏ, nên prior \(P(H)\) rất thấp. Vì vậy, một tín hiệu “trông có vẻ khả nghi” vẫn có thể chỉ cho ra posterior ở mức vừa phải — đây chính là phiên bản công nghiệp của nghịch lý xét nghiệm bệnh hiếm. Một hệ thống đáng tin cậy phải đưa tỷ lệ nền vào phép tính và chỉ kích hoạt hành động khi posterior vượt ngưỡng được xác định từ chi phí bỏ sót gian lận và chi phí báo động giả. Một điểm xếp hạng cao không đồng nghĩa với xác suất hậu nghiệm cao.&lt;/p&gt;

&lt;h4 id=&quot;video-ngắn-chống-gian-lận-thẻ-tín-dụng-cạm-bẫy-tỷ-lệ-nền-01&quot;&gt;Video ngắn: Chống Gian lận Thẻ tín dụng: Cạm bẫy Tỷ lệ nền 0.1%!&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-05b-fraud-detection-base-rate.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 18 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): trong 10.000 giao dịch (chỉ 10 ca gian lận), AI chính xác 99% vẫn tạo ra 100 cảnh báo giả (90.9%); thêm bằng chứng IP lạ + 3h sáng mới đẩy hậu nghiệm lên 90.9%.&lt;/p&gt;

&lt;h3 id=&quot;3-mô-hình-ngôn-ngữ-tự-đánh-giá-câu-trả-lời-của-chính-mình&quot;&gt;3. Mô hình ngôn ngữ tự đánh giá câu trả lời của chính mình&lt;/h3&gt;

&lt;p&gt;Kadavath et al. (2022) đặt ra một câu hỏi mang đậm tinh thần Bayes: sau khi mô hình ngôn ngữ đề xuất một câu trả lời, xác suất \(P(\text{True})\) rằng câu trả lời ấy đúng là bao nhiêu? Nghiên cứu cho thấy các mô hình lớn có thể được hiệu chỉnh tốt trên các tác vụ đúng/sai có định dạng rõ ràng, và việc tham khảo nhiều mẫu tự sinh trước khi đánh giá một phương án ứng viên giúp cải thiện khả năng tự đánh giá.&lt;/p&gt;

&lt;p&gt;Kuhn, Gal và Farquhar (2023) chỉ ra thêm một điểm nghẽn quan trọng: trong ngôn ngữ tự nhiên, nhiều câu khác nhau về mặt câu chữ nhưng lại mang cùng một ý nghĩa, nên entropy tính trên chuỗi token không phản ánh đúng entropy trên không gian giả thuyết. Phương pháp &lt;em&gt;semantic entropy&lt;/em&gt; nhóm các câu trả lời tương đương về nghĩa lại với nhau rồi mới đo độ bất định — tức là đo phân phối hậu nghiệm trên không gian giả thuyết thay vì trên không gian chuỗi ký tự.&lt;/p&gt;

&lt;h3 id=&quot;4-khai-thác-độ-tin-cậy-đã-hiệu-chỉnh-trực-tiếp-từ-mô-hình&quot;&gt;4. Khai thác độ tin cậy đã hiệu chỉnh trực tiếp từ mô hình&lt;/h3&gt;

&lt;p&gt;Tian et al. (2023) cho thấy rằng với các mô hình ngôn ngữ đã được tinh chỉnh bằng phản hồi của con người, xác suất được diễn đạt trực tiếp bằng lời (chẳng hạn “tôi tin 70%”) đôi khi có độ hiệu chỉnh tốt hơn xác suất điều kiện tính trên token. Điều này không biến chatbot thành một bộ suy luận Bayes chuẩn mực, nhưng cho thấy các hệ thống thực tế đang tìm cách trích xuất một giá trị giống posterior mà người dùng có thể đọc như độ hợp lý (plausibility). Nếu con số đó không khớp với tần suất đúng thực tế, ta lại rơi vào chính vấn đề diễn giải sai mà Chương 1 đã nêu ra từ đầu.&lt;/p&gt;

&lt;h2 id=&quot;diễn-giải-và-nhận-định&quot;&gt;Diễn giải và nhận định&lt;/h2&gt;

&lt;p&gt;Posterior trong các hệ thống này trả lời câu hỏi: “giả thuyết này còn đáng tin đến mức nào sau khi có bằng chứng?”, chứ không trả lời “thuật toán đã bác bỏ giả thuyết đối lập hay chưa”. Một giá trị \(P(\text{True})\) cao trên một câu trả lời ảo giác vẫn có thể xảy ra nếu likelihood được ước lượng quá lạc quan. Định lý Bayes không tự bảo vệ ta khỏi một likelihood sai; nó chỉ buộc ta phải thể hiện minh bạch việc dữ liệu đang kéo prior đi theo hướng nào.&lt;/p&gt;

&lt;h2 id=&quot;ứng-dụng&quot;&gt;Ứng dụng&lt;/h2&gt;

&lt;p&gt;Cả ba lĩnh vực — lọc thư rác/lừa đảo, phát hiện gian lận thanh toán và định lượng bất định ngôn ngữ — đều là các bài toán ra quyết định dưới tỷ lệ nền mất cân bằng và chi phí sai sót không đối xứng. Chúng đặt nền móng trực tiếp cho phân tích quyết định ở Chương 8, nhưng bản chất của chúng đã có thể hiểu rõ chỉ từ định lý Bayes.&lt;/p&gt;

&lt;h2 id=&quot;giới-hạn-và-hướng-mở-rộng&quot;&gt;Giới hạn và hướng mở rộng&lt;/h2&gt;

&lt;p&gt;Giả định độc lập giữa các từ trong Naive Bayes là một mô hình sinh khá thô. Semantic entropy phụ thuộc vào một mô hình đánh giá tương đương nghĩa mà bản thân nó cũng chứa độ bất định. Ngoài ra, một mô hình được hiệu chỉnh tốt trên một bộ tiêu chuẩn đánh giá không bảo đảm vẫn giữ nguyên độ hiệu chỉnh khi phân phối dữ liệu dịch chuyển. Bài học này không đi lại vào lý thuyết cập nhật; Chương 2 sẽ trình bày tường minh các thành phần likelihood, prior và posterior.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-giải-phẫu-bộ-lọc-spam-naive-bayes-trên-thang-tỷ-số-odds&quot;&gt;Giải thích: Giải phẫu bộ lọc spam Naive Bayes trên thang tỷ số Odds&lt;/h2&gt;

&lt;p&gt;Để thấy định lý Bayes hoạt động nhanh và gọn thế nào trong khoa học máy tính, hãy theo dõi 4 bước phân loại một email mới:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Thiết lập tỷ số Odds tiên nghiệm:&lt;/strong&gt; Dựa trên tỷ lệ spam lịch sử \(P(\text{Spam}) / P(\text{Ham})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính hệ số Bayes cho từng từ khóa xuất hiện:&lt;/strong&gt; Với mỗi từ \(w_j\), tính tỷ số \(P(w_j \mid \text{Spam}) / P(w_j \mid \text{Ham})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhân dồn các hệ số Bayes (hoặc cộng trên thang log):&lt;/strong&gt; Dưới giả định độc lập có điều kiện (Naive Bayes), tỷ số Odds hậu nghiệm bằng Odds tiên nghiệm nhân với tích các hệ số Bayes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy đổi sang xác suất hậu nghiệm và áp ngưỡng chi phí:&lt;/strong&gt; \(P(\text{Spam} \mid \mathbf{w}) = \frac{\text{Odds}}{1 + \text{Odds}}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-chấm-điểm-một-email-chứa-hai-từ-khóa&quot;&gt;Ví dụ tính toán làm từng bước: Chấm điểm một email chứa hai từ khóa&lt;/h3&gt;

&lt;p&gt;Giả sử \(20\%\) email đến là Spam (\(\text{Prior Odds} = 0.20 / 0.80 = 0.25\)). Một email chứa đồng thời hai từ khóa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;khuyến mãi&quot;&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;chuyển khoản&quot;&lt;/code&gt; có thống kê như sau:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Từ khóa \(w_j\)&lt;/th&gt;
      &lt;th&gt;\(P(w_j \vert \text{Spam})\)&lt;/th&gt;
      &lt;th&gt;\(P(w_j \vert \text{Ham})\)&lt;/th&gt;
      &lt;th&gt;Hệ số Bayes \(\text{BF}_j = \frac{P(w_j \vert \text{Spam})}{P(w_j \vert \text{Ham})}\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;khuyến mãi&quot;&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;\(0.60\)&lt;/td&gt;
      &lt;td&gt;\(0.10\)&lt;/td&gt;
      &lt;td&gt;\(0.60 / 0.10 = 6.0\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;chuyển khoản&quot;&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;\(0.40\)&lt;/td&gt;
      &lt;td&gt;\(0.05\)&lt;/td&gt;
      &lt;td&gt;\(0.40 / 0.05 = 8.0\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Áp dụng quy tắc nhân tỷ số Odds:&lt;/p&gt;

\[\text{Posterior Odds} = 0.25 \times 6.0 \times 8.0 = 12.0 \implies P(\text{Spam} \mid \mathbf{w}) = \frac{12.0}{1 + 12.0} = \frac{12}{13} \approx 0.9231 \quad (92.31\%).\]

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Quên làm trơn Laplace (&lt;em&gt;Laplace smoothing&lt;/em&gt;) khi gặp một từ chưa từng xuất hiện trong tập Spam lịch sử — lúc đó \(P(w_j \mid \text{Spam}) = 0\) sẽ kéo toàn bộ tích xác suất về 0 bất kể các từ còn lại đáng ngờ đến đâu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu email đó xuất hiện thêm một từ khóa rất đặc trưng cho email công việc (\(\text{BF}_3 = 0.1\)), Odds hậu nghiệm lập tức điều chỉnh về \(12.0 \times 0.1 = 1.2\), tương ứng xác suất spam giảm xuống \(1.2 / 2.2 \approx 54.5\%\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=SqW_p3311yY&quot;&gt;Naive Bayes từ A-Z: Trực Giác đến Toán Học&lt;/a&gt; — Gà AI, Tiếng Việt. &lt;strong&gt;xem trước&lt;/strong&gt;. Giải thích Naive Bayes từ trực giác đến công thức, minh họa trực tiếp cách đặt bộ lọc thư rác vào sơ đồ prior–likelihood–posterior.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=bc-SL86azrc&quot;&gt;Bayes Rule Example of Spam Filter&lt;/a&gt; — Eric Walden, English. Trình bày cách cập nhật xác suất thư rác của một email theo từng bằng chứng, hỗ trợ ví dụ về tỷ lệ nền thay đổi.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=veYq6EWZyVc&quot;&gt;MIT 6.S191: Uncertainty in Deep Learning&lt;/a&gt; — Alexander Amini, English. Giới thiệu về độ bất định trong học sâu; dù không đề cập trực tiếp đến semantic entropy, bài giảng hỗ trợ lập luận không nên đọc điểm số trên token như posterior của giả thuyết.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Tỷ lệ thư rác tăng từ 5% lên 30% trong mùa lễ, trong khi likelihood của một từ khóa không đổi. Posterior của một email chứa từ khóa đó thay đổi ra sao, và vì sao bộ lọc chỉ dựa vào điểm từ khóa sẽ hoạt động kém chính xác?&lt;/li&gt;
  &lt;li&gt;Một cổng thanh toán báo “điểm gian lận 0.95”. Trước khi khóa giao dịch, bạn cần hỏi thêm hai câu nào: một câu về prior và một câu về ngưỡng quyết định?&lt;/li&gt;
  &lt;li&gt;Vì sao entropy tính trên các câu trả lời khác nhau về câu chữ có thể phóng đại độ bất định so với entropy tính trên ý nghĩa? Hãy lấy một câu hỏi có hai cách diễn đạt đều đúng để minh họa.&lt;/li&gt;
  &lt;li&gt;So sánh \(P(\text{True})\) của Kadavath et al. với posterior \(P(H\mid D)\) trong ví dụ chẩn đoán ở Bài 1.3. Thành phần nào đóng vai trò là prior?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 1.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 4–5.&lt;/li&gt;
  &lt;li&gt;Kadavath, S., et al. (2022). Language models (mostly) know what they know. &lt;a href=&quot;https://arxiv.org/abs/2207.05221&quot;&gt;arXiv:2207.05221&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Kuhn, L., Gal, Y., &amp;amp; Farquhar, S. (2023). Semantic uncertainty: Linguistic invariances for uncertainty estimation in natural language generation. &lt;em&gt;ICLR&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2302.09664&quot;&gt;arXiv:2302.09664&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Tian, K., et al. (2023). Just ask for calibration: Strategies for eliciting calibrated confidence scores from language models fine-tuned with human feedback. &lt;a href=&quot;https://arxiv.org/abs/2305.14975&quot;&gt;arXiv:2305.14975&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.20: Ứng dụng hiện đại của xác suất nền tảng trong khoa học dữ liệu</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_20_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_20_modern_applications</id>
   <content type="html">&lt;p&gt;Từ những bài toán tung đồng xu cổ điển ở đầu Chương 0, toàn bộ hệ sinh thái khoa học dữ liệu hiện đại — từ thử nghiệm A/B trực tuyến, dự báo nhu cầu chuỗi cung ứng, đến đánh giá độ tin cậy của mô hình AI — đều đang vận hành trên đúng cùng một khung xác suất nền tảng. Điểm khác biệt duy nhất là quy mô dữ liệu lớn hơn, độ trễ quyết định ngắn hơn và hậu quả của việc hiểu sai xác suất cũng đắt giá hơn.&lt;/p&gt;

&lt;p&gt;Bài tổng kết Chương 0 này nối các khái niệm tưởng chừng rời rạc (phân phối, log-probability, luật số lớn, mô phỏng) thành một bức tranh ứng dụng thực chiến, sẵn sàng đưa bạn bước vào thế giới suy diễn Bayes ở Chương 1.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài đọc mở rộng này, bạn sẽ không còn xem xác suất, phân phối đồng thời (joint distribution), kỳ vọng, log-probability và mô phỏng chỉ là phần “ôn tập trước khi học Bayes”, mà nhận ra chúng chính là ngôn ngữ cốt lõi mà khoa học máy tính và khoa học dữ liệu hiện đại sử dụng khi đánh giá một mô hình có được hiệu chỉnh (calibration) hay không, có ổn định số học hay không, và có phản ánh đúng cơ chế sinh dữ liệu hay không. Mục tiêu là thay đổi góc nhìn: đưa các khái niệm nền tảng trở thành câu hỏi thiết kế trực tiếp cho hệ thống thực tế.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-xác-suất-nền-tảng-trong-hệ-thống-dữ-liệu-và-ai-hiện-đại&quot;&gt;Kiến thức cần nhớ: Xác suất nền tảng trong hệ thống dữ liệu và AI hiện đại&lt;/h2&gt;

&lt;p&gt;Bốn trụ cột dưới đây cho thấy kiến thức Chương 0 được “cài đặt” trực tiếp vào các hệ thống sản phẩm như thế nào:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình sinh dữ liệu trong kỹ thuật phần mềm &amp;amp; ML:&lt;/strong&gt; Các họ phân phối rời rạc/liên tục (Bernoulli, Poisson, Normal, Beta) là viên gạch cơ bản của hàm mất mát: tối thiểu hóa cross-entropy hay MSE thực chất là tối đa hóa log-likelihood của các phân phối này.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính toán số quy mô lớn (Log-space &amp;amp; Vectorization):&lt;/strong&gt; Mọi thư viện hiện đại (PyTorch, JAX, PyMC) đều dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log_softmax&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;logsumexp&lt;/code&gt; và tính toán song song trên GPU/CPU để tránh tràn số khi xử lý hàng triệu điểm dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Định lượng bất định và ra quyết định (Uncertainty Quantification):&lt;/strong&gt; Thay vì chỉ xuất ra một điểm dự báo, các hệ thống hiện đại cần phân phối dự báo đầy đủ để đo rủi ro đuôi, phát hiện lệch phân phối (&lt;em&gt;distribution shift&lt;/em&gt;) và tối ưu hóa quyết định kinh doanh.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-có&quot;&gt;Kiến thức cần có&lt;/h2&gt;

&lt;p&gt;Bài viết giả định bạn đã hoàn thành các bài bắt buộc trong Chương 0. Nội dung không bổ sung lý thuyết xác suất mới, mà đặt câu hỏi điều gì xảy ra khi các khái niệm này bước ra khỏi lớp học để đi vào bộ phân loại, mô hình ngôn ngữ và lập trình xác suất.&lt;/p&gt;

&lt;h2 id=&quot;mở-đầu&quot;&gt;Mở đầu&lt;/h2&gt;

&lt;p&gt;Sau khi học xong Chương 0, bạn đã có thể tính kỳ vọng, viết hàm mật độ và mô phỏng phân phối lấy mẫu. Các hệ thống trong công nghiệp có quy mô lớn hơn nhiều, nhưng thường gặp sự cố từ chính những lỗi nền tảng quen thuộc: con số được báo cáo như xác suất nhưng không khớp tần suất dài hạn, tích các giá trị hợp lý bị underflow về 0, hoặc mô hình đồng thời giả định các biến độc lập trái với thực tế. Câu hỏi trung tâm của bài vì thế giản dị nhưng thiết thực: vì sao nhiều hệ thống hiện đại vẫn ước lượng sai độ bất định dù đã có sẵn lý thuyết nền? Lý do là quy mô dữ liệu hay mô hình không thể thay thế ý nghĩa chặt chẽ của một phát biểu xác suất.&lt;/p&gt;

&lt;h2 id=&quot;phát-triển-khái-niệm&quot;&gt;Phát triển khái niệm&lt;/h2&gt;

&lt;p&gt;Một con số \(p\) gắn kèm dự báo là một phát biểu về quá trình sinh dữ liệu. Nếu mô hình đưa ra \(p=0.9\) cho một trăm trường hợp, thì khoảng chín mươi trường hợp trong số đó cần thực sự xảy ra nếu xác suất đó được hiệu chỉnh tốt — đây chính là tinh thần của phân phối lấy mẫu áp dụng cho điểm số học máy thay vì chỉ cho trung bình mẫu. Cấu trúc phân phối đồng thời cũng quan trọng không kém: khi các biến phụ thuộc nhau, tích của các phân phối biên không còn mô tả đúng thực tế. Và mô phỏng vẫn là cách ít tốn kém nhất để kiểm tra xem giả định mô hình có hợp lý hay không.&lt;/p&gt;

&lt;h2 id=&quot;mô-hình-như-câu-chuyện-sinh-dữ-liệu&quot;&gt;Mô hình như câu chuyện sinh dữ liệu&lt;/h2&gt;

&lt;h3 id=&quot;1-hiệu-chỉnh-xác-suất-của-bộ-phân-loại-và-mô-hình-ngôn-ngữ&quot;&gt;1. Hiệu chỉnh xác suất của bộ phân loại và mô hình ngôn ngữ&lt;/h3&gt;

&lt;p&gt;Bộ lọc thư rác, mô hình phát hiện gian lận và hệ thống cảnh báo y tế đều xuất ra các con số nằm trong đoạn \([0,1]\). Câu hỏi đúng theo góc nhìn sinh dữ liệu không chỉ là “mô hình xếp hạng có tốt không?”, mà là “khi mô hình dự báo \(P(\text{dương}\mid x)=0.8\), liệu có đúng khoảng tám trên mười trường hợp như vậy xảy ra không?” Kadavath et al. (2022) cho thấy các mô hình ngôn ngữ lớn có thể đạt mức hiệu chỉnh khá tốt trên các câu hỏi đúng/sai hoặc trắc nghiệm có định dạng rõ ràng khi được hỏi \(P(\text{True})\) cho câu trả lời vừa sinh. Tian et al. (2023) tiếp tục chỉ ra rằng các mô hình tinh chỉnh theo phản hồi của con người thường cho mức độ tự tin diễn đạt bằng lời (verbalized confidence) được hiệu chỉnh tốt hơn so với xác suất token thô. Bài học từ Chương 0 vẫn giữ nguyên giá trị: một con số nằm trong \([0,1]\) chưa tự động là xác suất cho đến khi nó vượt qua phép kiểm tra hiệu chỉnh theo tần suất.&lt;/p&gt;

&lt;h4 id=&quot;video-ngắn-hiệu-chuẩn-xác-suất-calibration--điểm-brier-trong-ai-hiện-đại&quot;&gt;Video ngắn: Hiệu chuẩn Xác suất (Calibration) &amp;amp; Điểm Brier trong AI Hiện đại&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-22a-calibration.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): vì sao mô hình đoán 90% phải đúng khoảng 90%, cách đọc đường cong hiệu chuẩn (Reliability Diagram) và đo chất lượng xác suất bằng Brier Score / Log-Loss.&lt;/p&gt;

&lt;h3 id=&quot;2-log-probability-và-ổn-định-số-học-trong-mô-hình-lớn&quot;&gt;2. Log-probability và ổn định số học trong mô hình lớn&lt;/h3&gt;

&lt;p&gt;Quá trình huấn luyện và suy luận trên các mạng nơ-ron hiện đại liên tục phải tính tích của rất nhiều xác suất. Chuyển sang thang log giúp biến tích thành tổng:&lt;/p&gt;

\[\log p(x_{1:n})=\sum_{i=1}^{n}\log p(x_i\mid x_{&amp;lt;i}),\]

&lt;p&gt;đây chính là lý do Chương 0 nhấn mạnh log-probability. Đẳng thức này ngăn hàm hợp lý của mô hình ngôn ngữ bị underflow và biến kỹ thuật log-sum-exp thành một phép toán cơ sở tiêu chuẩn. Về mặt lý thuyết, mô hình giả định các token được sinh tuần tự; về mặt thực thi, máy tính chỉ duy trì được tính đúng đắn đó nếu phép tính không sụp về 0.&lt;/p&gt;

&lt;h3 id=&quot;3-phân-phối-đồng-thời-trong-lập-trình-xác-suất&quot;&gt;3. Phân phối đồng thời trong lập trình xác suất&lt;/h3&gt;

&lt;p&gt;Một chương trình viết bằng PyMC hoặc NumPyro thực chất định nghĩa một phân phối đồng thời dưới dạng quy trình sinh dữ liệu: trước hết lấy mẫu tham số, sau đó sinh dữ liệu có điều kiện theo tham số đó. Đây chính là định nghĩa mô hình thống kê của Chương 0 được biểu diễn thành mã để thực hiện suy diễn ở các chương sau. Khi các biến giải thích dạng bảng có phụ thuộc phức tạp, chính phân phối đồng thời — chứ không phải tập hợp các thống kê tóm tắt một chiều rời rạc — mới là đối tượng mà mô hình Bayesian cần mô tả. Grinsztajn, Oyallon và Varoquaux (2022) cũng chỉ ra rằng trên nhiều bài toán dữ liệu bảng thông thường, các mô hình tổ hợp cây vẫn vượt trội mạng học sâu, một phần vì cấu trúc đồng thời của dữ liệu bảng thường rời rạc, không đồng nhất và khó được biểu diễn tốt bởi một hàm mật độ liên tục trơn.&lt;/p&gt;

&lt;h3 id=&quot;4-mô-phỏng-như-phép-kiểm-tra-trực-giác&quot;&gt;4. Mô phỏng như phép kiểm tra trực giác&lt;/h3&gt;

&lt;p&gt;Chương 0 dùng mô phỏng để quan sát biến thiên lấy mẫu. Cùng nguyên lý đó được mở rộng trong thực hành Bayesian thành kiểm tra dự báo hậu nghiệm (posterior predictive check) và hiệu chỉnh dựa trên mô phỏng (simulation-based calibration): rút tham số từ phân phối tiên nghiệm, sinh dữ liệu giả, khớp lại mô hình rồi kiểm tra xem độ bất định thu được có khớp với quy trình sinh hay không (Modrák et al., 2025). Ngay trước khi bước vào Markov chain Monte Carlo, bạn đã nắm được câu hỏi cốt lõi: thuật toán tính toán có tái tạo chính xác mô hình xác suất ban đầu hay không?&lt;/p&gt;

&lt;h2 id=&quot;diễn-giải-và-nhận-định&quot;&gt;Diễn giải và nhận định&lt;/h2&gt;

&lt;p&gt;Trong cả bốn ứng dụng trên, phân phối hậu nghiệm hay điểm xác suất đều dễ bị suy diễn quá mức. Một giá trị \(P(\text{True})\) được hiệu chỉnh tốt chưa đồng nghĩa với việc mô hình thực sự “hiểu” bài toán; một hàm log-likelihood ổn định về mặt số học không biến một hàm hợp lý sai đặc tả thành đúng; và một chương trình xác suất chỉ đáng tin ngang với các giả định độc lập có điều kiện mà nó đặt ra. Thói quen cần duy trì là luôn hỏi: tần suất kiểm chứng là gì, giả định phụ thuộc nào đang được dùng, và phép mô phỏng nào có thể kiểm chứng hoặc bác bỏ tuyên bố đó?&lt;/p&gt;

&lt;h2 id=&quot;ứng-dụng&quot;&gt;Ứng dụng&lt;/h2&gt;

&lt;p&gt;Bốn tình huống trên bao phủ các bài toán xếp hạng, mô hình ngôn ngữ, dữ liệu bảng và phần mềm suy diễn Bayesian. Chúng không phải các chủ đề tách rời, mà là chính kiến thức Chương 0 được thể hiện trong ngôn ngữ thực hành hiện đại của khoa học máy tính và khoa học dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-đường-ống-bayes-thực-chiến-từ-dữ-liệu-thô-đến-quyết-định-tối-ưu&quot;&gt;Video ngắn: Đường ống Bayes Thực chiến: Từ Dữ liệu Thô đến Quyết định Tối ưu&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-22b-decision-pipeline.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): tổng kết 4 mắt xích Chương 00 (Mô hình sinh → Log-prob/MCMC → PPC/Calibration → Lý thuyết Quyết định) qua A/B Testing, chuỗi cung ứng và AI y khoa.&lt;/p&gt;

&lt;h2 id=&quot;giới-hạn-và-hướng-mở-rộng&quot;&gt;Giới hạn và hướng mở rộng&lt;/h2&gt;

&lt;p&gt;Bài viết này không thay thế một học phần về học sâu hay lập trình xác suất. Độ hiệu chỉnh có thể suy giảm khi phân phối dữ liệu dịch chuyển; tính toán trên thang log không khắc phục được mô hình sai đặc tả; và kiểm tra bằng mô phỏng chỉ xác nhận được phần tính toán nằm trong kịch bản bạn đã chạy. Các chương tiếp theo sẽ đi trực tiếp vào quy trình cập nhật Bayesian.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-từ-một-bài-toán-sản-phẩm-thực-tế-về-đúng-mô-hình-xác-suất&quot;&gt;Giải thích: Từ một bài toán sản phẩm thực tế về đúng mô hình xác suất&lt;/h2&gt;

&lt;p&gt;Khi đối diện một bài toán khoa học dữ liệu mới, hãy đi chậm qua bốn bước ánh xạ sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Xác định bản chất biến đầu ra:&lt;/strong&gt; Nhị phân (Bernoulli/Binomial), số đếm (Poisson/Negative Binomial), hay liên tục (Normal/Log-normal/Student-\(t\))?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra hàm mất mát tương đương:&lt;/strong&gt; Chọn hàm mất mát chính là ngầm chọn một giả định likelihood (ví dụ MSE ứng với sai số Gaussian đồng phương sai).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đo bất định ở hai cấp độ:&lt;/strong&gt; Tách biệt bất định ngẫu nhiên tự nhiên (&lt;em&gt;aleatoric&lt;/em&gt; — không giảm khi thêm dữ liệu) và bất định tri thức (&lt;em&gt;epistemic&lt;/em&gt; — giảm theo \(1/\sqrt{n}\) khi thêm dữ liệu).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng bằng mô phỏng trước khi triển khai:&lt;/strong&gt; Sinh dữ liệu giả lập để đo hiệu quả quyết định trước khi chạy trên người dùng thật.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-so-sánh-hàm-mất-mát-log-loss-trên-mô-hình-dự-báo-xác-suất&quot;&gt;Ví dụ tính toán làm từng bước: So sánh hàm mất mát Log-Loss trên mô hình dự báo xác suất&lt;/h3&gt;

&lt;p&gt;Giả sử một mô hình phân loại rủi ro gian lận dự đoán xác suất cho 3 giao dịch có nhãn thật lần lượt là \(y = (1, 0, 1)\). So sánh Mô hình A (hiệu chỉnh tốt) và Mô hình B (quá tự tin và đoán sai giao dịch thứ 3):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Giao dịch&lt;/th&gt;
      &lt;th&gt;Nhãn thật \(y_i\)&lt;/th&gt;
      &lt;th&gt;Dự báo \(p_i\) (Mô hình A)&lt;/th&gt;
      &lt;th&gt;\(-\ln p_i(y_i)\) (A)&lt;/th&gt;
      &lt;th&gt;Dự báo \(p_i\) (Mô hình B)&lt;/th&gt;
      &lt;th&gt;\(-\ln p_i(y_i)\) (B)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;\(1\)&lt;/td&gt;
      &lt;td&gt;\(0.80\)&lt;/td&gt;
      &lt;td&gt;\(-\ln(0.80) \approx 0.223\)&lt;/td&gt;
      &lt;td&gt;\(0.99\)&lt;/td&gt;
      &lt;td&gt;\(-\ln(0.99) \approx 0.010\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;\(0\)&lt;/td&gt;
      &lt;td&gt;\(0.20\)&lt;/td&gt;
      &lt;td&gt;\(-\ln(0.80) \approx 0.223\)&lt;/td&gt;
      &lt;td&gt;\(0.01\)&lt;/td&gt;
      &lt;td&gt;\(-\ln(0.99) \approx 0.010\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;\(1\)&lt;/td&gt;
      &lt;td&gt;\(0.40\)&lt;/td&gt;
      &lt;td&gt;\(-\ln(0.40) \approx 0.916\)&lt;/td&gt;
      &lt;td&gt;\(0.01\)&lt;/td&gt;
      &lt;td&gt;\(-\ln(0.01) \approx 4.605\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Log-loss trung bình&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(0.454\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(1.542\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Dù cả hai mô hình đều đoán đúng 2/3 giao dịch (cùng độ chính xác 66.7%), Mô hình B bị phạt nặng gấp hơn &lt;strong&gt;3 lần&lt;/strong&gt; trên thang log-loss (\(1.542\) so với \(0.454\)) vì quá tự tin khi sai. Đây chính là lý do các hệ thống AI hiện đại ưu tiên điểm chấm xác suất nghiêm ngặt (&lt;em&gt;proper scoring rules&lt;/em&gt;) như log-loss thay vì chỉ nhìn accuracy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Chỉ tối ưu hóa độ chính xác phân loại (accuracy) mà bỏ qua hiệu chỉnh xác suất (&lt;em&gt;calibration&lt;/em&gt;) và log-loss — khiến mô hình đưa ra các quyết định rủi ro cực đoan khi gặp trường hợp biên.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu Mô hình B đoán xác suất \(0.001\) cho một ca dương tính thật, riêng một lỗi đó đã đóng góp \(-\ln(0.001) \approx 6.908\) vào tổng mất mát — lớn hơn tổng sai số của 30 dự đoán có xác suất \(0.80\) cộng lại.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=O2L2Uv9pdDA&quot;&gt;Naive Bayes, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Minh họa Naive Bayes như một bộ phân loại xây dựng trực tiếp từ xác suất có điều kiện.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HghZrdnrNQY&quot;&gt;Why Log Probabilities Are Everywhere in AI - Underflow Error in HMMs and Viterbi Algorithm&lt;/a&gt; — Algorithms and AI, English. Giải thích vì sao các mô hình chuỗi và mô hình ngôn ngữ bắt buộc làm việc trên thang log-probability.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=veYq6EWZyVc&quot;&gt;MIT 6.S191: Uncertainty in Deep Learning&lt;/a&gt; — Alexander Amini, English. Giới thiệu bài toán định lượng độ bất định trong học sâu, cho thấy kỳ vọng và phân phối xác suất được dùng ra sao trong các mô hình hiện đại.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Một mô hình phát hiện gian lận xuất xác suất \(0.99\) trên mười giao dịch, nhưng thực tế chỉ có ba giao dịch được xác nhận là gian lận. Viết một đoạn ngắn giải thích “sai hiệu chỉnh” ở đây nghĩa là gì và bạn sẽ dùng khái niệm nào của Chương 0 để trực quan hóa vấn đề này.&lt;/li&gt;
  &lt;li&gt;Giải thích vì sao xác suất token tiếp theo của một mô hình ngôn ngữ có thể rất tự tin trên không gian token nhưng vẫn còn nhiều bất định trên không gian ngữ nghĩa. Để đánh giá đúng độ bất định ngữ nghĩa, cần thêm khái niệm tương đương hay tính bất biến nào?&lt;/li&gt;
  &lt;li&gt;Viết một câu chuyện sinh dữ liệu gồm bốn dòng (bằng lời, không cần mã nguồn) cho mô hình tỷ lệ chuyển đổi Beta–Binomial, chỉ rõ phân phối đồng thời, phần quan sát được và phần chưa quan sát được.&lt;/li&gt;
  &lt;li&gt;Giả sử một đồng nghiệp cho rằng mô phỏng chỉ dùng để giảng dạy. Dựa trên ý tưởng simulation-based calibration, hãy lập luận về một ứng dụng thực tiễn của mô phỏng trong công nghiệp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., &amp;amp; Rubin, D. B. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 1.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 4–5.&lt;/li&gt;
  &lt;li&gt;Kadavath, S., et al. (2022). Language models (mostly) know what they know. &lt;a href=&quot;https://arxiv.org/abs/2207.05221&quot;&gt;arXiv:2207.05221&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Tian, K., et al. (2023). Just ask for calibration. &lt;a href=&quot;https://arxiv.org/abs/2305.14975&quot;&gt;arXiv:2305.14975&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Grinsztajn, L., Oyallon, E., &amp;amp; Varoquaux, G. (2022). Why do tree-based models still outperform deep learning on typical tabular data? &lt;em&gt;NeurIPS&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Modrák, M., et al. (2025). Simulation-based calibration checking for Bayesian computation. &lt;em&gt;Bayesian Analysis&lt;/em&gt;, 20(2), 461–488. &lt;a href=&quot;https://arxiv.org/abs/2211.02383&quot;&gt;arXiv:2211.02383&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.pymc.io/projects/docs/en/stable/learn/core_notebooks/pymc_overview.html&quot;&gt;PyMC conceptual overview&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 8.5: Modern Applications of Model Checking and Bayesian Decision-Making</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter08/08_05_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter08/08_05_modern_applications</id>
   <content type="html">&lt;p&gt;In modern tech, finance, and healthcare platforms (2022–2026), nobody ships a model just because a notebook printed &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elpd_loo = -124.2&lt;/code&gt;—they ship models that survive &lt;strong&gt;automated Posterior Predictive Checks&lt;/strong&gt;, &lt;strong&gt;PSIS-LOO regression gates&lt;/strong&gt;, and &lt;strong&gt;expected-utility decision rules&lt;/strong&gt; under real dollar constraints! From &lt;strong&gt;inventory optimization (Newsvendor problem)&lt;/strong&gt; to &lt;strong&gt;Bayesian A/B early stopping via Expected Loss&lt;/strong&gt;, Chapter 8’s model-checking and decision machinery is where Bayesian statistics directly creates measurable business value.&lt;/p&gt;

&lt;p&gt;This optional bridge shows how PPC, LOO-CV, and Bayesian Expected Loss operate inside modern decision pipelines.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-three-production-applications-of-chapter-8&quot;&gt;Key ideas: Three Production Applications of Chapter 8&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian A/B Testing via Expected Loss (VWO / GrowthBook):&lt;/strong&gt; Instead of p-values, compute \(\mathbb{E}[\max(\theta_A - \theta_B,\; 0) \mid \text{data}]\)—the expected conversion loss if you ship Variant B and it turns out worse than A—and ship as soon as expected loss drops below your business threshold (e.g., &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.1%&lt;/code&gt;)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Inventory Optimization (Newsvendor Quantile):&lt;/strong&gt; Given a posterior predictive demand distribution \(p(\tilde{y}\mid y)\), stock the exact &lt;strong&gt;critical fractile&lt;/strong&gt; \(q^* = \frac{c_{\text{under}}}{c_{\text{under}} + c_{\text{over}}}\) rather than the mean demand!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Automated Model Monitoring (Online PPC Drift Detection):&lt;/strong&gt; Continuously compare live incoming production data against the model’s posterior predictive intervals—triggering retraining alerts when observed outcomes fall outside the 95% predictive band far more than 5% of the time.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this optional lesson, you will see PPC, LOO/WAIC and decision analysis as a production workflow, not as an “appendix chapter after the fit”. You will connect posterior checks with simulation-based calibration, model comparison with the uncertainty of the LOO difference itself, and the Bayes action rule with Bayesian optimization and bandits.&lt;/p&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;Lessons 8.1–8.4 built PPC, information criteria, model comparison, and decisions under loss. This lesson does not redefine ELPD. It shows how those objects are being tightened in 2022–2025 research and in optimization libraries.&lt;/p&gt;

&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;

&lt;p&gt;Chapter 8 was written because of a bad habit: watching the MCMC chains converge and stopping. In computer science, that habit turns into a green dashboard. A sampler can draw the right samples from the wrong model, or the wrong samples from the right model. A difference \(\Delta\mathrm{ELPD}\) can change sign once you recompute its error. The tension of this lesson is to separate three questions that products tend to mix: can the model generate data of this kind, which model predicts better under the uncertainty of the comparison itself, and what should we &lt;em&gt;do&lt;/em&gt;?&lt;/p&gt;

&lt;h2 id=&quot;conceptual-development&quot;&gt;Conceptual development&lt;/h2&gt;

&lt;p&gt;PPC asks whether \(y^{\mathrm{rep}}\) generated from \(p(y\mid\theta)\) with \(\theta\sim p(\theta\mid y)\) reproduces the structure of \(y\). LOO estimates the expected log predictive density at a new point. Decision theory chooses&lt;/p&gt;

\[a^*(y)=\arg\min_a\int L(a,\theta)\,p(\theta\mid y)\,d\theta.\]

&lt;p&gt;These three objects do not replace each other. A model that wins on LOO can still fail PPC in the tail. An optimal action can choose a model that is &lt;em&gt;worse in log score&lt;/em&gt; if the loss is asymmetric.&lt;/p&gt;

&lt;h2 id=&quot;models-as-generative-stories&quot;&gt;Models as generative stories&lt;/h2&gt;

&lt;h3 id=&quot;1-simulation-based-calibration-as-a-check-of-software-and-inference&quot;&gt;1. Simulation-based calibration as a check of software and inference&lt;/h3&gt;

&lt;p&gt;Modrák et al. (2025) tighten simulation-based calibration: draw \(\theta\) from the prior, generate \(y\), refit, then look at the rank of the test quantity in the posterior. They show that ranking only the parameters misses a whole class of errors—including the case where the posterior equals the prior—and that the likelihood is a sensitive test quantity as well. In industry, this is a unit test for a PyMC/Stan model before it enters an A/B test or pricing. The PPC of Lesson 8.1 checks the model on real data; SBC checks the &lt;em&gt;inference tool&lt;/em&gt; on data generated from the model itself.&lt;/p&gt;

&lt;h3 id=&quot;2-the-uncertainty-of-the-loo-comparison-itself&quot;&gt;2. The uncertainty of the LOO comparison itself&lt;/h3&gt;

&lt;p&gt;Sivula, Magnusson, Matamoros and Vehtari (2025) show that the normal approximation of the LOO difference is often biased when two models predict similarly, when the model is misspecified, or when the sample is small. The skewness of the error may not vanish as \(n\to\infty\) in some situations. The product consequence is very concrete: a model leaderboard must not be published as a hard ranking if the error of \(\Delta\mathrm{ELPD}\) swallows the difference. Lesson 8.3 already said that comparison is a decision under model uncertainty; this paper measures that very uncertainty.&lt;/p&gt;

&lt;h3 id=&quot;3-bayesian-optimization-as-decision-theory-on-an-expensive-function&quot;&gt;3. Bayesian optimization as decision theory on an expensive function&lt;/h3&gt;

&lt;p&gt;When \(\theta\) is a hyperparameter configuration or a lab experiment, each evaluation \(f(\theta)\) is very expensive. Bayesian optimization places a posterior—usually a Gaussian process—on \(f\), then chooses the next point by minimizing expected loss, for example expected improvement. That is Lesson 8.4 written for a continuous action space. BoTorch (Balandat et al., 2020; the 2022–2026 ecosystem) turns this rule into Monte Carlo over the posterior, enough to optimize multiple objectives and constraints. AutoML is an application, not a new theory: choosing models and hyperparameters by Bayes action, not by a blind grid.&lt;/p&gt;

&lt;h3 id=&quot;4-bandits-and-adaptive-experiments&quot;&gt;4. Bandits and adaptive experiments&lt;/h3&gt;

&lt;p&gt;Thompson sampling, which already appeared as a conjugate application in Chapter 2, is now read in its proper place: a sequential approximation of the Bayes action when the loss is regret. Content platforms, advertising, and adaptive clinical trials all update \(p(\theta\mid y)\) and then choose an arm. The decision is not “reject \(H_0\)”; the decision is to continue, stop, or change the allocation ratio. PPC is still needed: if the model gets the tail of conversions wrong, the bandit will exploit a mirage.&lt;/p&gt;

&lt;h2 id=&quot;interpretation-and-insight&quot;&gt;Interpretation and insight&lt;/h2&gt;

&lt;p&gt;A beautiful PPC does not grant a causal license. A LOO difference larger than two standard errors can still be a comparison between two models that are both misspecified. A high expected improvement does not mean the next point will be good; it means that &lt;em&gt;under the current posterior&lt;/em&gt; the value of information exceeds the cost. Keep three layers of interpretation separate: criticism of the data generation, predictive comparison, and action.&lt;/p&gt;

&lt;h2 id=&quot;applications&quot;&gt;Applications&lt;/h2&gt;

&lt;p&gt;Testing models before production, choosing forecasting models for tables and for time series, tuning hyperparameters, and allocating experiments are the four faces of Chapter 8 in CS/DS today.&lt;/p&gt;

&lt;h2 id=&quot;limitations-and-extensions&quot;&gt;Limitations and extensions&lt;/h2&gt;

&lt;p&gt;SBC requires many model fits. LOO assumes that the observations contribute in a nearly factorizable way. Bayesian optimization depends strongly on the prior over \(f\) and will be naive if the noise is misunderstood. The course has no dedicated Gaussian process chapter, so this lesson uses the GP only as a posterior that serves decisions. If a later chapter opens up nonparametrics, you will see that the kernel of BO is exactly that model.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-bayesian-newsvendor-optimal-stocking-quantile&quot;&gt;Worked Numerical Example: Bayesian Newsvendor Optimal Stocking Quantile&lt;/h3&gt;

&lt;p&gt;A bakery earns &lt;strong&gt;\(c_{\text{under}} = \$6\)&lt;/strong&gt; profit per croissant sold (lost profit if it stocks out), and loses &lt;strong&gt;\(c_{\text{over}} = \$2\)&lt;/strong&gt; per unsold croissant thrown away at closing:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Optimal critical fractile:&lt;/strong&gt;
\(q^* = \frac{c_{\text{under}}}{c_{\text{under}} + c_{\text{over}}} = \frac{6}{6 + 2} = \frac{6}{8} = \mathbf{0.75} \quad (\text{75th percentile!}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply to posterior predictive demand&lt;/strong&gt; \(\tilde{y} \sim \mathcal{N}(100,\; 20^2)\) (where the 75th percentile of standard Normal is \(z_{0.75} \approx +0.674\)):
\(Q^* = 100 + 0.674(20) \approx \mathbf{113.5 \to 114\text{ croissants}}!\)
Stocking the &lt;em&gt;mean&lt;/em&gt; (100 croissants) leaves money on the table every busy morning; stocking the &lt;strong&gt;75th posterior predictive percentile (114)&lt;/strong&gt; maximizes expected daily profit!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-shipping-bayesian-decision-systems&quot;&gt;Explanation: Four Rules for Shipping Bayesian Decision Systems&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always evaluate decisions on &lt;em&gt;posterior predictive&lt;/em&gt; draws \(\tilde{y}^{(s)}\), not just parameter draws:&lt;/strong&gt; Real-world profit depends on noisy future outcomes \(\tilde{y}\), not just the noiseless mean \(\mu\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Expected Loss stopping rules are intuitive for executives:&lt;/strong&gt; Saying &lt;em&gt;“if we ship B today, our expected downside risk is under 0.05% conversion”&lt;/em&gt; beats explaining Type I error every time.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pair LOO-CV with domain-specific business metrics:&lt;/strong&gt; A model with slightly higher ELPD should still be checked against actual simulated expected profit.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Re-audit loss weights quarterly:&lt;/strong&gt; When unit margins or cloud costs shift, update \(c_{\text{under}}, c_{\text{over}}\)—your optimal action updates immediately without even retraining the posterior!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the bakery Newsvendor problem above, if profit per sold croissant rises to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;\$8&lt;/code&gt; while waste cost stays &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;\$2&lt;/code&gt;, what is the new optimal stocking quantile \(q^*\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ysITaNRUQUU&quot;&gt;#164 Bayesian Workflow, with Andrew Gelman, Aki Vehtari &amp;amp; Richard McElreath&lt;/a&gt; — Learning Bayesian Statistics, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch Andrew Gelman, Aki Vehtari and Richard McElreath discuss the Bayesian workflow, exactly how the lesson joins model checking with comparison and decision.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[BITESIZE&lt;/td&gt;
          &lt;td&gt;Understanding Simulation-Based Calibration, with Teemu Säilynoja](https://www.youtube.com/watch?v=EC1bvP65rjs) — Learning Bayesian Statistics, English. Watch simulation-based calibration, supporting the part of the lesson that connects posterior predictive checks with checking the inference algorithm itself.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vLx6lUlZ0fc&quot;&gt;Uncertainty in Bayesian leave-one-out cross-validation based model comparison&lt;/a&gt; — Aki Vehtari, English. Watch the uncertainty of LOO model comparison, used for the part of the lesson that does not read an ELPD difference as a hard ranking.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;On a pricing model, distinguish a right-tail PPC failure from an SBC failure. Which one forces you to fix the &lt;em&gt;inference code&lt;/em&gt;, and which one forces you to fix the &lt;em&gt;generative story&lt;/em&gt;?&lt;/li&gt;
  &lt;li&gt;Two models have \(\Delta\mathrm{ELPD}=1.2\) and an error of 1.5. Based on Sivula et al. (2025), what would you write on a slide for the product director?&lt;/li&gt;
  &lt;li&gt;Write the loss of a Bayesian optimization round when each experiment costs a fixed budget and you have five evaluations left. What is the action, and what is the state of the world?&lt;/li&gt;
  &lt;li&gt;A content bandit exploits a clickbait headline early. Which PPC would expose the reward model, and which decision rule would be more cautious than pure Thompson sampling?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 6–7, 9.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 10, 13.&lt;/li&gt;
  &lt;li&gt;Modrák, M., et al. (2025). Simulation-based calibration checking for Bayesian computation. &lt;em&gt;Bayesian Analysis&lt;/em&gt;, 20(2), 461–488. &lt;a href=&quot;https://arxiv.org/abs/2211.02383&quot;&gt;arXiv:2211.02383&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Sivula, T., Magnusson, M., Matamoros, A. A., &amp;amp; Vehtari, A. (2025). Uncertainty in Bayesian leave-one-out cross-validation based model comparison. &lt;em&gt;Bayesian Analysis&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2008.10296&quot;&gt;arXiv:2008.10296&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Balandat, M., et al. (2020). BoTorch: A framework for efficient Monte-Carlo Bayesian optimization. &lt;em&gt;NeurIPS&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/1910.06403&quot;&gt;arXiv:1910.06403&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Russo, D., et al. (2018). A tutorial on Thompson sampling. &lt;em&gt;Foundations and Trends in Machine Learning&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://python.arviz.org/en/stable/api/generated/arviz.plot_ppc.html&quot;&gt;ArviZ posterior predictive checks&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://mc-stan.org/docs/stan-users-guide/posterior-predictive-checks.html&quot;&gt;Stan Workflow / SBC notes&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 7.4: Modern Applications of Priors, Regularization, and Bayesian Deep Learning</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter07/07_04_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter07/07_04_modern_applications</id>
   <content type="html">&lt;p&gt;A standard deep neural network classifying chest X-rays can be &lt;strong&gt;99.8% confident&lt;/strong&gt; even when you accidentally feed it a blurry photo of a golden retriever! Why? Because ordinary neural nets fit a single point estimate (MAP via weight decay = Gaussian prior!) and throw away the entire posterior distribution over weights. &lt;strong&gt;Bayesian Deep Learning (BDL)&lt;/strong&gt; restores honest epistemic uncertainty to modern neural networks—using scalable approximations like &lt;strong&gt;Deep Ensembles&lt;/strong&gt;, &lt;strong&gt;MC Dropout&lt;/strong&gt;, &lt;strong&gt;Last-Layer Laplace&lt;/strong&gt;, and &lt;strong&gt;SWAG&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;This optional bridge links Chapter 7’s priors and regularization directly to 2022–2026 production deep learning: showing how weight decay &lt;em&gt;is&lt;/em&gt; a Gaussian prior, and how ensembling turns neural nets into uncertainty-aware systems that know when to say &lt;em&gt;“I don’t know—escalate to a human!”&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-four-practical-approximations-to-bayesian-deep-learning&quot;&gt;Key ideas: Four Practical Approximations to Bayesian Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Weight Decay = Gaussian Prior MAP:&lt;/strong&gt; Standard &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AdamW&lt;/code&gt; weight decay is literally placing \(\mathbf{w} \sim \mathcal{N}(\mathbf{0}, \tau^2 I)\) and keeping only the single peak—fast, yet blind to posterior width!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Last-Layer Laplace Approximation:&lt;/strong&gt; Freezes the deep feature backbone and computes the exact Hessian covariance \((-\mathbf{H})^{-1}\) only on the final linear layer—adding calibrated Bayesian uncertainty in seconds with zero retraining!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;MC Dropout (Gal &amp;amp; Ghahramani):&lt;/strong&gt; Leaves dropout masks &lt;em&gt;active&lt;/em&gt; at test time and runs \(M\) stochastic forward passes—approximating variational Bayesian inference cheaply.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Deep Ensembles (Lakshminarayanan et al.):&lt;/strong&gt; Trains \(M = 5\) independent networks from different random initializations; their disagreement across predictions is one of the strongest empirical detectors of &lt;strong&gt;Out-of-Distribution (OOD)&lt;/strong&gt; inputs!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this optional lesson, you will read weight decay, the horseshoe, the Laplace approximation, and deep ensembles as different ways of placing a prior on an overly flexible model. The goal is not to memorize algorithm names, but to see that the overfitting of Chapter 7 is exactly why Bayesian deep learning had to be invented: a network has so many parameters that we need a distribution over functions, not a single optimum.&lt;/p&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;Lessons 7.1–7.3 connected priors with regularization, bias–variance, and variable selection. This lesson does not rewrite the shrinkage theory. It only shows that the same logic is being used on neural networks and high-dimensional tabular models in 2021–2024.&lt;/p&gt;

&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;

&lt;p&gt;Chapter 7 opened with a tradeoff: a model soft enough will fit the noise, a model rigid enough will drop the signal. In deep learning, that tradeoff is magnified. Millions of weights can interpolate the training set and still generalize, but the confidence a network attaches to a prediction is usually not a probability. The intellectual tension therefore changes shape. It is no longer “should we add variables?”, but “can we keep a posterior, even only on the last layer, honest enough to know when the model does not know?”.&lt;/p&gt;

&lt;h2 id=&quot;conceptual-development&quot;&gt;Conceptual development&lt;/h2&gt;

&lt;p&gt;A Gaussian prior on the coefficients,&lt;/p&gt;

\[\beta_j\sim\mathcal N(0,\tau^2),\]

&lt;p&gt;is equivalent to weight decay: the MAP is an optimization with an \(L_2\) penalty. The horseshoe and spike-and-slab go further: they allow many coefficients near zero and a few large ones, that is, feature selection as a posterior rather than as a pre-filtering step. When \(\beta\) becomes millions of weights, full MCMC is out of reach. The 2021–2024 approximations—Laplace, last-layer Bayes, ensembles—are different ways of keeping a part of \(p(\theta\mid y)\).&lt;/p&gt;

&lt;h2 id=&quot;models-as-generative-stories&quot;&gt;Models as generative stories&lt;/h2&gt;

&lt;h3 id=&quot;1-regularization-as-a-prior-in-glms-and-shallow-networks&quot;&gt;1. Regularization as a prior in GLMs and shallow networks&lt;/h3&gt;

&lt;p&gt;The generative story does not change: data comes from a simple function plus noise. A narrow prior says “I do not believe the function bends too much”. In credit scoring or tabular ranking, that is often still the right choice, especially since Grinsztajn et al. (2022) show that tree models and regularized linear models remain competitive with deep networks. Chapter 7 is therefore not made obsolete by deep learning; deep learning only makes the prior &lt;em&gt;more mandatory&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;2-laplace-and-the-last-layer-a-local-posterior-at-a-low-price&quot;&gt;2. Laplace and the last layer: a local posterior at a low price&lt;/h3&gt;

&lt;p&gt;Daxberger et al. (2021) build Laplace Redux: take a MAP, approximate the posterior with a Gaussian from the Hessian (or proxies), and turn a trained network into a Bayesian model with few code changes. Harrison, Willes and Snoek (2024) turn the Bayesian last layer into a deterministic variational loss, with no sampling needed, at a cost that grows only with the square of the last-layer dimension. The generative story is deliberately shrunk: the features are treated as already learned, and the remaining uncertainty lives in the readout layer. That is regularization in the form of a distribution over the decision hyperplane.&lt;/p&gt;

&lt;h3 id=&quot;3-do-we-need-a-fully-stochastic-bayesian-network&quot;&gt;3. Do we need a fully stochastic Bayesian network?&lt;/h3&gt;

&lt;p&gt;Sharma, Farquhar, Nalisnick and Rainforth (2023) ask a very Chapter-7 question: is full stochasticity the only way to avoid overfitting and to have a rich predictive distribution? They prove that networks that are only partly stochastic are still universal approximators for conditional distributions, and experimentally find no systematic benefit from making every weight stochastic. Bias–variance here is the cost of memory and the honesty of inference, not only prediction error. The feature selection of Lesson 7.3 reappears in the form of choosing &lt;em&gt;which layer&lt;/em&gt; receives a prior.&lt;/p&gt;

&lt;h3 id=&quot;4-deep-ensembles-as-a-practical-bayesian-approximation&quot;&gt;4. Deep ensembles as a practical Bayesian approximation&lt;/h3&gt;

&lt;p&gt;Deep ensembles—training a few networks from different initializations—remain a strong uncertainty baseline in industry. Wilson and Izmailov have argued that they approximate a mixture over the modes of the posterior. They do not replace the MCMC of Izmailov et al. (2021), but they are how products “buy” posterior diversity when HMC cannot run. Reading an ensemble as several MAPs under an implicit prior, then averaging the predictions, keeps the true spirit of Chapter 7: reduce variance by not trusting a single point.&lt;/p&gt;

&lt;h2 id=&quot;interpretation-and-insight&quot;&gt;Interpretation and insight&lt;/h2&gt;

&lt;p&gt;A narrow Laplace interval around the MAP can miss other modes. A confident last-layer Bayes remains blind if the features have collapsed. A consensus ensemble does not mean the data has proven the hypothesis; the members may share the same systematic error. The prior has done its job when the model &lt;em&gt;refuses&lt;/em&gt; to go too far in sparse regions, not when its confidence is always high.&lt;/p&gt;

&lt;h2 id=&quot;applications&quot;&gt;Applications&lt;/h2&gt;

&lt;p&gt;Tabular scoring, out-of-distribution detection, and the uncertainty of classification networks are three places where Bayesian regularization has become a deployed technique, no longer a metaphor.&lt;/p&gt;

&lt;h2 id=&quot;limitations-and-extensions&quot;&gt;Limitations and extensions&lt;/h2&gt;

&lt;p&gt;Laplace is local. VBLL assumes a linear last layer on fixed features. Ensembles multiply the training cost. No method removes the need for model checking in Chapter 8. This lesson deliberately does not open a separate deep learning chapter; it only shows that the prior of Lesson 7.1 has entered modern networks through narrow doors.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-detecting-an-out-of-distribution-input-with-a-4-model-deep-ensemble&quot;&gt;Worked Numerical Example: Detecting an Out-of-Distribution Input With a 4-Model Deep Ensemble&lt;/h3&gt;

&lt;p&gt;Suppose 4 independently trained ensemble networks predict the probability of pneumonia on two test images:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;In-Distribution Chest X-Ray:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0.82, 0.85, 0.79, 0.86]&lt;/code&gt;
    &lt;ul&gt;
      &lt;li&gt;Mean prediction: \(\bar{p} = \mathbf{0.830}\); Ensemble SD (epistemic disagreement): \(\mathbf{0.032}\) (tight consensus \(\implies\) trust!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Out-of-Distribution Blurry Non-X-Ray Image:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0.91, 0.12, 0.65, 0.30]&lt;/code&gt;
    &lt;ul&gt;
      &lt;li&gt;Mean prediction: \(\bar{p} = \mathbf{0.495}\); Ensemble SD: &lt;strong&gt;\(0.354\)&lt;/strong&gt; (&lt;strong&gt;11× wider epistemic disagreement&lt;/strong&gt; \(\implies\) flag for human doctor review!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-takeaways-on-bayesian-deep-learning-in-practice&quot;&gt;Explanation: Four Takeaways on Bayesian Deep Learning in Practice&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;You don’t need full HMC over 100 million weights to get Bayesian benefits:&lt;/strong&gt; A 5-model Deep Ensemble or a Last-Layer Laplace head captures 90% of practical OOD detection and calibration gains at tiny cost.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Separate &lt;em&gt;epistemic&lt;/em&gt; (model disagreement) from &lt;em&gt;aleatoric&lt;/em&gt; (inherent data noise):&lt;/strong&gt; High epistemic variance means &lt;em&gt;“show this to a human and label it for the next training round”&lt;/em&gt; (Active Learning!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check Expected Calibration Error (ECE) on shifted test sets:&lt;/strong&gt; Standard nets look calibrated on i.i.d. validation sets and fall apart under real-world distribution shift—where Bayesian methods shine brightest.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pair BDL uncertainty with abstention thresholds:&lt;/strong&gt; Allowing a medical or autonomous system to abstain on the top 5% most uncertain inputs often cuts real-world errors by 50%+!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the 4-model ensemble example above, why does a single network with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p = 0.91&lt;/code&gt; fail to warn the hospital about the blurry OOD image, whereas the 4-model ensemble catches it immediately?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=RckG_kNv1Kc&quot;&gt;The Bayesian interpretation of weight decay 43 Machine Learning&lt;/a&gt; — Professor tutorials, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch weight decay read as a prior on the weights, exactly the bridge the lesson draws from regularization to neural networks.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dj-FKXxy7HQ&quot;&gt;Uncertainty estimation and Bayesian Neural Networks - Marcin Możejko&lt;/a&gt; — PyData, English. Watch uncertainty estimation with a Bayesian neural network, supporting the part on overly flexible models needing a prior.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=veYq6EWZyVc&quot;&gt;MIT 6.S191: Uncertainty in Deep Learning&lt;/a&gt; — Alexander Amini, English. Watch the ways deep learning reports uncertainty, including the ensemble family, used for the part of the lesson on deep ensembles.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Rewrite weight decay as a prior. If you decrease \(\tau\), what are you declaring about the data-generating function, and what kind of bias do you accept?&lt;/li&gt;
  &lt;li&gt;A team places Bayes only on the last layer because it is “cheap”. Based on Sharma et al. (2023), argue when that is enough and when fixed features will hide uncertainty.&lt;/li&gt;
  &lt;li&gt;Compare a horseshoe on twenty predictors with dropout on a network. What is being shrunk, and what is hidden as an optimization trick?&lt;/li&gt;
  &lt;li&gt;Laplace Redux uses the Hessian at the MAP. Describe in words a two-mode posterior and say what that approximation would miss.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 14–15.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 17–18.&lt;/li&gt;
  &lt;li&gt;Daxberger, E., et al. (2021). Laplace Redux — effortless Bayesian deep learning. &lt;em&gt;NeurIPS&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Harrison, J., Willes, J., &amp;amp; Snoek, J. (2024). Variational Bayesian last layers. &lt;em&gt;ICLR&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2404.11599&quot;&gt;arXiv:2404.11599&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Sharma, M., Farquhar, S., Nalisnick, E., &amp;amp; Rainforth, T. (2023). Do Bayesian neural networks need to be fully stochastic? &lt;em&gt;AISTATS&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2211.06291&quot;&gt;arXiv:2211.06291&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Izmailov, P., Vikram, S., Hoffman, M. D., &amp;amp; Wilson, A. G. (2021). What are Bayesian neural network posteriors really like? &lt;em&gt;ICML&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 6.4: Modern Applications of Bayesian GLMs</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter06/06_04_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter06/06_04_modern_applications</id>
   <content type="html">&lt;p&gt;Why do premier football analytics desks, insurance actuaries, and tech ad-auction teams still bet billions of dollars on &lt;strong&gt;Bayesian Generalized Linear Models (GLMs)&lt;/strong&gt; in the era of giant Transformers? Because when you need &lt;strong&gt;calibrated probabilities, interpretable risk factors, and hierarchical partial pooling across thousands of sparse entities&lt;/strong&gt; (like pricing insurance for a rare car model or predicting goals for a newly promoted club), hierarchical Bayesian GLMs remain unbeatable!&lt;/p&gt;

&lt;p&gt;This optional bridge connects Chapter 6’s Logistic and Poisson GLMs to real-world systems in 2022–2026: click-through-rate (CTR) ad auctions, insurance claim frequency/severity modeling, and hierarchical sports rating models.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-three-high-stakes-production-uses-of-bayesian-glms&quot;&gt;Key ideas: Three High-Stakes Production Uses of Bayesian GLMs&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Ad-Auction CTR &amp;amp; Conversion Modeling (Logistic GLMs):&lt;/strong&gt; Expected value of showing an ad is \(\text{bid} \times P(\text{click}\mid x)\); calibrated Bayesian posteriors directly power Thompson Sampling and risk-aware bidding.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Actuarial Pricing (Poisson Frequency \(\times\) Gamma Severity):&lt;/strong&gt; Insurance models separate &lt;em&gt;how many claims&lt;/em&gt; (Poisson/NegBin GLM with exposure offset) from &lt;em&gt;how costly each claim is&lt;/em&gt; (Gamma/Log-Normal GLM)—requiring full regulatory interpretability.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hierarchical Sports &amp;amp; Ranking Models (Baio–Blangiardo Poisson GLM):&lt;/strong&gt; Models goals scored as \(\ln\lambda_{ij} = \text{home} + \text{attack}_i - \text{defense}_j\) with hierarchical priors shrinking small-sample teams smoothly toward the league average!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this optional lesson, you can choose a Bayesian GLM because of the &lt;em&gt;generative story of the outcome&lt;/em&gt;, not out of the habit of calling every problem a linear regression. You will recognize logistic, Poisson, and neighboring families running in credit, epidemiology, and marketing measurement, and know that the posterior of a probability or a count intensity must be read together with the decision cost.&lt;/p&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;Lessons 6.1–6.3 built logistic, Poisson, and GLM evaluation. This lesson does not rewrite the link function. It only connects the same models with 2022–2026 systems.&lt;/p&gt;

&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;

&lt;p&gt;Chapter 6 was born because the Gaussian assumption of Chapter 4 cannot withstand binary outcomes and counts. In products, that intolerance shows up immediately: a transaction defaults or not, the number of orders in an hour, the number of cases reported late. If we still optimize least squares, we are telling a generative story that the data could never have lived. The tension of this lesson is to choose the right observation family before discussing deep networks or feature stores.&lt;/p&gt;

&lt;h2 id=&quot;conceptual-development&quot;&gt;Conceptual development&lt;/h2&gt;

&lt;p&gt;A Bayesian GLM keeps a linear structure on a suitable scale,&lt;/p&gt;

\[g(\mathbb E[y_i\mid x_i])=x_i^\top\beta,\]

&lt;p&gt;then places a prior on \(\beta\) and takes the posterior. For logistic, \(g\) is the logit and \(y\) is Bernoulli. For Poisson, \(g\) is the log and \(y\) is a count. The posterior does not return a “predicted class”; it returns a distribution over the probability or over the intensity. A classification threshold appears only later, when a loss function says clearly how much more expensive a false positive is than a false negative.&lt;/p&gt;

&lt;h2 id=&quot;models-as-generative-stories&quot;&gt;Models as generative stories&lt;/h2&gt;

&lt;h3 id=&quot;1-bayesian-logistic-for-credit-fraud-and-clinical-risk&quot;&gt;1. Bayesian logistic for credit, fraud, and clinical risk&lt;/h3&gt;

&lt;p&gt;The generative story: each record has a probability of a rare event, \(\theta(x)=\mathrm{logit}^{-1}(x^\top\beta)\), and then the label is tossed like a biased coin. The prior on \(\beta\) keeps the probability from being pushed to 0 or 1 when a combination of features has never appeared—exactly the spirit of regularization that will be emphasized in Chapter 7. What industry needs from the posterior is not maximum accuracy, but a calibrated probability for setting limits, insurance, or approval thresholds. Grinsztajn, Oyallon and Varoquux (2022) show that on many heterogeneous tables, “shallow” models still beat deep networks; a well-specified Bayesian logistic is therefore not a step backward.&lt;/p&gt;

&lt;h3 id=&quot;2-poisson-and-negative-binomial-for-demand-and-nowcasting&quot;&gt;2. Poisson and Negative Binomial for demand and nowcasting&lt;/h3&gt;

&lt;p&gt;The number of orders, calls, or cases per day is a count. The Poisson story says that the variance equals the mean; in epidemiology and commerce, reality often requires the Negative Binomial when there is overdispersion. In a pandemic, nowcasting must both estimate the intensity and correct the reporting delay. Hierarchical Bayes over geographic groups is the Chapter 6 GLM written as many intercepts. The posterior predictive of next week is not a point; it is a fan of uncertainty that warehouses and hospitals must pay for.&lt;/p&gt;

&lt;h3 id=&quot;3-media-mix-modeling-as-a-causal-glm-with-priors&quot;&gt;3. Media mix modeling as a causal GLM with priors&lt;/h3&gt;

&lt;p&gt;Google Meridian (2024) is a Bayesian marketing-mix framework: sales are told as a function of media channels transformed by adstock and diminishing returns, plus non-media factors, with priors that can be calibrated by experiments. Inference uses MCMC/NUTS. The likelihood is close to regression, but the spirit is a GLM opened up to nonlinear transformations of exposure. The Meridian documentation emphasizes that the goal is causal inference about ROI, not minimizing hold-out prediction error—a direct warning from Chapters 5 and 6: the same model family serves two different questions.&lt;/p&gt;

&lt;h3 id=&quot;4-glm-evaluation-calibration-before-hard-labels&quot;&gt;4. GLM evaluation: calibration before hard labels&lt;/h3&gt;

&lt;p&gt;Lesson 6.3 already warned that the confusion matrix is not cost-neutral. In credit, missing a default is more expensive than a wrong rejection. In epidemiology, missing a cluster is more expensive than an extra alert. Therefore the posterior of \(\theta(x)\) must be checked with a reliability diagram, not only with accuracy. A “less sharp” GLM that is straight on the calibration plot can still be the right decision model.&lt;/p&gt;

&lt;h2 id=&quot;interpretation-and-insight&quot;&gt;Interpretation and insight&lt;/h2&gt;

&lt;p&gt;A logistic coefficient is a change in log-odds, not a constant change in probability. A Poisson coefficient is a change in log-intensity. A posterior interval on media ROI has pooled the uncertainty of the adstock, of the confounder, and of the sampler. No interval becomes a decision until the loss is written.&lt;/p&gt;

&lt;h2 id=&quot;applications&quot;&gt;Applications&lt;/h2&gt;

&lt;p&gt;Credit approval, fraud detection, demand forecasting, nowcasting, and advertising budget allocation are four places where Bayesian GLMs are already infrastructure, not textbook examples.&lt;/p&gt;

&lt;h2 id=&quot;limitations-and-extensions&quot;&gt;Limitations and extensions&lt;/h2&gt;

&lt;p&gt;Meridian warns that a good hold-out does not prove that the media effect is right. Poisson will break with zero-inflation. A linear logistic does not capture deep interactions unless you write them out. Chapter 7 will ask which prior keeps a GLM from overfitting as the number of columns grows.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-partial-pooling-in-a-bayesian-poisson-sportsctr-model&quot;&gt;Worked Numerical Example: Partial Pooling in a Bayesian Poisson Sports/CTR Model&lt;/h3&gt;

&lt;p&gt;Suppose the league average scoring rate is &lt;strong&gt;1.40 goals/game&lt;/strong&gt; (prior \(\mathrm{Gamma}(\alpha=7,\; \beta=5)\), equivalent to 5 pseudo-games). A newly promoted team scores &lt;strong&gt;4 goals in its very first match&lt;/strong&gt; (\(n = 1\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Unpooled MLE:&lt;/strong&gt; \(\hat{\lambda}_{\text{MLE}} = 4 / 1 = \mathbf{4.00}\) goals/game (absurdly predicting a 152-goal season!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Conjugate Posterior:&lt;/strong&gt; \(\mathrm{Gamma}(7 + 4,\; 5 + 1) = \mathrm{Gamma}(11,\; 6) \implies \hat{\lambda}_{\text{post}} = \frac{11}{6} \approx \mathbf{1.83}\) goals/game!
The Bayesian GLM gives genuine credit for the strong opener (lifting the team from \(1.40 \to 1.83\)) while refusing to overreact to a 1-game fluke!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-reasons-bayesian-glms-still-thrive-alongside-deep-learning&quot;&gt;Explanation: Four Reasons Bayesian GLMs Still Thrive Alongside Deep Learning&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tabular &amp;amp; sparse-group data favors structured hierarchical priors:&lt;/strong&gt; Deep nets struggle with 500 small groups of 3 rows each; hierarchical GLMs borrow strength across groups automatically.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Auditability and regulatory compliance:&lt;/strong&gt; Insurance, healthcare, and credit teams must explain &lt;em&gt;why&lt;/em&gt; a rate changed—log-odds and rate ratios provide transparent audits.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Natural handling of exposure, censoring, and domain offsets:&lt;/strong&gt; Putting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(policy_years)&lt;/code&gt; directly in a Poisson GLM encodes domain physics with zero extra parameters.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hybrid architectures combine both worlds:&lt;/strong&gt; Use a neural embedding for text/images and feed it into a calibrated Bayesian GLM head for final uncertainty-aware decisions!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the football example above, after the same team plays &lt;strong&gt;20 matches&lt;/strong&gt; and scores &lt;strong&gt;40 total goals&lt;/strong&gt; (2.00 goals/game), what is its updated \(\mathrm{Gamma}(7+40,\; 5+20)\) posterior mean—and how close is it now to the raw sample average?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Explaining generalized linear models (GLMs)&lt;/td&gt;
          &lt;td&gt;VNT #15](https://www.youtube.com/watch?v=1fZeBafD1nw) — Very Normal, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch GLMs chosen by the type of outcome variable, exactly the habit the lesson wants in place of calling every problem a linear regression.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=J4zNmGqttVo&quot;&gt;GLM Intro - 4 - Link Function&lt;/a&gt; — Meerkat Statistics, English. Watch the link function connect the mean of the outcome with the linear part, supporting logistic and Poisson in real systems.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zffwg0xDOgE&quot;&gt;Statistical Rethinking 2023 - 19 - Generalized Linear Madness&lt;/a&gt; — Richard McElreath, English. Watch GLMs pushed beyond the textbook form, used for the part of the lesson on model families close to logistic and Poisson.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;A default model reaches 98% accuracy because only 2% of records default. The posterior mean of \(\theta(x)\) in the high-risk group is 0.15. Why is accuracy hiding exactly the subjects that the Bayesian GLM cares about?&lt;/li&gt;
  &lt;li&gt;Write the generative story for the number of orders per hour at a warehouse. When do you move from Poisson to Negative Binomial, and how will the posterior predictive change shape?&lt;/li&gt;
  &lt;li&gt;Meridian advises against taking hold-out prediction as the main criterion. Connect that statement with the difference between prediction and causal inference in Chapter 5.&lt;/li&gt;
  &lt;li&gt;Choose a logistic threshold when a false negative is ten times as expensive as a false positive. Which additional object of the posterior do you need, not only \(\hat\beta\)?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 16.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 21–22.&lt;/li&gt;
  &lt;li&gt;Grinsztajn, L., Oyallon, E., &amp;amp; Varoquaux, G. (2022). Why do tree-based models still outperform deep learning on typical tabular data? &lt;em&gt;NeurIPS&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Google. (2024). &lt;em&gt;Meridian&lt;/em&gt;: Bayesian marketing mix modeling. &lt;a href=&quot;https://developers.google.com/meridian/docs/causal-inference/bayesian-inference&quot;&gt;Bayesian inference&lt;/a&gt;; &lt;a href=&quot;https://github.com/google/meridian&quot;&gt;GitHub&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://mc-stan.org/docs/stan-users-guide/index.html&quot;&gt;Stan User’s Guide, GLM chapters&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.pymc.io/projects/docs/en/stable/learn/core_notebooks/GLM_linear.html&quot;&gt;PyMC GLM examples&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 5.5: Modern Applications of Multiple Regression and Causal Thinking</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter05/05_05_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter05/05_05_modern_applications</id>
   <content type="html">&lt;p&gt;When a streaming service launches a $20 million Super Bowl ad campaign, they can’t run a clean user-level A/B test—everybody in the broadcast region sees the ad! How do modern tech and economics teams measure the true causal lift without a randomized trial? They combine Chapter 5’s &lt;strong&gt;Bayesian multiple regression + DAG causal thinking&lt;/strong&gt; into &lt;strong&gt;Bayesian Structural Time Series (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CausalImpact&lt;/code&gt;)&lt;/strong&gt;, &lt;strong&gt;Geo-Lift Difference-in-Differences&lt;/strong&gt;, and &lt;strong&gt;Uplift Modeling&lt;/strong&gt;—delivering full posterior distributions over incremental revenue!&lt;/p&gt;

&lt;p&gt;This optional bridge shows how causal DAGs and Bayesian regression power real-world industry decisions in 2022–2026.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-three-production-causal-bayesian-frameworks&quot;&gt;Key ideas: Three Production Causal-Bayesian Frameworks&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Difference-in-Differences &amp;amp; Geo-Lift:&lt;/strong&gt; Compares a treated city’s pre-to-post jump against a synthetic control of untreated cities, yielding \(P(\text{ROI} &amp;gt; 1 \mid \text{data})\) directly.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Structural Time Series (CausalImpact):&lt;/strong&gt; Predicts the counterfactual trajectory &lt;em&gt;“what sales would have been without the campaign”&lt;/em&gt; using correlated control markets, then subtracts counterfactual draws from observed sales to get a full posterior over cumulative lift!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Heterogeneous Treatment Effects (Interactions / Uplift):&lt;/strong&gt; Models &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;outcome ~ treatment * user_segment&lt;/code&gt; with shrinkage priors to identify &lt;em&gt;which&lt;/em&gt; customers actually respond positively vs. which ones are unaffected or annoyed.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this optional lesson, you can read a coefficient in a multi-predictor model as a conditional causal claim, not as a coefficient that is “more important” just because the software printed it. You will see that confounding, multicollinearity and interactions are not regression bugs, but the shape of product data: A/B tests on marketplaces, recommender systems, and medical records over time.&lt;/p&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;Lessons 5.1–5.4 laid out multiple regression, DAGs, multicollinearity and interactions. This lesson does not redraw the definition of the back-door. It only brings those same diagrams into 2022–2026 papers and systems.&lt;/p&gt;

&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;

&lt;p&gt;Chapter 5 begins with a familiar disappointment: adding variables raises \(R^2\), but the story about “impact” falls apart. In applied computer science, that disappointment is more expensive. A platform can add hundreds of features to a ranking model and then claim to have “controlled for everything”. If one of those features is a mediator or a collider, the coefficient of the treatment is no longer the effect we want. The tension of this lesson is: the more columns the data has, the more a DAG is needed, not the less.&lt;/p&gt;

&lt;h2 id=&quot;conceptual-development&quot;&gt;Conceptual development&lt;/h2&gt;

&lt;p&gt;A coefficient \(\beta_j\) in&lt;/p&gt;

\[y_i=\alpha+\sum_j\beta_j x_{ij}+\varepsilon_i\]

&lt;p&gt;has a causal meaning only after the set of controls has blocked the back-door paths and has not opened new ones. Cinelli, Forney and Pearl (2022) name exactly this problem good and bad controls: not every “related” covariate should enter the equation. Interaction says something else, namely that \(\beta_j\) itself can be a function of another variable. Multicollinearity is not causal bias; it is posterior uncertainty swelling when the columns tell the same story.&lt;/p&gt;

&lt;h2 id=&quot;models-as-generative-stories&quot;&gt;Models as generative stories&lt;/h2&gt;

&lt;h3 id=&quot;1-good-and-bad-controls-in-product-experiments&quot;&gt;1. Good and bad controls in product experiments&lt;/h3&gt;

&lt;p&gt;The generative story of an A/B test on a marketplace often comes with built-in confounding: users are active, supply and demand move together, and an intervention on one side changes the other side. Adding the variable “number of clicks after seeing the variant” can be a bad control if the click lies on the path from treatment to revenue. Cinelli et al. (2022) give a catalog of small DAGs where the intuition “the more you control, the cleaner” fails. An honest experimentation team draws the DAG before opening the feature store, and only then asks which variables the Bayesian regression should condition on.&lt;/p&gt;

&lt;h3 id=&quot;2-learning-dags-and-the-limits-of-optimization&quot;&gt;2. Learning DAGs and the limits of optimization&lt;/h3&gt;

&lt;p&gt;Bello, Aragam and Ravikumar (2022) reduce DAG learning to a log-det acyclicity characterization on an M-matrix, then optimize continuously (DAGMA). This is a clear computer science development: instead of assuming the graph, we try to learn it. But the generative story still needs assumptions—usually an additive structural equation model with independent noise. A DAG learned from click logs is not automatically the business DAG. The multiple regression of Chapter 5 still needs an analyst who takes responsibility for the unobserved arrows.&lt;/p&gt;

&lt;h3 id=&quot;3-causal-transformers-for-outcomes-over-time&quot;&gt;3. Causal transformers for outcomes over time&lt;/h3&gt;

&lt;p&gt;Melnychuk, Frauen and Feuerriegel (2022) build the Causal Transformer to estimate counterfactual outcomes on longitudinal data, for example treatment protocols in MIMIC. The generative story is: covariates over time, treatment, and outcome depend on one another over a long horizon; confounding changes over time. The transformer architecture does not remove confounding. It tries to learn a representation that predicts the outcome but does &lt;em&gt;not&lt;/em&gt; predict the current treatment assignment, through an adversarial loss. This is the deep learning version of the same Chapter 5 idea: to make the treatment’s \(\beta\) readable, you must block the confounding path, not add layers to the network.&lt;/p&gt;

&lt;h3 id=&quot;4-interactions-and-multicollinearity-in-personalization&quot;&gt;4. Interactions and multicollinearity in personalization&lt;/h3&gt;

&lt;p&gt;A recommender that writes “the effect of a discount depends on how new the user is” is exactly an interaction. Two nearly collinear embeddings will give a wide posterior on each coefficient even though the forecast is still good—exactly the phenomenon of Lesson 5.3. In products, this means: do not interpret each embedding coordinate as a mechanism; interpret the predictions and the named interactions.&lt;/p&gt;

&lt;h2 id=&quot;interpretation-and-insight&quot;&gt;Interpretation and insight&lt;/h2&gt;

&lt;p&gt;A narrow posterior interval on \(\beta_{\text{treatment}}\) after stuffing in twenty controls is not causal evidence. It may be a bad control that has blocked the path or a collider that has opened a path. Conversely, a wide interval after conditioning on exactly the minimal set can still be an honest estimate. Chapter 5 teaches the right order: DAG first, narrowness second.&lt;/p&gt;

&lt;h2 id=&quot;applications&quot;&gt;Applications&lt;/h2&gt;

&lt;p&gt;Marketplace experiments, controlled ranking, personalized treatment, and embedding interpretation are all multiple regression plus a causal question. Bayes adds something that OLS often hides: the uncertainty that remains after the structure has been declared.&lt;/p&gt;

&lt;h2 id=&quot;limitations-and-extensions&quot;&gt;Limitations and extensions&lt;/h2&gt;

&lt;p&gt;Learning a DAG from observations does not solve non-identifiability when assumptions are missing. The Causal Transformer needs assumptions about temporal ordering and about the ability to balance the representation. This lesson does not replace a course on causal inference. Chapter 6 will change the likelihood family when \(y\) is no longer Gaussian, but the confounding problem still follows.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-bayesian-geo-lift-difference-in-differences-calculation&quot;&gt;Worked Numerical Example: Bayesian Geo-Lift Difference-in-Differences Calculation&lt;/h3&gt;

&lt;p&gt;A retailer runs a TV campaign in &lt;strong&gt;City A (Treated)&lt;/strong&gt; while holding &lt;strong&gt;City B (Control)&lt;/strong&gt; unchanged. Weekly sales ($K):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Region&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Pre-Campaign Avg&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Post-Campaign Avg&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Pre \(\to\) Post Change&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;City A (Treated)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(100\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(114\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+14\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;City B (Control)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(100\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(104\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+4\) (seasonal trend!)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Naive before/after estimate (WRONG — confounded by seasonality!):&lt;/strong&gt; \(114 - 100 = +14\text{K}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Difference-in-Differences causal lift:&lt;/strong&gt; \((114 - 100) - (104 - 100) = \mathbf{+10\text{K}}\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian decision check:&lt;/strong&gt; Suppose the posterior for causal lift is \(\Delta \sim \mathcal{N}(+10\text{K},\; 3\text{K}^2)\) and the campaign cost \(C = \$7\text{K}\). Then the posterior probability the campaign was profitable is \(P(\Delta &amp;gt; 7) = P(Z &amp;gt; -1.0) \approx \mathbf{84.1\%}\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-applied-causal-bayes-in-industry&quot;&gt;Explanation: Four Rules for Applied Causal Bayes in Industry&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check the parallel-trends assumption before trusting DiD:&lt;/strong&gt; Verify that Treatment and Control tracked closely &lt;em&gt;before&lt;/em&gt; launch; if they were already diverging, your counterfactual is biased.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Separate marketing spend &lt;em&gt;correlation&lt;/em&gt; from incremental &lt;em&gt;causality&lt;/em&gt;:&lt;/strong&gt; Ad platforms naturally target users who were already about to buy (confounding!); geo-experiments break that confounding cleanly.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Report probability of beating the break-even cost, not just &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lift &amp;gt; 0&lt;/code&gt;:&lt;/strong&gt; A +$2K lift that costs $7K to run is a losing campaign even if \(P(\text{lift} &amp;gt; 0) = 99\%\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use regularizing priors on segment interactions:&lt;/strong&gt; Without shrinkage, slicing a geo-lift test into 20 regions will always make 2 lucky regions look like “miracle markets.”&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the Geo-Lift example above, if the campaign cost were &lt;strong&gt;\(\$10\text{K}\)&lt;/strong&gt; (equal to the posterior mean lift), what is \(P(\Delta &amp;gt; 10\text{K})\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=IFgHw_E521U&quot;&gt;A Crash Course in Good and Bad Controls with Carlos Cinelli&lt;/a&gt; — Spark: a centre for social research innovation, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch a short course on good and bad controls, exactly how the lesson reads a coefficient as a conditional causal claim.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=uanZZLlzKHw&quot;&gt;Statistical Rethinking 2023 - 06 - Good &amp;amp; Bad Controls&lt;/a&gt; — Richard McElreath, English. Watch the good and bad control graphs, supporting the part that says confounding is not a bug of regression software.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=IajzIKW518M&quot;&gt;Causality: Closing Back Doors&lt;/a&gt; — Econometrics, Causality, and Coding with Dr. HK, English. Watch closing backdoors on a DAG, used where the lesson connects multicollinearity and interactions with the causal question.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Draw a three-node DAG for “ad display → click → purchase”. If the goal is the effect of display on purchase, is conditioning on click in the regression a good or bad control, and why?&lt;/li&gt;
  &lt;li&gt;A personalization model has two features correlated at 0.97. The hold-out forecast is good but the two coefficients flip sign when you drop one percent of the data. Which coefficient would you interpret, if any?&lt;/li&gt;
  &lt;li&gt;The Causal Transformer minimizes the ability to predict treatment from the representation. Which confounding of Lesson 5.2 is that aiming at?&lt;/li&gt;
  &lt;li&gt;DAGMA returns a graph from a product log. List two arrows that you do &lt;em&gt;not&lt;/em&gt; allow the model to draw by itself unless there is domain knowledge.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 5, 14.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 18.&lt;/li&gt;
  &lt;li&gt;Cinelli, C., Forney, A., &amp;amp; Pearl, J. (2022). A crash course in good and bad controls. &lt;em&gt;Sociological Methods &amp;amp; Research&lt;/em&gt;. &lt;a href=&quot;https://doi.org/10.1177/00491241221099552&quot;&gt;doi:10.1177/00491241221099552&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Bello, K., Aragam, B., &amp;amp; Ravikumar, P. (2022). DAGMA: Learning DAGs via M-matrices and a log-determinant acyclicity characterization. &lt;em&gt;NeurIPS&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2209.08011&quot;&gt;arXiv:2209.08011&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Melnychuk, V., Frauen, D., &amp;amp; Feuerriegel, S. (2022). Causal Transformer for estimating counterfactual outcomes. &lt;em&gt;ICML&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2204.07258&quot;&gt;arXiv:2204.07258&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 4.7: Modern MCMC — NUTS, HMC and Bayesian Regression in Practice</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_07_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_07_modern_applications</id>
   <content type="html">&lt;p&gt;Why did Bayesian statistics explode from a niche academic corner into the backbone of modern scientific modeling, epidemiology, and probabilistic ML over the past decade? The turning point was not a new theorem—it was a physics-inspired sampler called &lt;strong&gt;Hamiltonian Monte Carlo (HMC)&lt;/strong&gt; and its self-tuning heir, &lt;strong&gt;NUTS&lt;/strong&gt; (the No-U-Turn Sampler). By treating the negative log-posterior as a frictionless landscape and rolling a marble across it using exact gradients, NUTS turns high-dimensional posteriors that once took weeks into seconds—and even sounds an alarm (&lt;strong&gt;divergent transitions&lt;/strong&gt;) whenever the geometry gets treacherous.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lesson Roadmap:&lt;/strong&gt; How physics revolutionized Bayesian computation → Key ideas (Hamiltonian dynamics &amp;amp; leapfrog integration, NUTS adaptive trajectory length, Divergences as geometric alarms) → Hand-worked 1-step leapfrog integration conserving energy → Modern applications, limitations, and exercises.&lt;/p&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this optional lesson, you understand that Hamiltonian Monte Carlo and NUTS are not decorative algorithms added after Bayesian linear regression, but an inevitable consequence once the posterior no longer has a closed form. You will be able to read a Stan, PyMC or NumPyro chain as a controlled approximation of the same generative model that Chapter 4 wrote in words.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-why-hmc-and-nuts-power-modern-bayesian-practice&quot;&gt;Key ideas: Why HMC and NUTS Power Modern Bayesian Practice&lt;/h2&gt;

&lt;h3 id=&quot;1-hamiltonian-dynamics-and-symplectic-leapfrog-integration&quot;&gt;1. Hamiltonian Dynamics and Symplectic (Leapfrog) Integration&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Augmenting parameter position \(q\) with an auxiliary momentum \(p \sim \mathrm{Normal}(0, M)\) and simulating Hamilton’s equations for total energy \(H(q, p) = U(q) + K(p)\), where potential energy \(U(q) = -\log \tilde{\pi}(q)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Proposing distant, nearly independent points across a high-dimensional posterior with acceptance rates near \(80\%\text{–}99\%\) because symplectic leapfrog steps nearly conserve total energy \(H\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-the-no-u-turn-sampler-nuts&quot;&gt;2. The No-U-Turn Sampler (NUTS)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Hoffman &amp;amp; Gelman’s (2014) recursive tree-building extension of HMC that automatically stops integrating the moment the trajectory begins to U-turn back toward its starting point.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Eliminating manual tuning of trajectory length \(L\) (and adapting step size \(\varepsilon\) + mass matrix \(M\) during warmup), powering Stan, PyMC, and NumPyro.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-divergent-transitions-as-built-in-geometry-detectors&quot;&gt;3. Divergent Transitions as Built-In Geometry Detectors&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Steps where the leapfrog integrator’s energy error \(\vert \Delta H \vert\) blows up because curvature changes faster than step size \(\varepsilon\) (such as Neal’s funnel in hierarchical models).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Turning numerical failure into an actionable diagnostic—unlike random-walk MH, which silently misses narrow funnels without warning.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;explanation-one-leapfrog-step-of-hmc-by-hand&quot;&gt;Explanation: One Leapfrog Step of HMC by Hand&lt;/h2&gt;

&lt;p&gt;Take the 1D standard normal posterior \(\tilde{\pi}(q) = e^{-q^2/2}\), so potential energy is \(U(q) = \frac{1}{2}q^2\) (gradient \(\nabla U(q) = q\)) and kinetic energy is \(K(p) = \frac{1}{2}p^2\). Start at position \(q_0 = 1.0\) with momentum \(p_0 = 0.0\), giving initial energy:
\(H_0 = U(1.0) + K(0.0) = \frac{1.0^2}{2} + 0 = \mathbf{0.5000}.\)
Now take &lt;strong&gt;one leapfrog step&lt;/strong&gt; with a huge step size \(\varepsilon = 0.5\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Half-step momentum:&lt;/strong&gt; \(p_{1/2} = p_0 - \frac{\varepsilon}{2}\nabla U(q_0) = 0 - 0.25(1.0) = \mathbf{-0.25}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Full-step position:&lt;/strong&gt; \(q_1 = q_0 + \varepsilon\,p_{1/2} = 1.0 + 0.5(-0.25) = \mathbf{0.875}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Half-step momentum:&lt;/strong&gt; \(p_1 = p_{1/2} - \frac{\varepsilon}{2}\nabla U(q_1) = -0.25 - 0.25(0.875) = \mathbf{-0.46875}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check energy conservation:&lt;/strong&gt;
\(H_1 = \frac{0.875^2}{2} + \frac{(-0.46875)^2}{2} = 0.38281 + 0.10986 = \mathbf{0.49268}.\)
Energy drift is a tiny \(\Delta H = H_1 - H_0 = -0.00732\), so the Metropolis acceptance probability is \(\min(1, e^{-\Delta H}) = \mathbf{1.000}\)! Even with a coarse step \(\varepsilon = 0.5\), the leapfrog integrator glides smoothly toward the high-probability region while conserving energy to within \(1.5\%\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;Lessons 4.1–4.6 built linear regression as a generative story, chose priors, and obtained the posterior with PyMC. Lesson 4.2b covered MCMC at the level of classroom theory. This lesson does not rewrite Metropolis. It asks what modern samplers are doing in 2022–2026 systems, and why linear regression is still the most-sampled model.&lt;/p&gt;

&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;

&lt;p&gt;Once a model has an intercept, a slope, a variance, and a few predictors, the prior–likelihood product can no longer be integrated by hand. The grid of Chapter 2 explodes in the number of cells. Exact theory therefore becomes insufficient, not because the Bayesian idea has weakened, but because the geometry of the posterior has outgrown the paper. The tension of this lesson is: if we cannot draw the posterior, can we still trust the sequence of numbers the machine returns?&lt;/p&gt;

&lt;h2 id=&quot;conceptual-development&quot;&gt;Conceptual development&lt;/h2&gt;

&lt;p&gt;Hamiltonian Monte Carlo uses the gradient of the log-posterior to propose long moves that are still accepted. NUTS (No-U-Turn Sampler) stops the trajectory when it begins to turn back, so the user does not have to choose the trajectory length by hand. What the sampler approximates is the expectation under the posterior,&lt;/p&gt;

\[\mathbb E[g(\theta)\mid y]\approx\frac{1}{S}\sum_{s=1}^{S}g(\theta^{(s)}),\qquad \theta^{(s)}\sim p(\theta\mid y),\]

&lt;p&gt;the same object that Bayesian regression uses for coefficients, for predictions, and for posterior intervals. The software does not replace the model; it replaces the scratch paper.&lt;/p&gt;

&lt;h2 id=&quot;models-as-generative-stories&quot;&gt;Models as generative stories&lt;/h2&gt;

&lt;h3 id=&quot;1-nuts-in-stan-pymc-and-numpyro-for-hierarchical-regression&quot;&gt;1. NUTS in Stan, PyMC and NumPyro for hierarchical regression&lt;/h3&gt;

&lt;p&gt;The generative story is still: parameters ~ prior, data ~ normal around a plane. The industrial difference is that this plane has an intercept by country, by campaign, or by server. The Stan User’s Guide and the PyMC/NumPyro notebooks all take NUTS as the default because the gradient of the log-density can be obtained by automatic differentiation. When you read a credible interval for an advertising coefficient, you are reading a summary of a NUTS chain, not an OLS formula.&lt;/p&gt;

&lt;h3 id=&quot;2-pathfinder-as-a-warm-start-not-a-replacement-for-mcmc&quot;&gt;2. Pathfinder as a warm start, not a replacement for MCMC&lt;/h3&gt;

&lt;p&gt;Zhang, Carpenter, Gelman and Vehtari (2022) propose Pathfinder: follow a quasi-Newton optimization path, place Gaussian approximations along the path, and then sample from the approximation with the smallest KL. On many posteriors, those samples are better than ADVI and cheaper than a short HMC chain, so Stan and JAX libraries use Pathfinder to initialize NUTS. The pedagogical meaning fits Chapter 4 exactly. Variational inference appears because MCMC needs a good place to stand, not because the posterior has been replaced by an optimization.&lt;/p&gt;

&lt;h3 id=&quot;3-blackjax-and-composable-mcmc-on-accelerators&quot;&gt;3. BlackJAX and composable MCMC on accelerators&lt;/h3&gt;

&lt;p&gt;Cabezas et al. (2024) describe BlackJAX as a box of statistical atoms—Metropolis steps, Hamiltonian dynamics, Langevin mechanisms—written in JAX to compile onto GPUs and TPUs. Bayesian regression is then no longer “one chain on a laptop”, but the same log-density running thousands of chains in parallel. The generative story does not change; the compute budget does.&lt;/p&gt;

&lt;h3 id=&quot;4-mcmc-for-bayesian-neural-networks&quot;&gt;4. MCMC for Bayesian neural networks&lt;/h3&gt;

&lt;p&gt;Izmailov, Vikram, Hoffman and Wilson (2021) ask what the posterior of a Bayesian neural network looks like if we really run expensive HMC, instead of immediately trusting dropout or a diagonal Gaussian. They find that popular approximations often fail to reproduce the full posterior, but predictions can still be useful. The lesson for linear regression students is humble and sharp: if HMC is already hard to read on a few dozen correlated coefficients, then “MCMC for deep learning” is the same geometric problem, only bigger. Chapter 7 will meet cheaper approximations again.&lt;/p&gt;

&lt;h2 id=&quot;interpretation-and-insight&quot;&gt;Interpretation and insight&lt;/h2&gt;

&lt;p&gt;A posterior interval from NUTS is only trustworthy if the chain has mixed and the model is not grossly wrong. \(\hat R\) near 1 does not prove the plane is causal. Pathfinder can sit at a minor mode and make NUTS start in the wrong place. A fast BlackJAX does not make the prior harmless. Read the sampler as a magnifying glass: it magnifies exactly the model you wrote, including the Gaussian assumptions about the residuals.&lt;/p&gt;

&lt;h2 id=&quot;applications&quot;&gt;Applications&lt;/h2&gt;

&lt;p&gt;Bayesian linear regression is the backbone of media mix, pricing, and hierarchical models in A/B testing. Modern MCMC is why those models can carry real priors and still produce a usable posterior, instead of stopping at point estimates.&lt;/p&gt;

&lt;h2 id=&quot;limitations-and-extensions&quot;&gt;Limitations and extensions&lt;/h2&gt;

&lt;p&gt;HMC needs a differentiable log-density; discrete data with discrete parameters must take another route. Large models still need VI, Laplace, or ensembles. This lesson deliberately does not reopen Markov chain theory. Chapter 5 will make the posterior harder by adding many predictors and causal structure.&lt;/p&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=a-wydhEuAm0&quot;&gt;The intuition behind the Hamiltonian Monte Carlo algorithm&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the HMC intuition before reading NUTS as a way to choose the trajectory length, exactly the step where the lesson moves from Metropolis to modern samplers.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jUSZboSq1zg&quot;&gt;Michael Betancourt: Scalable Bayesian Inference with Hamiltonian Monte Carlo&lt;/a&gt; — London Machine Learning Meetup, English. Watch Michael Betancourt present large-scale Bayesian inference with Hamiltonian Monte Carlo.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KVpAziPblks&quot;&gt;#78 Exploring MCMC Sampler Algorithms, with Matt D. Hoffman&lt;/a&gt; — Learning Bayesian Statistics, English. Watch Matt Hoffman, co-author of NUTS, discuss MCMC samplers, supporting the part of the lesson that reads a PyMC or Stan chain as a controlled approximation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;A colleague says “PyMC has converged because the trace looks fine”. Which two more diagnostics would you ask for, and which geometric assumption is each checking?&lt;/li&gt;
  &lt;li&gt;Explain, without code, why Pathfinder can be both variational inference and part of an MCMC workflow.&lt;/li&gt;
  &lt;li&gt;In a house-price regression with heavy-tailed errors, NUTS still runs. Which model is the posterior approximating, and what will the PPC expose?&lt;/li&gt;
  &lt;li&gt;Read the NUTS page of Stan or NumPyro. Point to one sentence in the documentation about the &lt;em&gt;target log density&lt;/em&gt;. Which mathematical object of lesson 4.1 does that sentence correspond to?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 11–12.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 7, 17.&lt;/li&gt;
  &lt;li&gt;Zhang, L., Carpenter, B., Gelman, A., &amp;amp; Vehtari, A. (2022). Pathfinder: Parallel quasi-Newton variational inference. &lt;em&gt;JMLR&lt;/em&gt;, 23(306). &lt;a href=&quot;https://arxiv.org/abs/2108.03782&quot;&gt;arXiv:2108.03782&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Cabezas, A., Corenflos, A., Lao, J., Louf, R., et al. (2024). BlackJAX: Composable Bayesian inference in JAX. &lt;a href=&quot;https://arxiv.org/abs/2402.10797&quot;&gt;arXiv:2402.10797&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Izmailov, P., Vikram, S., Hoffman, M. D., &amp;amp; Wilson, A. G. (2021). What are Bayesian neural network posteriors really like? &lt;em&gt;ICML&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://mc-stan.org/docs/reference-manual/mcmc.html&quot;&gt;Stan HMC/NUTS&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://num.pyro.ai/en/stable/mcmc.html&quot;&gt;NumPyro inference&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.pymc.io/projects/docs/en/stable/learn/core_notebooks/pymc_overview.html&quot;&gt;PyMC sampling&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 2.7: Modern Applications of Conjugate Updating and Empirical Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_07_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_07_modern_applications</id>
   <content type="html">&lt;p&gt;If you think conjugate Beta–Binomial and Normal–Normal formulas are merely classroom warm-ups before “real” machine learning, look under the hood of modern ad-tech, clinical adaptive trials, and large-scale recommendation systems. When a platform must update click-through rate estimates for ten million ads every few seconds—or shrink noisy conversion rates of brand-new products toward a category average—exact conjugate updating and Empirical Bayes are not relics; they are the fastest, cleanest production engines available.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lesson Roadmap:&lt;/strong&gt; Why conjugacy still powers modern scale → Key ideas (Sequential conjugate updating, Empirical Bayes shrinkage, Thompson sampling) → Hand-worked 3-campaign shrinkage calculation → Generative stories, applications, limitations, and exercises.&lt;/p&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this optional lesson you should see conjugate priors and grid approximation as industrial design choices, not classroom tricks. You will be able to point to a live product—ads, ranking, or rate monitoring—and say which likelihood is being assumed, which prior family keeps the update cheap, and when the algebra must be abandoned for simulation.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-where-classical-conjugacy-powers-modern-systems&quot;&gt;Key ideas: Where Classical Conjugacy Powers Modern Systems&lt;/h2&gt;

&lt;h3 id=&quot;1-online-sequential-updating-via-sufficient-statistics&quot;&gt;1. Online Sequential Updating via Sufficient Statistics&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; In exponential-family conjugate models, all historical data compresses losslessly into a tiny vector of &lt;strong&gt;sufficient statistics&lt;/strong&gt; (e.g., total clicks \(k\) and impressions \(n\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Updating a posterior in \(O(1)\) time and \(O(1)\) memory as new events stream in—ideal for real-time bidding, streaming telemetry, and edge devices.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-empirical-bayes-and-partial-pooling-shrinkage&quot;&gt;2. Empirical Bayes and Partial Pooling (Shrinkage)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Estimating a shared prior (e.g., \(\mathrm{Beta}(\alpha_0, \beta_0)\)) from a large population of parallel units, then updating each unit individually.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; How small-sample extremes get pulled smoothly toward the population mean while large-sample units keep their empirical estimates—preventing “1 click out of 1 impression = 100% CTR” disasters.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-thompson-sampling-for-explorationexploitation&quot;&gt;3. Thompson Sampling for Exploration–Exploitation&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; A Bayesian multi-armed bandit algorithm that draws one sample \(\tilde{\theta}_a \sim p(\theta_a \mid D)\) per arm and selects the arm with the largest draw.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Automatically balancing exploration (wide posteriors occasionally draw high values) and exploitation (narrow, high-mean posteriors win consistently) with near-optimal regret bounds.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;explanation-empirical-bayes-shrinkage-across-three-ad-campaigns&quot;&gt;Explanation: Empirical Bayes Shrinkage Across Three Ad Campaigns&lt;/h2&gt;

&lt;p&gt;Suppose an ad platform fits a shared category prior \(\theta \sim \mathrm{Beta}(2, 18)\) across thousands of historical ads, encoding a prior mean click-through rate of \(\frac{2}{2+18} = 10.0\%\) with effective prior sample size \(n_0 = 20\). Now compare three live campaigns using the exact conjugate posterior mean \(\hat{\theta}_{\text{Bayes}} = \frac{2 + k}{20 + n}\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Campaign&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Clicks \(k\) / Impressions \(n\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Raw MLE \(k/n\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Posterior \(\mathrm{Beta}(2+k,\, 18+n-k)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Posterior Mean&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Shrinkage Weight on Prior \(\frac{20}{20+n}\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;A (brand new)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1 / 2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(50.0\%\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mathrm{Beta}(3, 19)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(3/22 = \mathbf{13.6\%}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(90.9\%\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;B (mature)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(100 / 1{,}000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(10.0\%\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mathrm{Beta}(102, 918)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(102/1020 = \mathbf{10.0\%}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2.0\%\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;C (growing)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(30 / 200\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(15.0\%\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mathrm{Beta}(32, 188)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(32/220 = \mathbf{14.5\%}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(9.1\%\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Look at Campaign A: a naive MLE ranking would flood it with traffic at “50% CTR” after two lucky impressions, whereas conjugate Empirical Bayes automatically tempers it to \(13.6\%\) until real volume arrives—while barely touching Campaign B (only \(2\%\) prior weight).&lt;/p&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;Lessons 2.1–2.6 already built the four-part skeleton: distribution, likelihood, prior, posterior. This lesson does not re-derive Beta–Binomial or Gamma–Poisson conjugacy. It asks why those pairs still appear inside large CS systems, and why empirical Bayes is the usual way the prior gets a number.&lt;/p&gt;

&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;

&lt;p&gt;Once you can update a Beta by counting successes, a natural doubt appears. Why would a company with millions of users still care about a closed-form posterior? The answer is latency and multiplicity. An ads or ranking stack may need a conversion probability for every item, every minute. A full MCMC draw for each item is often too slow; a conjugate update that adds counts to \((\alpha,\beta)\) is not. The intellectual tension is therefore economic as well as statistical. Exact algebra survives where it is &lt;em&gt;fast enough to be honest at scale&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id=&quot;conceptual-development&quot;&gt;Conceptual development&lt;/h2&gt;

&lt;p&gt;A conjugate prior is a family that stays inside itself after multiplication by the likelihood. For a conversion probability \(\theta\) with binomial data, the Beta prior yields&lt;/p&gt;

\[\theta\mid y \sim \mathrm{Beta}(\alpha+y,\ \beta+n-y).\]

&lt;p&gt;The same addition of counts is what a dashboard calls “smoothing.” Empirical Bayes chooses \(\alpha\) and \(\beta\) from the ensemble of items rather than from a single expert guess, so a rare item borrows strength from the marketplace. When the likelihood leaves the exponential family, or the prior must be hierarchical in a way that breaks conjugacy, the grid you met in Lesson 2.6 becomes the last exact picture before Hamiltonian Monte Carlo.&lt;/p&gt;

&lt;h2 id=&quot;models-as-generative-stories&quot;&gt;Models as generative stories&lt;/h2&gt;

&lt;h3 id=&quot;1-betabinomial-rates-in-advertising-and-ranking&quot;&gt;1. Beta–Binomial rates in advertising and ranking&lt;/h3&gt;

&lt;p&gt;Imagine each creative, query–item pair, or recommended pin as having an unknown click or conversion probability \(\theta_i\). The data story is brutally simple: \(n_i\) opportunities, \(y_i\) successes. A shared Beta prior, with hyperparameters fit by empirical Bayes, shrinks noisy items toward the marketplace mean. That is why a new item with one click in two impressions is not treated as a 50% converter. The posterior mean&lt;/p&gt;

\[\hat\theta_i=\frac{\alpha+y_i}{\alpha+\beta+n_i}\]

&lt;p&gt;is the ranking score that can be refreshed with integer additions. Pinterest’s PinnerFormer (Pancha et al., 2022) is a sequence model for user representations, but the serving layer still needs well-behaved item rates; conjugate smoothing remains the inexpensive first Bayesian move beneath more elaborate rankers.&lt;/p&gt;

&lt;h3 id=&quot;2-thompson-sampling-as-posterior-sampling-for-decisions&quot;&gt;2. Thompson sampling as posterior sampling for decisions&lt;/h3&gt;

&lt;p&gt;Russo et al. (2018) organized a fact that platforms still implement daily: if you can sample from \(p(\theta\mid y)\), you can choose an action by pretending the sample is true. For a Beta–Binomial bandit that sample is one line of code. The generative story is sequential. Today’s posterior becomes tomorrow’s prior; exploration is not a heuristic but a consequence of remaining posterior width. Modern contextual bandits replace the Beta with a regression posterior, yet the decision rule—sample, then act—is the same update you have already performed on a grid.&lt;/p&gt;

&lt;h3 id=&quot;3-gammapoisson-monitoring-of-counts&quot;&gt;3. Gamma–Poisson monitoring of counts&lt;/h3&gt;

&lt;p&gt;Infrastructure events, streaming-quality drops, and incident counts are often modeled as Poisson with a Gamma prior on the rate. The posterior remains Gamma after a night of counts, so an on-call system can report a posterior predictive interval without a sampler. When overdispersion appears, the story must change to Negative Binomial and conjugacy is no longer a free lunch. That is the moment Lesson 2.6 was preparing: draw a grid, see the posterior warp, and admit that a closed form has ended.&lt;/p&gt;

&lt;h3 id=&quot;4-when-conjugacy-fails-from-the-grid-to-probabilistic-programming&quot;&gt;4. When conjugacy fails: from the grid to probabilistic programming&lt;/h3&gt;

&lt;p&gt;Stan, PyMC, and NumPyro all document conjugate models as the cases you should &lt;em&gt;not&lt;/em&gt; waste a sampler on, and nonconjugate models as the reason NUTS exists. The grid is still the right mental picture. It shows the unnormalized product \(p(y\mid\theta)p(\theta)\) as a landscape. Hamiltonian Monte Carlo, introduced in Chapter 4, is what you do when that landscape has too many coordinates for a grid. Pathfinder (Zhang, Carpenter, Gelman, and Vehtari, 2022) later uses a quasi-Newton path to place a cheap Gaussian near the same landscape, often as a warm start. The Chapter 2 objects have not been replaced; they have been given compilers.&lt;/p&gt;

&lt;h2 id=&quot;interpretation-and-insight&quot;&gt;Interpretation and insight&lt;/h2&gt;

&lt;p&gt;A shrunk rate is not “the true CTR.” It is a posterior mean under a hierarchical story that may be wrong if items are not exchangeable—creatives in different countries, or queries with incompatible intents. Thompson sampling does not remove regret; it spends posterior uncertainty. A Gamma interval that ignores a change-point will look precise and be late. Read every closed form as an assumption that the next observation is still of the same kind.&lt;/p&gt;

&lt;h2 id=&quot;applications&quot;&gt;Applications&lt;/h2&gt;

&lt;p&gt;Ads, ranking, site reliability, and sequential experiments are four places where Chapter 2 is already in production. They also show the boundary: conjugacy for the inner loop, simulation for the model that no longer fits on a whiteboard.&lt;/p&gt;

&lt;h2 id=&quot;limitations-and-extensions&quot;&gt;Limitations and extensions&lt;/h2&gt;

&lt;p&gt;Empirical Bayes point-estimates the hyperparameters and therefore understates uncertainty about the prior itself. Fully hierarchical Bayes, which Chapter 5’s multilevel thinking begins to motivate, puts a posterior on \((\alpha,\beta)\). Grid approximation dies in more than a few dimensions. The honest next tool is not a fancier conjugate table but a sampler, which Chapter 4 develops.&lt;/p&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aPNrhR0dFi8&quot;&gt;What is a conjugate prior?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Watch when conjugacy is still a computational design choice, the reading this lesson gives conjugate priors.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How to Estimate Rates with a Gamma-Poisson Bayesian Model&lt;/td&gt;
          &lt;td&gt;Conjugate Priors](https://www.youtube.com/watch?v=m8roQUqmybg) — Drawing Distributions, English. Watch a Gamma–Poisson model estimate an event rate, the rate-monitoring pattern in the lesson.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=GqSX-8AQL90&quot;&gt;Bayesian Updates and Conjugate Priors&lt;/a&gt; — Steve Brunton, English. Watch conjugate updates applied as data arrive in sequence, supporting the lesson’s live-system examples.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Two items have click data \((y,n)=(1,2)\) and \((40,100)\). Under a \(\mathrm{Beta}(2,98)\) prior, which posterior mean moves more, and what product decision does that justify?&lt;/li&gt;
  &lt;li&gt;Write the generative story for Thompson sampling on three email subject lines. What is observed, what is latent, and when should you stop exploring?&lt;/li&gt;
  &lt;li&gt;A Poisson–Gamma monitor reports a tight rate after a quiet weekend. Traffic is ten times higher on Monday. Which assumption broke?&lt;/li&gt;
  &lt;li&gt;Open the PyMC or Stan getting-started page and find one example that is conjugate and one that is not. For the second, say why a grid would fail.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 2–3.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 6.&lt;/li&gt;
  &lt;li&gt;Russo, D., Van Roy, B., Kazerouni, A., Osband, I., &amp;amp; Wen, Z. (2018). A tutorial on Thompson sampling. &lt;em&gt;Foundations and Trends in Machine Learning&lt;/em&gt;, 11(1), 1–96.&lt;/li&gt;
  &lt;li&gt;Pancha, N., Zhai, A., Leskovec, J., &amp;amp; Rosenberg, C. (2022). PinnerFormer: Sequence modeling for user representation at Pinterest. &lt;em&gt;KDD&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2205.04507&quot;&gt;arXiv:2205.04507&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Zhang, L., Carpenter, B., Gelman, A., &amp;amp; Vehtari, A. (2022). Pathfinder: Parallel quasi-Newton variational inference. &lt;em&gt;JMLR&lt;/em&gt;, 23(306), 1–49. &lt;a href=&quot;https://arxiv.org/abs/2108.03782&quot;&gt;arXiv:2108.03782&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://mc-stan.org/docs/stan-users-guide/index.html&quot;&gt;Stan User’s Guide&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.pymc.io/projects/docs/en/stable/learn/core_notebooks/pymc_overview.html&quot;&gt;PyMC overview&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://num.pyro.ai/en/stable/getting_started.html&quot;&gt;NumPyro getting started&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 1.5: Modern Applications of Bayes' Theorem in Computer Science</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_05_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_05_modern_applications</id>
   <content type="html">&lt;p&gt;Thomas Bayes sketched his theorem in the 1760s using billiard balls on a flat table; two and a half centuries later, that exact equation is quietly running inside &lt;strong&gt;self-driving car sensor fusion (Kalman &amp;amp; Particle Filters)&lt;/strong&gt;, &lt;strong&gt;email spam filters&lt;/strong&gt;, &lt;strong&gt;Thompson Sampling bandits&lt;/strong&gt; routing millions of ads and recommendations, and &lt;strong&gt;Bayesian Optimization&lt;/strong&gt; tuning billion-dollar neural-network hyperparameters!&lt;/p&gt;

&lt;p&gt;This optional bridge shows how Bayes’ theorem powers modern computer science systems in 2022–2026—where uncertainty isn’t an academic nuisance, it is the exact signal algorithms use to &lt;strong&gt;explore vs. exploit&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-three-ways-bayes-theorem-ships-in-computer-science&quot;&gt;Key ideas: Three Ways Bayes’ Theorem Ships in Computer Science&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sequential Filtering (Robotics &amp;amp; Tracking):&lt;/strong&gt; Kalman filters (exact linear-Gaussian Bayes) and Particle filters fuse noisy GPS + LiDAR + IMU streams every 20 milliseconds by turning the previous millisecond’s posterior into the next millisecond’s prior.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thompson Sampling (Multi-Armed Bandits):&lt;/strong&gt; Instead of wasting 50% of traffic on a losing A/B variant for weeks, Thompson Sampling samples \(\theta_k \sim \mathrm{Beta}(\alpha_k, \beta_k)\) for each arm and plays the winner—automatically shifting traffic toward better options while keeping exploration alive!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Optimization (Hyperparameter &amp;amp; Drug Discovery):&lt;/strong&gt; Fits a Gaussian Process posterior over an expensive black-box objective and queries the next point maximizing Expected Improvement (EI)—cutting expensive GPU/lab trials by 5–10×.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this optional lesson, you no longer see Bayes’ theorem as a diagnostic formula in a textbook, but as a rule for updating beliefs that is running inside spam filtering, fraud detection, and the quantification of uncertainty in language models. What needs to change is the question: not “how is the formula written?”, but “where do the prior, likelihood and posterior sit in a real system?”.&lt;/p&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;This lesson builds on lessons 1.1–1.4. It does not rewrite the critique of the p-value or the Bayesian–frequentist comparison. It only brings the same updating diagram into recent computer science products.&lt;/p&gt;

&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;

&lt;p&gt;Chapter 1 created a tension: the p-value answers a question that users usually do not ask, while the decision really needs the probability of a hypothesis after the data. Spam filters, payment gateways, and chatbots all live in exactly that tension. They must turn a new observation—an email, a transaction, a generated answer—into an updated belief honest enough to act on. If there is only a ranking score, the system still does not know whether it should stay silent or raise a warning.&lt;/p&gt;

&lt;h2 id=&quot;conceptual-development&quot;&gt;Conceptual development&lt;/h2&gt;

&lt;p&gt;Bayes’ theorem,&lt;/p&gt;

\[P(H\mid D)=\frac{P(D\mid H)P(H)}{P(D)},\]

&lt;p&gt;is still the same multiplication of prior by likelihood followed by normalization. In a product, \(H\) can be “spam”, “fraudulent transaction”, or “the answer just generated is correct”. \(D\) is the observed evidence. The hard part is not the algebra, but a skewed prior (the spam base rate changes with the season) and a likelihood being read as if it were already the posterior.&lt;/p&gt;

&lt;h2 id=&quot;models-as-generative-stories&quot;&gt;Models as generative stories&lt;/h2&gt;

&lt;h3 id=&quot;1-spam-scams-and-calibrated-classification&quot;&gt;1. Spam, scams and calibrated classification&lt;/h3&gt;

&lt;p&gt;The classic generative story of Naive Bayes is still alive: each token is treated as conditional evidence about the spam label, and then the likelihoods are multiplied under an independence assumption. Modern systems replace the dictionary with denser representations, but the Bayesian question does not change. The prior is the base rate of spam; the likelihood is “under which label does an email like this appear more often?”; the posterior is the probability that the email is spam &lt;em&gt;after having read the content&lt;/em&gt;. If the action threshold ignores the base rate, you are using the likelihood as if it were already the posterior—exactly the mistake that lesson 1.3 warns about in medical diagnosis.&lt;/p&gt;

&lt;h3 id=&quot;2-payment-fraud-as-updating-under-an-extremely-low-base-rate&quot;&gt;2. Payment fraud as updating under an extremely low base rate&lt;/h3&gt;

&lt;p&gt;Fraud is rare. The prior \(P(H)\) is therefore very small, so a “suspicious-looking” signal can still leave a moderate posterior. That is the industrial version of the rare-disease test paradox. An honest system must keep the base rate in the formula, and then act only when the posterior exceeds a threshold set by the cost of misses and false alarms. A high ranking score is not yet an updated belief.&lt;/p&gt;

&lt;h3 id=&quot;3-language-models-evaluating-their-own-answers&quot;&gt;3. Language models evaluating their own answers&lt;/h3&gt;

&lt;p&gt;Kadavath et al. (2022) ask a very Bayesian question: after a model proposes an answer, what is the probability \(P(\text{True})\) that the answer is correct? They find that large models can be well calibrated on formatted true/false tasks, and that looking at many self-generated samples before evaluating one candidate helps self-evaluation. Kuhn, Gal and Farquhar (2023) point out a new bottleneck: in language, many sentences differ in wording but share the same meaning, so entropy over token strings is not entropy over hypotheses. Semantic entropy groups sentences of equivalent meaning and only then measures uncertainty—that is, it measures the posterior over the space of hypotheses, not over the space of character strings.&lt;/p&gt;

&lt;h3 id=&quot;4-asking-the-model-for-calibrated-confidence&quot;&gt;4. Asking the model for calibrated confidence&lt;/h3&gt;

&lt;p&gt;Tian et al. (2023) show that, for models fine-tuned with human feedback, verbalized probabilities (“I am 70% sure”) are sometimes better calibrated than the conditional probabilities on tokens. This does not turn a chatbot into a Bayesian sampler, but it shows that products are trying to extract a posterior that users can read as plausibility. If that number does not match the true frequency of being correct, we are repeating the interpretation crisis with which Chapter 1 began.&lt;/p&gt;

&lt;h2 id=&quot;interpretation-and-insight&quot;&gt;Interpretation and insight&lt;/h2&gt;

&lt;p&gt;The posterior in these systems answers “how credible is this hypothesis after the evidence?”. It does not answer “the algorithm has rejected the alternative hypothesis”. A high \(P(\text{True})\) on a hallucinated answer can still occur if the likelihood is too optimistic. Bayes does not protect us from a wrong likelihood; it only forces us to say clearly where the prior is being pulled by the data.&lt;/p&gt;

&lt;h2 id=&quot;applications&quot;&gt;Applications&lt;/h2&gt;

&lt;p&gt;The three domains—spam/scams, fraud, and language uncertainty—are all decision problems under skewed base rates and asymmetric costs. They directly prepare for the decision analysis of Chapter 8, but can already be understood with Bayes’ theorem alone.&lt;/p&gt;

&lt;h2 id=&quot;limitations-and-extensions&quot;&gt;Limitations and extensions&lt;/h2&gt;

&lt;p&gt;Naive Bayes with independent words is a crude generative story. Semantic entropy needs a model of meaning equivalence, which is itself uncertain. Calibration on one benchmark does not guarantee calibration after a distribution shift. This lesson deliberately does not rewrite updating theory; Chapter 2 will turn that diagram into an explicit likelihood, prior and posterior.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-one-step-of-a-naive-bayes-spam-filter-in-log-odds&quot;&gt;Worked Numerical Example: One Step of a Naive Bayes Spam Filter in Log-Odds&lt;/h3&gt;

&lt;p&gt;Suppose 20% of incoming emails are Spam (\(\text{prior odds} = \frac{0.20}{0.80} = 0.25\)). An email contains the word &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;lottery&quot;&lt;/code&gt;, which appears in 40% of Spam emails (\(P(\text{&quot;lottery&quot;}\mid\text{Spam}) = 0.40\)) but only 1% of Ham emails (\(P(\text{&quot;lottery&quot;}\mid\text{Ham}) = 0.01\)):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Likelihood Ratio (Bayes Factor):&lt;/strong&gt;
\(\mathrm{LR} = \frac{0.40}{0.01} = \mathbf{40}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior Odds = Prior Odds \(\times\) Likelihood Ratio:&lt;/strong&gt;
\(\text{Posterior Odds} = 0.25 \times 40 = \mathbf{10.0} \quad (\text{10-to-1 in favor of Spam!}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convert back to probability:&lt;/strong&gt;
\(P(\text{Spam} \mid \text{&quot;lottery&quot;}) = \frac{10}{10 + 1} = \frac{10}{11} \approx \mathbf{90.9\%}!\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-takeaways-on-bayesian-algorithms-in-cs&quot;&gt;Explanation: Four Takeaways on Bayesian Algorithms in CS&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Odds form makes sequential updates pure multiplication (or log-addition):&lt;/strong&gt; Every new word or sensor reading simply adds \(\ln(\mathrm{LR})\) to the running log-odds!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Uncertainty drives smart exploration:&lt;/strong&gt; In Thompson Sampling and Bayesian Optimization, &lt;em&gt;high posterior variance&lt;/em&gt; is a feature—it tells the agent where learning has the highest payoff.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Naive independence assumptions still rank accurately:&lt;/strong&gt; Even when words in Naive Bayes are correlated, the &lt;em&gt;decision ranking&lt;/em&gt; often remains strong—though raw probabilities become overconfident and need calibration.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always pair online Bayesian bandits with guardrails:&lt;/strong&gt; Delayed reward feedback and non-stationary traffic require windowed or discounted updates so stale posteriors don’t lock onto yesterday’s winner.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the Naive Bayes spam example above, if the email &lt;em&gt;also&lt;/em&gt; contains the word &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;invoice&quot;&lt;/code&gt; with \(P(\text{&quot;invoice&quot;}\mid\text{Spam}) = 0.05\) and \(P(\text{&quot;invoice&quot;}\mid\text{Ham}) = 0.25\) (\(\mathrm{LR} = 0.20\)), what are the new posterior odds and posterior spam probability?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=SqW_p3311yY&quot;&gt;Naive Bayes từ A-Z: Trực Giác đến Toán Học&lt;/a&gt; — Gà AI, Vietnamese. &lt;strong&gt;watch first&lt;/strong&gt;. Watch Naive Bayes from intuition to formula, exactly the part of the lesson that places the spam filter in the prior–likelihood–posterior diagram.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=bc-SL86azrc&quot;&gt;Bayes Rule Example of Spam Filter&lt;/a&gt; — Eric Walden, English. Watch an email having its spam probability updated with each piece of evidence, supporting the shifting-base-rate example.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=veYq6EWZyVc&quot;&gt;MIT 6.S191: Uncertainty in Deep Learning&lt;/a&gt; — Alexander Amini, English. Watch the uncertainty of deep learning models; the video does not discuss semantic entropy, but supports the part of the lesson about not reading token scores as the posterior of a hypothesis.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;The spam rate rises from 5% to 30% during the holiday season. The likelihood of a keyword does not change. How does the posterior of an email containing that keyword change, and why will a filter that uses only the keyword score fail?&lt;/li&gt;
  &lt;li&gt;A payment gateway reports “fraud score 0.95”. Which two further questions would you ask before closing the transaction, one about the prior and one about the decision threshold?&lt;/li&gt;
  &lt;li&gt;Why can entropy over answers that differ in wording exaggerate uncertainty compared with entropy over meanings? Take a question that has two correct ways of being phrased.&lt;/li&gt;
  &lt;li&gt;Compare Kadavath et al.’s \(P(\text{True})\) with the posterior \(P(H\mid D)\) in the diagnostic example of lesson 1.3. What plays the role of the prior?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 1.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 4–5.&lt;/li&gt;
  &lt;li&gt;Kadavath, S., et al. (2022). Language models (mostly) know what they know. &lt;a href=&quot;https://arxiv.org/abs/2207.05221&quot;&gt;arXiv:2207.05221&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Kuhn, L., Gal, Y., &amp;amp; Farquhar, S. (2023). Semantic uncertainty: Linguistic invariances for uncertainty estimation in natural language generation. &lt;em&gt;ICLR&lt;/em&gt;. &lt;a href=&quot;https://arxiv.org/abs/2302.09664&quot;&gt;arXiv:2302.09664&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Tian, K., et al. (2023). Just ask for calibration: Strategies for eliciting calibrated confidence scores from language models fine-tuned with human feedback. &lt;a href=&quot;https://arxiv.org/abs/2305.14975&quot;&gt;arXiv:2305.14975&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.20: Modern Applications of Foundational Probability in Data Science</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_13_modern_applications/"/>
   <updated>2026-09-16T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_13_modern_applications</id>
   <content type="html">&lt;p&gt;It is easy to think Chapter 0’s probability basics are mere warm-up exercises before “real” machine learning. Yet look inside modern production data-science stacks in 2022–2026—streaming analytics engines, probabilistic classifiers, and LLM evaluation pipelines—and you find these exact foundations doing mission-critical work: &lt;strong&gt;Welford’s single-pass variance algorithm&lt;/strong&gt; tracking telemetry over billions of events without overflow, &lt;strong&gt;proper scoring rules (Brier score &amp;amp; log-loss)&lt;/strong&gt; auditing whether AI probability predictions are actually calibrated, and &lt;strong&gt;log-space softmax&lt;/strong&gt; stabilizing every Transformer layer!&lt;/p&gt;

&lt;p&gt;This optional bridge connects Chapter 0’s foundational probability directly to production data-science engineering.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-where-chapter-0-probability-ships-in-modern-data-science&quot;&gt;Key ideas: Where Chapter 0 Probability Ships in Modern Data Science&lt;/h2&gt;

&lt;p&gt;Three foundational ideas from Chapter 0 underpin modern production ML infrastructure:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Numerically Stable Streaming Moments (Welford’s Algorithm):&lt;/strong&gt; Computing \(\frac{1}{n}\sum x_i^2 - \bar{x}^2\) on large numbers (e.g., Unix timestamps around \(1.7\times 10^9\)) suffers catastrophic cancellation in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt;; Welford’s online recurrence updates mean and variance in one pass with full precision.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Probabilistic Calibration &amp;amp; Proper Scoring Rules:&lt;/strong&gt; A model predicting “80% chance of rain” is &lt;strong&gt;calibrated&lt;/strong&gt; only if it actually rains on ~80% of those days. &lt;strong&gt;Brier score&lt;/strong&gt; \(\frac{1}{n}\sum (p_i - y_i)^2\) and &lt;strong&gt;Log-Loss&lt;/strong&gt; reward both sharpness &lt;em&gt;and&lt;/em&gt; honest calibration.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Log-Space Stability Across Deep Learning &amp;amp; Bayesian Pipelines:&lt;/strong&gt; Every softmax layer subtracts &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max(logits)&lt;/code&gt; (the exact Log-Sum-Exp trick!) before exponentiating—preventing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; gradients at billion-parameter scale.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;By the end of this optional lesson you should be able to recognize the Chapter 0 toolkit—probability, joint distributions, expectation, log-probability, and simulation—not as a waiting room before Bayes, but as the same language that modern computer science and data science use when they ask whether a model is calibrated, numerically stable, and generative. The aim is a change of stance: foundational objects become design questions rather than review items.&lt;/p&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;This lesson assumes the required Chapter 0 sequence. It does not introduce new probability theory. It only asks what happens when those ideas leave the classroom and enter classifiers, language models, and probabilistic programs.&lt;/p&gt;

&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;

&lt;p&gt;A student who has just finished Chapter 0 can compute a mean, write a density, and simulate a sampling distribution. Industry problems look larger, but they often fail for the same small reasons: a reported probability is not a long-run frequency, a product of tiny likelihoods underflows, or a joint model is written as if dependence did not exist. The tension of this lesson is therefore modest and useful. If the foundations are already in place, why do modern systems still misread uncertainty? Because scale does not replace the meaning of a probability statement.&lt;/p&gt;

&lt;h2 id=&quot;conceptual-development&quot;&gt;Conceptual development&lt;/h2&gt;

&lt;p&gt;A probability \(p\) attached to a prediction is a claim about a data-generating process. If a model says \(p=0.9\) on one hundred cases, about ninety of those cases should be correct if the number is calibrated. That is the same idea as a sampling distribution, now applied to machine-learning scores rather than to a sample mean. Joint structure matters for the same reason: once two events are dependent, the product of marginals is no longer a story about the world. Simulation remains the cheapest way to see whether the story is even possible.&lt;/p&gt;

&lt;h2 id=&quot;models-as-generative-stories&quot;&gt;Models as generative stories&lt;/h2&gt;

&lt;h3 id=&quot;1-calibration-of-classifiers-and-language-models&quot;&gt;1. Calibration of classifiers and language models&lt;/h3&gt;

&lt;p&gt;Spam filters, fraud scores, and medical alerts all output a number that looks like a probability. The generative question is not “did the model rank cases well?” but “if the model claims \(P(\text{positive}\mid x)=0.8\), do eight in ten such cases really occur?” Kadavath et al. (2022) showed that large language models can be surprisingly well calibrated on formatted true/false and multiple-choice tasks, and that a model can be asked for \(P(\text{True})\) after it proposes an answer. Tian et al. (2023) then showed that models fine-tuned with human feedback often give better-calibrated &lt;em&gt;verbalized&lt;/em&gt; confidences than their raw token probabilities. The Chapter 0 moral is exact: a number in \([0,1]\) is not automatically a probability until it survives a frequency check.&lt;/p&gt;

&lt;h3 id=&quot;2-log-probability-and-numerical-stability-in-large-models&quot;&gt;2. Log-probability and numerical stability in large models&lt;/h3&gt;

&lt;p&gt;Training and inference in modern networks repeatedly evaluate products of probabilities. In log space the product becomes a sum,&lt;/p&gt;

\[\log p(x_{1:n})=\sum_{i=1}^{n}\log p(x_i\mid x_{&amp;lt;i}),\]

&lt;p&gt;which is why Chapter 0 insisted on log-probability. The same identity is what keeps language-model likelihoods from underflowing and what makes the log-sum-exp trick a standard primitive. The model believes that tokens are generated sequentially; the computer can only believe that story if the arithmetic does not collapse to zero.&lt;/p&gt;

&lt;h3 id=&quot;3-joint-distributions-in-probabilistic-programming&quot;&gt;3. Joint distributions in probabilistic programming&lt;/h3&gt;

&lt;p&gt;A PyMC or NumPyro program is a joint distribution written as a generative recipe: first sample parameters, then sample data given parameters. That is precisely the Chapter 0 definition of a statistical model, now compiled so that later chapters can condition it. When tabular predictors are strongly dependent, the joint—not a pile of one-dimensional summaries—is the object that later Bayesian models must respect. Grinsztajn, Oyallon, and Varoquaux (2022) remind us that on many ordinary tabular tasks, tree ensembles still beat deep nets, in part because the relevant joint structure is discrete, heterogeneous, and not well served by a generic continuous density.&lt;/p&gt;

&lt;h3 id=&quot;4-simulation-as-a-check-on-intuition&quot;&gt;4. Simulation as a check on intuition&lt;/h3&gt;

&lt;p&gt;Chapter 0 treated simulation as a way to see sampling variability. The same habit now appears as posterior predictive checking and as simulation-based calibration: draw parameters from a prior, draw data, refit, and ask whether the recovered uncertainties are honest (Modrák et al., 2025). Before you meet Markov chain Monte Carlo, you already have the right question. Does the computational story reproduce the probabilistic story?&lt;/p&gt;

&lt;h2 id=&quot;interpretation-and-insight&quot;&gt;Interpretation and insight&lt;/h2&gt;

&lt;p&gt;In each application the posterior or the score is easy to over-read. A calibrated \(P(\text{True})\) is still not a proof that the model “knows.” A stable log-likelihood is still not a correct likelihood. A joint program is still only as honest as the conditional independence it assumes. The useful habit is to ask what frequency, what dependence, and what simulation would embarrass the claim.&lt;/p&gt;

&lt;h2 id=&quot;applications&quot;&gt;Applications&lt;/h2&gt;

&lt;p&gt;These four settings already cover ranking, language, tabular modeling, and software for Bayesian computation. They are not extra topics. They are Chapter 0 spoken in the dialect of current CS/DS practice.&lt;/p&gt;

&lt;h2 id=&quot;limitations-and-extensions&quot;&gt;Limitations and extensions&lt;/h2&gt;

&lt;p&gt;This lesson does not replace a course on deep learning or probabilistic programming. Calibration can fail after a distribution shift; log-space arithmetic does not fix a misspecified likelihood; and simulation-based checks only test the computation you actually ran. The next chapters begin the Bayesian update itself.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-auditing-calibration-with-the-brier-score&quot;&gt;Worked Numerical Example: Auditing Calibration With the Brier Score&lt;/h3&gt;

&lt;p&gt;Suppose two weather models predict rain probabilities across 4 days with true outcomes \(y = [1, 0, 1, 0]\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Model A (Well-calibrated):&lt;/strong&gt; \(p_A = [0.80,\; 0.20,\; 0.70,\; 0.30]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Model B (Overconfident):&lt;/strong&gt; \(p_B = [0.99,\; 0.01,\; 0.99,\; 0.90]\) (confidently wrong on Day 4!).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Compute the exact &lt;strong&gt;Brier score&lt;/strong&gt; \(\mathrm{BS} = \frac{1}{4}\sum_{i=1}^4 (p_i - y_i)^2\) (lower is better):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Day&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Truth \(y_i\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Model A \((p_A - y)^2\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Model B \((p_B - y)^2\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((0.80-1)^2 = 0.0400\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((0.99-1)^2 = 0.0001\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((0.20-0)^2 = 0.0400\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((0.01-0)^2 = 0.0001\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((0.70-1)^2 = 0.0900\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((0.99-1)^2 = 0.0001\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;4&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((0.30-0)^2 = 0.0900\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((0.90-0)^2 = \mathbf{0.8100}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Brier Score&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;—&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.0650\) (Wins!)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.2026\) (3× worse!)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Even though Model B got 3 days nearly perfect, one overconfident mistake on Day 4 devastated its Brier score (and under Log-Loss it gets penalized even harder: \(-\ln(0.10) = 2.30\)!).&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-probabilistic-thinking-in-production-ml&quot;&gt;Explanation: Four Rules for Probabilistic Thinking in Production ML&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Accuracy alone ignores confidence:&lt;/strong&gt; Both Model A and Model B have the exact same 75% classification accuracy at threshold 0.5, yet Model A is 3× better calibrated!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always check calibration curves before using predicted probabilities for expected-value decisions:&lt;/strong&gt; An uncalibrated neural net predicting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.95&lt;/code&gt; when true risk is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.60&lt;/code&gt; breaks pricing, medical triage, and fraud thresholds.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never compute variance via &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean(x**2) - mean(x)**2&lt;/code&gt; on shifted data:&lt;/strong&gt; Subtracting two huge nearly equal numbers wipes out significant digits—use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.var&lt;/code&gt; or Welford’s online update.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian posteriors naturally hedge extreme confidence on sparse data:&lt;/strong&gt; Integrating over parameter uncertainty automatically softens overconfident &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.999&lt;/code&gt; predictions when sample size is small.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; What is the Brier score of a naive model that always predicts \(p = 0.50\) on every day (regardless of whether \(y_i\) is 0 or 1)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=O2L2Uv9pdDA&quot;&gt;Naive Bayes, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch Naive Bayes as a classifier written with conditional probability, matching the lesson’s move from classroom probability into classifiers.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HghZrdnrNQY&quot;&gt;Why Log Probabilities Are Everywhere in AI - Underflow Error in HMMs and Viterbi Algorithm&lt;/a&gt; — Algorithms and AI, English. Watch why language models stay on the log-probability scale, supporting the lesson’s section on log-probability outside the classroom.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=veYq6EWZyVc&quot;&gt;MIT 6.S191: Uncertainty in Deep Learning&lt;/a&gt; — Alexander Amini, English. Watch uncertainty in deep learning as one place where expectation and full distributions leave the probability warmup and enter modern models.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;A fraud model outputs \(0.99\) on ten transactions, three of which are later confirmed as fraud. In one paragraph, say what “miscalibrated” means here and which Chapter 0 object you would plot.&lt;/li&gt;
  &lt;li&gt;Explain why a language model’s next-token probabilities can look confident in token space and still be uncertain in meaning space. What extra invariance would you need?&lt;/li&gt;
  &lt;li&gt;Write a four-line generative story (in words, not code) for a Beta–Binomial conversion rate. Identify the joint, the observed, and the unobserved.&lt;/li&gt;
  &lt;li&gt;A colleague says simulation is only for teaching. Using the idea of simulation-based calibration, argue for one industrial use.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., &amp;amp; Rubin, D. B. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Ch. 1.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Ch. 4–5.&lt;/li&gt;
  &lt;li&gt;Kadavath, S., et al. (2022). Language models (mostly) know what they know. &lt;a href=&quot;https://arxiv.org/abs/2207.05221&quot;&gt;arXiv:2207.05221&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Tian, K., et al. (2023). Just ask for calibration. &lt;a href=&quot;https://arxiv.org/abs/2305.14975&quot;&gt;arXiv:2305.14975&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Grinsztajn, L., Oyallon, E., &amp;amp; Varoquaux, G. (2022). Why do tree-based models still outperform deep learning on typical tabular data? &lt;em&gt;NeurIPS&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Modrák, M., et al. (2025). Simulation-based calibration checking for Bayesian computation. &lt;em&gt;Bayesian Analysis&lt;/em&gt;, 20(2), 461–488. &lt;a href=&quot;https://arxiv.org/abs/2211.02383&quot;&gt;arXiv:2211.02383&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.pymc.io/projects/docs/en/stable/learn/core_notebooks/pymc_overview.html&quot;&gt;PyMC conceptual overview&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 12.8: Đề ôn tập 45 phút cho Lab 1-4</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/on-tap-lab-01-04/"/>
   <updated>2026-03-25T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/12_08_on_tap_lab_01_04</id>
   <content type="html">&lt;p&gt;Trước khi bước sang nửa sau của chuỗi thực hành với MCMC và hồi quy Bayes, đề ôn tập 45 phút này là một bài kiểm tra tổng lực gói gọn đúng bốn kỹ năng nền tảng từ Lab 1 đến Lab 4: xác suất có điều kiện, mô phỏng Monte Carlo, tính toán phân phối chuẩn liên tục và cập nhật hậu nghiệm Beta–Binomial.&lt;/p&gt;

&lt;p&gt;Hãy giữ nguyên tinh thần thi thật — tự bấm giờ 45 phút giải trọn vẹn cả 4 bài trên Python trước khi đối chiếu với khung kiểm tra nhanh ở cuối trang.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu&quot;&gt;Mục tiêu&lt;/h2&gt;

&lt;p&gt;Đề ôn tập này giúp sinh viên hệ thống lại các nội dung trọng tâm từ &lt;strong&gt;Lab 1 đến Lab 4&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Xác suất có điều kiện và công thức Bayes;&lt;/li&gt;
  &lt;li&gt;Mô phỏng xác suất bằng Python;&lt;/li&gt;
  &lt;li&gt;Tính toán với phân phối liên tục;&lt;/li&gt;
  &lt;li&gt;Cập nhật hậu nghiệm trong mô hình liên hợp đơn giản.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-kỹ-năng-được-kiểm-tra-trong-đề-ôn-tập-lab-14&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột kỹ năng được kiểm tra trong Đề ôn tập Lab 1–4&lt;/h2&gt;

&lt;p&gt;Mỗi bài trong đề ôn tập ánh xạ trực tiếp vào một năng lực cốt lõi của nửa đầu khóa học:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bài 1 — Xác suất toàn phần &amp;amp; Định lý Bayes rời rạc (Lab 1):&lt;/strong&gt; Lập bảng 4 cột &lt;em&gt;Prior → Likelihood → Tích đồng thời → Chuẩn hóa&lt;/em&gt; để không bao giờ đảo chiều xác suất có điều kiện.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài 2 — Mô phỏng Monte Carlo kiểm chứng trực giác (Lab 2):&lt;/strong&gt; Chuyển mô tả trò chơi thành mã mô phỏng tái lập được (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seed&lt;/code&gt;), chạy \(10\,000\) lần và đối chiếu độ hội tụ qua sai số chuẩn Monte Carlo.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài 3 — Thành thạo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats.norm&lt;/code&gt; trên phân phối liên tục (Lab 3):&lt;/strong&gt; Phân biệt rạch ròi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cdf&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sf&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ppf&lt;/code&gt; và tham số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale&lt;/code&gt; (độ lệch chuẩn \(\sigma\), không phải phương sai \(\sigma^2\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài 4 — Cập nhật liên hợp Beta–Binomial &amp;amp; Trực quan hóa (Lab 4):&lt;/strong&gt; Cập nhật siêu tham số \(\alpha_{\text{post}} = \alpha_0 + k, \beta_{\text{post}} = \beta_0 + n - k\), tính xác suất hậu nghiệm vượt ngưỡng bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;beta.sf&lt;/code&gt; và vẽ đồ thị so sánh rõ ràng.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;hướng-dẫn-làm-bài&quot;&gt;Hướng dẫn làm bài&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Thời gian làm bài: &lt;strong&gt;45 phút&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Hình thức: &lt;strong&gt;làm trực tiếp trên máy tính&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Mức độ: &lt;strong&gt;cơ bản&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Được phép sử dụng Python cùng các thư viện quen thuộc như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;numpy&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;matplotlib&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Trình bày ngắn gọn, ưu tiên lập luận đúng và kết quả rõ ràng.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;video-ngắn-ôn-tập-45-phút-lab-14-lộ-trình-4-dạng-bài-trọng-tâm&quot;&gt;Video ngắn: Ôn tập 45 phút (Lab 1–4): Lộ trình 4 Dạng bài Trọng tâm&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch12-08a-review-lab1-4-roadmap.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 15 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): tóm tắt nhanh 4 trụ cột kỹ năng (Bảng Bayes, Monty Hall, scipy.stats, Beta–Binomial).&lt;/p&gt;

&lt;h2 id=&quot;đề-kiểm-tra-ôn-tập&quot;&gt;Đề kiểm tra ôn tập&lt;/h2&gt;

&lt;p&gt;Tổng điểm: &lt;strong&gt;10 điểm&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;bài-1-xác-suất-có-điều-kiện-và-công-thức-bayes-2-điểm&quot;&gt;Bài 1. Xác suất có điều kiện và công thức Bayes (2 điểm)&lt;/h3&gt;

&lt;p&gt;Có ba túi bi:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Túi 1 có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;7&lt;/code&gt; bi đỏ và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3&lt;/code&gt; bi xanh.&lt;/li&gt;
  &lt;li&gt;Túi 2 có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt; bi đỏ và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt; bi xanh.&lt;/li&gt;
  &lt;li&gt;Túi 3 có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2&lt;/code&gt; bi đỏ và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;8&lt;/code&gt; bi xanh.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Chọn ngẫu nhiên một túi (với xác suất như nhau), sau đó lấy ngẫu nhiên một viên bi từ túi đó.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Tính xác suất để viên bi lấy ra là bi đỏ.&lt;/li&gt;
  &lt;li&gt;Biết rằng viên bi lấy ra là bi đỏ, tính xác suất viên bi đó đến từ &lt;strong&gt;Túi 1&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Yêu cầu: trình bày rõ công thức và kết quả cuối cùng.&lt;/p&gt;

&lt;h3 id=&quot;bài-2-mô-phỏng-monte-carlo-cho-bài-toán-monty-hall-25-điểm&quot;&gt;Bài 2. Mô phỏng Monte Carlo cho bài toán Monty Hall (2.5 điểm)&lt;/h3&gt;

&lt;p&gt;Trong trò chơi Monty Hall có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3&lt;/code&gt; cánh cửa, trong đó chỉ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; cửa chứa xe và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2&lt;/code&gt; cửa còn lại chứa dê. Người chơi chọn ngẫu nhiên một cửa. Người dẫn chương trình luôn mở một trong các cửa còn lại có dê, rồi cho người chơi quyền &lt;strong&gt;giữ nguyên&lt;/strong&gt; lựa chọn ban đầu hoặc &lt;strong&gt;đổi cửa&lt;/strong&gt;.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Viết chương trình mô phỏng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10000&lt;/code&gt; lần chơi.&lt;/li&gt;
  &lt;li&gt;Ước lượng xác suất thắng nếu:
    &lt;ul&gt;
      &lt;li&gt;người chơi luôn &lt;strong&gt;giữ nguyên&lt;/strong&gt; lựa chọn ban đầu;&lt;/li&gt;
      &lt;li&gt;người chơi luôn &lt;strong&gt;đổi cửa&lt;/strong&gt;.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Kết luận nên chọn chiến lược nào.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Yêu cầu: nộp đoạn mã ngắn gọn và ghi rõ hai xác suất thực nghiệm thu được.&lt;/p&gt;

&lt;h3 id=&quot;bài-3-phân-phối-chuẩn-và-tính-xác-suất-25-điểm&quot;&gt;Bài 3. Phân phối chuẩn và tính xác suất (2.5 điểm)&lt;/h3&gt;

&lt;p&gt;Giả sử chiều cao của sinh viên trong một lớp tuân theo phân phối chuẩn:&lt;/p&gt;

\[X \sim N(165, 8^2).\]

&lt;ol&gt;
  &lt;li&gt;Tính xác suất để một sinh viên được chọn ngẫu nhiên có chiều cao lớn hơn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;170 cm&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Tính xác suất để chiều cao nằm trong khoảng từ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;160 cm&lt;/code&gt; đến &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;175 cm&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Tìm giá trị \(x\) sao cho:&lt;/li&gt;
&lt;/ol&gt;

\[P(X \le x) = 0.9.\]

&lt;p&gt;Yêu cầu: có thể sử dụng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats&lt;/code&gt; để tính toán, nhưng cần ghi rõ từng giá trị thu được.&lt;/p&gt;

&lt;h3 id=&quot;bài-4-cập-nhật-bayes-với-mô-hình-betabinomial-3-điểm&quot;&gt;Bài 4. Cập nhật Bayes với mô hình Beta–Binomial (3 điểm)&lt;/h3&gt;

&lt;p&gt;Gọi \(p\) là xác suất một sinh viên trả lời đúng một câu hỏi trắc nghiệm. Trước khi quan sát dữ liệu, giả sử:&lt;/p&gt;

\[p \sim \text{Beta}(2,2).\]

&lt;p&gt;Quan sát kết quả của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10&lt;/code&gt; câu hỏi độc lập, sinh viên trả lời đúng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;7&lt;/code&gt; câu.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Tìm phân phối hậu nghiệm của \(p\).&lt;/li&gt;
  &lt;li&gt;Tính kỳ vọng hậu nghiệm của \(p\).&lt;/li&gt;
  &lt;li&gt;Tính xác suất hậu nghiệm:&lt;/li&gt;
&lt;/ol&gt;

\[P(p &amp;gt; 0.6 \mid \text{data}).\]

&lt;ol&gt;
  &lt;li&gt;Vẽ đồ thị hàm mật độ của phân phối tiên nghiệm và phân phối hậu nghiệm trên cùng một hệ trục tọa độ.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Yêu cầu: nêu rõ công thức cập nhật và dùng Python để hỗ trợ tính toán cũng như vẽ đồ thị.&lt;/p&gt;

&lt;h2 id=&quot;gợi-ý-phân-bổ-thời-gian&quot;&gt;Gợi ý phân bổ thời gian&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Bài 1: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;8&lt;/code&gt; phút&lt;/li&gt;
  &lt;li&gt;Bài 2: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;12&lt;/code&gt; phút&lt;/li&gt;
  &lt;li&gt;Bài 3: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10&lt;/code&gt; phút&lt;/li&gt;
  &lt;li&gt;Bài 4: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;15&lt;/code&gt; phút&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;tiêu-chí-chấm-nhanh&quot;&gt;Tiêu chí chấm nhanh&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Nêu đúng công thức và lập luận cơ bản.&lt;/li&gt;
  &lt;li&gt;Kết quả số hợp lý.&lt;/li&gt;
  &lt;li&gt;Mã nguồn chạy được với các câu yêu cầu lập trình.&lt;/li&gt;
  &lt;li&gt;Đồ thị có nhãn đầy đủ và dễ đọc ở bài phân phối hậu nghiệm.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;giải-thích-chiến-lược-tự-kiểm-tra-bài-làm-trong-3-phút-cuối-giờ&quot;&gt;Giải thích: Chiến lược tự kiểm tra bài làm trong 3 phút cuối giờ&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn tất cả 4 bài trong 45 phút, hãy dùng danh sách kiểm tra tính hợp lý (&lt;em&gt;sanity checks&lt;/em&gt;) 4 bước dưới đây để tự bắt mọi lỗi thường gặp trước khi nộp bài:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra Bài 1 (Tổng hậu nghiệm = 1):&lt;/strong&gt; Cộng xác suất hậu nghiệm của cả 3 túi bi phải bằng đúng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.0&lt;/code&gt;, và túi có tỷ lệ bi đỏ cao nhất (Túi 1) bắt buộc phải có hậu nghiệm lớn hơn prior \(1/3\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra Bài 2 (So với xác suất lý thuyết):&lt;/strong&gt; Tổng xác suất thắng của chiến lược giữ cửa và đổi cửa phải xấp xỉ \(1.0\) (quanh \(0.333\) và \(0.667\) trong biên độ \(\pm 0.015\) với \(M = 10\,000\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra Bài 3 (Quy tắc Z-score):&lt;/strong&gt; Nhẩm nhanh \(z = (x - 165)/8\): vì \(170 &amp;gt; 165\), xác suất \(P(X &amp;gt; 170)\) chắc chắn nhỏ hơn \(0.5\); và phân vị 90% chắc chắn nằm trên trung bình khoảng \(1.28\sigma \approx +10.2\text{ cm}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra Bài 4 (Bảo toàn tổng siêu tham số):&lt;/strong&gt; Với prior \(\text{Beta}(2, 2)\) và \(n = 10\) câu hỏi, tổng \(\alpha_{\text{post}} + \beta_{\text{post}}\) phải bằng \(2 + 2 + 10 = 14\), và kỳ vọng hậu nghiệm phải nằm giữa kỳ vọng prior (\(0.50\)) và tỷ lệ mẫu (\(0.70\)).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-tự-kiểm-tra-nhanh-mốc-số-học-không-thay-thế-bước-tự-giải&quot;&gt;Ví dụ tính toán làm từng bước: Tự kiểm tra nhanh mốc số học (không thay thế bước tự giải)&lt;/h3&gt;

&lt;p&gt;Để minh họa cách tự kiểm tra bằng nhẩm trên một bộ số tương tự (nhưng khác số liệu đề thi), giả sử bạn có bài Beta–Binomial phụ với prior \(\text{Beta}(3, 3)\) và quan sát \(6\) câu đúng trên \(8\) câu:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Kiểm tra nhanh&lt;/th&gt;
      &lt;th&gt;Công thức kiểm tra&lt;/th&gt;
      &lt;th&gt;Kết quả mong đợi&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Tổng siêu tham số hậu nghiệm&lt;/td&gt;
      &lt;td&gt;\(\alpha_0 + \beta_0 + n = 3 + 3 + 8\)&lt;/td&gt;
      &lt;td&gt;\(14\) (ứng với \(\text{Beta}(9, 5)\))&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Kỳ vọng hậu nghiệm bị kẹp giữa prior và mẫu&lt;/td&gt;
      &lt;td&gt;\(0.50 &amp;lt; \frac{9}{14} \approx 0.643 &amp;lt; 0.75\)&lt;/td&gt;
      &lt;td&gt;Thỏa mãn&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Xác suất đuôi phải \(P(p &amp;gt; 0.5 \mid y)\)&lt;/td&gt;
      &lt;td&gt;Vì kỳ vọng \(0.643 &amp;gt; 0.5\) nên chắc chắn \(&amp;gt; 0.5\)&lt;/td&gt;
      &lt;td&gt;Hợp lý (chạy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;beta.sf(0.5, 9, 5)&lt;/code&gt; để lấy số chính xác)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhập nhầm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale = 64&lt;/code&gt; thay vì &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale = 8&lt;/code&gt; trong Bài 3 khi đề ghi \(X \sim N(165, 8^2)\), hoặc quên trừ \(k\) khỏi \(n\) ở Bài 4 (viết nhầm \(\text{Beta}(2+7, 2+10)\) thay vì \(\text{Beta}(2+7, 2+3)\)).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Trước khi đóng notebook, chạy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Restart &amp;amp; Run All&lt;/code&gt; để chắc chắn mọi ô mã chạy thông suốt từ trên xuống dưới mà không phụ thuộc biến rác còn sót trong bộ nhớ.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Ôn lại định lý Bayes trước khi làm phần xác suất có điều kiện và cập nhật niềm tin của Lab 1–2.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R1vcdhPBlXA&quot;&gt;Statistical Rethinking 2023 - 02 - The Garden of Forking Data&lt;/a&gt; — Richard McElreath, English. Minh họa cập nhật Bayes bằng mô phỏng trên một tham số tỷ lệ, hỗ trợ câu hỏi ôn về mô phỏng và phương pháp lưới.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aPNrhR0dFi8&quot;&gt;What is a conjugate prior?&lt;/a&gt; — Ben Lambert, English. Giải thích tiên nghiệm liên hợp, phục vụ phần ôn tập Lab 4 về cập nhật hậu nghiệm cùng họ phân phối.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 12.8: 45-Minute Review Exam for Labs 1-4</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/en/chapter12/on-tap-lab-01-04/"/>
   <updated>2026-03-25T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/en/chapter12/12_08_on_tap_lab_01_04</id>
   <content type="html">&lt;p&gt;A 45-minute timed review exam isn’t about memorizing obscure formulas—it tests whether you can move &lt;strong&gt;fluidly and calmly&lt;/strong&gt; across the four core pillars of Labs 1–4: discrete Bayes tables, simulation verification, continuous grid normalization, and exact Beta–Binomial / Gamma–Poisson conjugate updates!&lt;/p&gt;

&lt;p&gt;This review guide gives you a rapid pre-exam calibration map and a 3-minute &lt;strong&gt;complete end-to-end warm-up problem&lt;/strong&gt; so you walk into the exam with sharp numerical instincts.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-four-lab-synthesis-checklist-labs-14&quot;&gt;Key ideas: The Four-Lab Synthesis Checklist (Labs 1–4)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lab 1 (Discrete Bayes):&lt;/strong&gt; Joint tables, base-rate traps, and verifying \(P(H\mid E) = \frac{P(E\mid H)P(H)}{P(E)}\) sums to 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lab 2 (Simulation &amp;amp; Sequential Updating):&lt;/strong&gt; Filtering simulated worlds to approximate posteriors and confirming sequential updates match batch updates.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lab 3 (Continuous Grid):&lt;/strong&gt; Remembering &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w = unnorm / unnorm.sum()&lt;/code&gt; vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pdf = w / dtheta&lt;/code&gt;, and using log-space for stability.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lab 4 (Conjugacy):&lt;/strong&gt; Beta–Binomial \(\mathrm{Beta}(\alpha+k, \beta+n-k)\) and Gamma–Poisson \(\mathrm{Gamma}(\alpha+\sum k_i, \beta+n)\) with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy&lt;/code&gt;’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale = 1 / rate&lt;/code&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;This review exam helps students consolidate the main ideas from &lt;strong&gt;Lab 1 to Lab 4&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;conditional probability and Bayes’ formula;&lt;/li&gt;
  &lt;li&gt;simulating probabilities with Python;&lt;/li&gt;
  &lt;li&gt;computing with continuous distributions;&lt;/li&gt;
  &lt;li&gt;posterior updating in a simple conjugate model.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;instructions&quot;&gt;Instructions&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Time allowed: &lt;strong&gt;45 minutes&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Format: &lt;strong&gt;done on a computer&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Level: &lt;strong&gt;basic, easy&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;You may use Python and familiar libraries such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;numpy&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;matplotlib&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Keep answers concise; prioritize correct ideas and clear results.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;review-exam&quot;&gt;Review exam&lt;/h2&gt;

&lt;p&gt;Total: &lt;strong&gt;10 points&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;problem-1-conditional-probability-and-bayes-2-points&quot;&gt;Problem 1. Conditional probability and Bayes (2 points)&lt;/h3&gt;

&lt;p&gt;There are three bags of marbles:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Bag 1 has &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;7&lt;/code&gt; red marbles and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3&lt;/code&gt; blue marbles.&lt;/li&gt;
  &lt;li&gt;Bag 2 has &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt; red marbles and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt; blue marbles.&lt;/li&gt;
  &lt;li&gt;Bag 3 has &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2&lt;/code&gt; red marbles and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;8&lt;/code&gt; blue marbles.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Pick a bag at random, then draw one marble at random from that bag.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Compute the probability that the drawn marble is red.&lt;/li&gt;
  &lt;li&gt;Given that the drawn marble is red, compute the probability that it came from &lt;strong&gt;Bag 1&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Requirement: show the formulas and the final result.&lt;/p&gt;

&lt;h3 id=&quot;problem-2-monte-carlo-simulation-for-the-monty-hall-problem-25-points&quot;&gt;Problem 2. Monte Carlo simulation for the Monty Hall problem (2.5 points)&lt;/h3&gt;

&lt;p&gt;In the Monty Hall game there are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3&lt;/code&gt; doors; only &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; hides a car and the other &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2&lt;/code&gt; hide goats. The player picks a door at random. The host always opens one of the remaining doors that hides a goat, then lets the player &lt;strong&gt;stay&lt;/strong&gt; or &lt;strong&gt;switch&lt;/strong&gt;.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Write a program that simulates &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10000&lt;/code&gt; plays.&lt;/li&gt;
  &lt;li&gt;Estimate the probability of winning if:
    &lt;ul&gt;
      &lt;li&gt;the player always &lt;strong&gt;stays&lt;/strong&gt; with the initial choice;&lt;/li&gt;
      &lt;li&gt;the player always &lt;strong&gt;switches&lt;/strong&gt;.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Conclude which strategy to choose.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Requirement: submit a short code snippet and state the two empirical probabilities you obtained.&lt;/p&gt;

&lt;h3 id=&quot;problem-3-the-normal-distribution-and-computing-probabilities-25-points&quot;&gt;Problem 3. The normal distribution and computing probabilities (2.5 points)&lt;/h3&gt;

&lt;p&gt;Suppose the heights of students in a class follow a normal distribution:&lt;/p&gt;

\[X \sim N(165, 8^2).\]

&lt;ol&gt;
  &lt;li&gt;Compute the probability that a randomly chosen student is taller than &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;170 cm&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Compute the probability that the height is between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;160 cm&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;175 cm&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Find the value \(x\) such that:&lt;/li&gt;
&lt;/ol&gt;

\[P(X \le x) = 0.9.\]

&lt;p&gt;Requirement: you may use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats&lt;/code&gt; for the computation, but state each requested value clearly.&lt;/p&gt;

&lt;h3 id=&quot;problem-4-bayesian-updating-with-the-beta-binomial-model-3-points&quot;&gt;Problem 4. Bayesian updating with the Beta-Binomial model (3 points)&lt;/h3&gt;

&lt;p&gt;Let \(p\) be the probability that a student answers a multiple-choice question correctly. Before observing data, assume:&lt;/p&gt;

\[p \sim \text{Beta}(2,2).\]

&lt;p&gt;We observe the results of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10&lt;/code&gt; independent questions; the student answers &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;7&lt;/code&gt; correctly.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Find the posterior distribution of \(p\).&lt;/li&gt;
  &lt;li&gt;Compute the posterior mean of \(p\).&lt;/li&gt;
  &lt;li&gt;Compute the posterior probability:&lt;/li&gt;
&lt;/ol&gt;

\[P(p &amp;gt; 0.6 \mid \text{data}).\]

&lt;ol&gt;
  &lt;li&gt;Plot the prior and posterior densities on the same axes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Requirement: state the update formula clearly and use Python to help with the computation or the plot.&lt;/p&gt;

&lt;h2 id=&quot;suggested-time-allocation&quot;&gt;Suggested time allocation&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Problem 1: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;8&lt;/code&gt; minutes&lt;/li&gt;
  &lt;li&gt;Problem 2: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;12&lt;/code&gt; minutes&lt;/li&gt;
  &lt;li&gt;Problem 3: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10&lt;/code&gt; minutes&lt;/li&gt;
  &lt;li&gt;Problem 4: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;15&lt;/code&gt; minutes&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;quick-grading-criteria&quot;&gt;Quick grading criteria&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Correct formulas and basic reasoning.&lt;/li&gt;
  &lt;li&gt;Reasonable numerical results.&lt;/li&gt;
  &lt;li&gt;Code runs for the programming parts.&lt;/li&gt;
  &lt;li&gt;Correctly labeled, readable plot in the posterior problem.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-3-minute-full-cycle-warm-up-labs-14-combined&quot;&gt;Worked Numerical Example: 3-Minute Full-Cycle Warm-Up (Labs 1–4 Combined)&lt;/h3&gt;

&lt;p&gt;Test yourself on one compact problem touching every Lab 1–4 skill:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Setup:&lt;/strong&gt; Prior \(\theta \sim \mathrm{Beta}(2, 3)\) (mean \(2/5 = 0.40\)). Observe \(k = 4\) successes in \(n = 5\) trials.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Conjugate Posterior (Lab 4):&lt;/strong&gt; \(\mathrm{Beta}(2 + 4,\; 3 + 1) = \mathbf{\mathrm{Beta}(6, 4)}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior Mean &amp;amp; Mode:&lt;/strong&gt; Mean \(= \frac{6}{10} = \mathbf{0.60}\); Mode \(= \frac{6-1}{10-2} = \frac{5}{8} = \mathbf{0.625}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior Predictive (Next Trial):&lt;/strong&gt; \(P(y_{\text{new}} = 1 \mid D) = \mathbb{E}[\theta\mid D] = \mathbf{0.60}\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Grid Sanity Check (Lab 3):&lt;/strong&gt; On a 1,001-point grid (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dtheta = 0.001&lt;/code&gt;), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(theta * w).sum()&lt;/code&gt; must equal &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.6000&lt;/code&gt; within &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-4&lt;/code&gt;!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-exam-day-sanity-checks-that-catch-silly-mistakes&quot;&gt;Explanation: Four Exam-Day Sanity Checks That Catch Silly Mistakes&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Check bounds immediately:&lt;/strong&gt; Every probability and Beta mean must lie strictly in \([0, 1]\); every Gamma rate must be \(&amp;gt; 0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check the “pull” direction:&lt;/strong&gt; Your posterior mean &lt;em&gt;must&lt;/em&gt; sit strictly between your prior mean (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.40&lt;/code&gt;) and your raw sample rate (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4/5 = 0.80&lt;/code&gt;)—if you get &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.85&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.30&lt;/code&gt;, you swapped \(\alpha\) and \(\beta\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale = 1/rate&lt;/code&gt; on any Gamma question:&lt;/strong&gt; Verify &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dist.mean() == alpha / beta&lt;/code&gt; right in Python before answering.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Budget your 45 minutes cleanly:&lt;/strong&gt; Spend 10 minutes per lab section and keep 5 minutes at the end to verify sums, shapes, and interpretations in plain English.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the warm-up problem above (prior mean &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.40&lt;/code&gt;, observed sample rate &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.80&lt;/code&gt;), if your code printed a posterior mean of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.35&lt;/code&gt;, how would you know &lt;em&gt;in 2 seconds&lt;/em&gt; that there is a bug?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. &lt;strong&gt;watch first&lt;/strong&gt;. Revisit Bayes’ theorem before the review of conditional probability and belief updating from Labs 1–2.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R1vcdhPBlXA&quot;&gt;Statistical Rethinking 2023 - 02 - The Garden of Forking Data&lt;/a&gt; — Richard McElreath, English. Watch updating by simulation on a proportion parameter; it supports the review questions on simulation and grids.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aPNrhR0dFi8&quot;&gt;What is a conjugate prior?&lt;/a&gt; — Ben Lambert, English. Watch conjugate priors; use it for the Lab 4 review on updating where the posterior stays in the same family.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 12.7: Lab 7: Quy trình hồi quy Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/lab-07/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/12_07_lab_07</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  Trang này được sinh tự động từ các notebook trong thư mục &lt;code&gt;labs/&lt;/code&gt; và &lt;code&gt;labs/solutions/&lt;/code&gt;.
  Khi tệp notebook thay đổi, hãy chạy lại &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; để cập nhật Chương 12.
&lt;/div&gt;

&lt;p&gt;Đến &lt;strong&gt;Lab 7&lt;/strong&gt;, mọi viên gạch từ đầu khóa học — chọn prior thông tin yếu, xây dựng mô hình sinh dữ liệu, lấy mẫu MCMC, kiểm tra hội tụ (\(\hat R\), ESS), đọc khoảng tin cậy cho hệ số dốc và chạy kiểm tra dự báo hậu nghiệm (PPC) — được lắp ráp thành một &lt;strong&gt;quy trình hồi quy Bayes hoàn chỉnh&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Đây là bài thực hành bản lề giúp bạn chuyển từ các mô hình 1 tham số sang tư duy xây dựng và phản biện mô hình thống kê đầy đủ trên dữ liệu thực tế.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-quy-trình-hồi-quy-bayes-hoàn-chỉnh-từ-prior-đến-ppc&quot;&gt;Kiến thức cần nhớ: Quy trình Hồi quy Bayes Hoàn chỉnh từ Prior đến PPC&lt;/h2&gt;

&lt;p&gt;Lab 7 gắn kết ba trụ cột của một dự án hồi quy Bayes chuẩn mực:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đặc tả mô hình sinh &amp;amp; Chuẩn hóa biến (Generative Specification):&lt;/strong&gt; Viết rõ \(y_i \sim \mathcal{N}(\alpha + \beta (x_i - \bar x), \sigma^2)\). Việc căn giữa biến dự báo \(x_i - \bar x\) vừa làm hệ số chặn \(\alpha\) mang ý nghĩa trực quan (kỳ vọng của \(y\) tại mức trung bình của \(x\)), vừa giảm tương quan hậu nghiệm giữa \(\alpha\) và \(\beta\) giúp MCMC lấy mẫu nhanh hơn rõ rệt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chẩn đoán MCMC (Convergence Diagnostics):&lt;/strong&gt; Trước khi đọc bất kỳ hệ số nào, luôn kiểm tra \(\hat R \approx 1.00\) (\(\le 1.01\)), kích thước mẫu hiệu dụng (ESS) đủ lớn, không có phân kỳ (&lt;em&gt;divergences&lt;/em&gt;) và biểu đồ trace trộn đều.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân biệt Đường hồi quy Hậu nghiệm và Dự báo Hậu nghiệm (Mean Band vs. Predictive Band):&lt;/strong&gt; Dải bất định của đường trung bình \(\mu(x) = \alpha + \beta x\) chỉ phản ánh bất định tham số (hẹp dần khi \(n\) lớn); còn dải dự báo cho quan sát mới \(\tilde y \sim \mathcal{N}(\alpha + \beta x, \sigma^2)\) cộng thêm nhiễu \(\sigma\) nên luôn rộng hơn nhiều.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Đề lab&lt;/h2&gt;
  &lt;p&gt;Bạn có thể xem trực tiếp notebook trên web, mở tệp HTML riêng hoặc tải tệp &lt;code&gt;.ipynb&lt;/code&gt; gốc về máy để thực hành.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-07.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Lab 7 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%207.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Lab 7 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-07.html&quot; title=&quot;Lab 7 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lời giải (Solution)&lt;/h2&gt;
  &lt;p&gt;Phần lời giải được đặt cùng trang để bạn đối chiếu quy trình, cách giải và mã nguồn sau khi đã tự hoàn thành đề lab.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-07-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Solution Lab 7 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_07_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Solution Lab 7 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-07-solution.html&quot; title=&quot;Lab 7 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;h2 id=&quot;giải-thích-phân-biệt-hai-loại-dải-bất-định-trong-hồi-quy-bayes&quot;&gt;Giải thích: Phân biệt hai loại dải bất định trong Hồi quy Bayes&lt;/h2&gt;

&lt;p&gt;Rất nhiều sinh viên khi vẽ biểu đồ hồi quy Bayes trong Lab 7 bị nhầm giữa hai dải màu quanh đường hồi quy. Hãy kiểm tra chậm rãi 3 bước tính trên một điểm mới \(x_{\text{new}}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính đường trung bình tại từng mẫu hậu nghiệm \(s\):&lt;/strong&gt; \(\mu^{(s)} = \alpha^{(s)} + \beta^{(s)} x_{\text{new}}\). Độ rộng của tập \(\{\mu^{(s)}\}\) là &lt;strong&gt;bất định tham số&lt;/strong&gt; (epistemic).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cộng thêm nhiễu quan sát ở từng mẫu \(s\):&lt;/strong&gt; rút \(\tilde y^{(s)} \sim \mathcal{N}(\mu^{(s)}, (\sigma^{(s)})^2)\). Tập \(\{\tilde y^{(s)}\}\) cho &lt;strong&gt;khoảng dự báo hậu nghiệm&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh độ rộng hai khoảng:&lt;/strong&gt; Phương sai dự báo tổng bằng \(\mathrm{Var}(\mu \mid y) + \mathbb{E}[\sigma^2 \mid y]\) — luôn lớn hơn phương sai của riêng đường trung bình!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-so-sánh-khoảng-tin-cậy-đường-trung-bình-và-khoảng-dự-báo&quot;&gt;Ví dụ tính toán làm từng bước: So sánh Khoảng tin cậy Đường trung bình và Khoảng Dự báo&lt;/h3&gt;

&lt;p&gt;Giả sử sau khi chạy MCMC cho hồi quy dự đoán điểm thi \(y\) theo số giờ ôn \(x\), tại \(x_{\text{new}} = 5\) giờ ta có:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đường trung bình hậu nghiệm: \(\mu(5) \mid y \approx \mathcal{N}(75.0,\; 1.5^2)\) (độ lệch chuẩn tham số \(1.5\) điểm).&lt;/li&gt;
  &lt;li&gt;Độ lệch chuẩn nhiễu quan sát hậu nghiệm quanh mức \(\sigma \approx 6.0\) điểm (\(\sigma^2 = 36.0\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Loại khoảng 95% tại \(x = 5\)&lt;/th&gt;
      &lt;th&gt;Phương sai&lt;/th&gt;
      &lt;th&gt;Độ lệch chuẩn&lt;/th&gt;
      &lt;th&gt;Khoảng 95% (\(\pm 1.96\,\text{SD}\))&lt;/th&gt;
      &lt;th&gt;Câu hỏi trả lời&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Đường trung bình \(\mu(5)\)&lt;/td&gt;
      &lt;td&gt;\(1.5^2 = 2.25\)&lt;/td&gt;
      &lt;td&gt;\(1.50\)&lt;/td&gt;
      &lt;td&gt;\([72.06,\; 77.94]\)&lt;/td&gt;
      &lt;td&gt;Điểm &lt;em&gt;trung bình&lt;/em&gt; của nhóm học 5 giờ nằm ở đâu?&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Quan sát mới \(\tilde y(5)\)&lt;/td&gt;
      &lt;td&gt;\(2.25 + 36.0 = 38.25\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{38.25} \approx 6.18\)&lt;/td&gt;
      &lt;td&gt;\([62.88,\; 87.12]\)&lt;/td&gt;
      &lt;td&gt;Điểm của &lt;em&gt;một sinh viên cụ thể&lt;/em&gt; học 5 giờ nằm ở đâu?&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Vẽ dải 95% của đường trung bình \(\mu(x)\) lên đồ thị tán xạ dữ liệu rồi thấy chỉ có khoảng 30% điểm dữ liệu nằm trong dải, từ đó tưởng nhầm mô hình bị sai! Muốn kiểm tra 95% điểm dữ liệu thật có nằm trong dải hay không, ta bắt buộc phải vẽ &lt;strong&gt;dải dự báo hậu nghiệm&lt;/strong&gt; (Posterior Predictive).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu cỡ mẫu tăng lên rất lớn khiến bất định tham số \(1.5^2 \to 0\), khoảng tin cậy của \(\mu(5)\) co về đúng điểm \(75.0\), nhưng khoảng dự báo 95% của một sinh viên mới vẫn rộng \(75.0 \pm 1.96(6.0) = [63.24,\; 86.76]\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-lab-7-phân-biệt-dải-đường-trung-bình-μ-và-khoảng-dự-báo-cá-thể-ỹ&quot;&gt;Video ngắn: Lab 7: Phân biệt Dải Đường Trung bình μ và Khoảng Dự báo Cá thể ỹ&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch12-07a-lab7-regression-band-vs-pred.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 14 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): giải thích trực quan vì sao khoảng dự báo luôn rộng hơn dải đường hồi quy.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=tNOu-SEacNU&quot;&gt;Statistical Rethinking 2023 - 03 - Geocentric Models&lt;/a&gt; — Richard McElreath, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Trình bày cách xây dựng hồi quy dưới dạng mô hình sinh trước khi ước lượng, bám sát quy trình đầy đủ mà bài lab yêu cầu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=fpS0NjqNHn8&quot;&gt;L4: Interpretable Linear Regressions (State of Bayes Lecture Series)&lt;/a&gt; — PyMC Labs, English. Minh họa cách khớp và diễn giải hệ số trong hồi quy tuyến tính Bayes, hỗ trợ phần suy luận hậu nghiệm của bài lab.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yDPJnV9vcHs&quot;&gt;What is a posterior predictive check and why is it useful?&lt;/a&gt; — Ben Lambert, English. Giải thích kiểm tra dự báo hậu nghiệm (PPC), hỗ trợ bước kiểm chứng mô hình sau khi chuỗi MCMC đã hội tụ.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 12.6: Lab 6: Ước lượng điểm và prior hỗn hợp</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/lab-06/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/12_06_lab_06</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  Trang này được sinh tự động từ các notebook trong thư mục &lt;code&gt;labs/&lt;/code&gt; và &lt;code&gt;labs/solutions/&lt;/code&gt;.
  Khi tệp notebook thay đổi, hãy chạy lại &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; để cập nhật Chương 12.
&lt;/div&gt;

&lt;p&gt;Trong thực tế, tri thức ban đầu hiếm khi gọn ghẽ thành một đỉnh chuông duy nhất: ví dụ trước khi mở hộp một đồng xu lạ, bạn có thể tin nó &lt;em&gt;hoặc&lt;/em&gt; là đồng xu bình thường quanh \(0.5\), &lt;em&gt;hoặc&lt;/em&gt; là đồng xu bị làm lệch mạnh quanh \(0.8\) — tức một &lt;strong&gt;prior hỗn hợp hai đỉnh (mixture prior)&lt;/strong&gt;. Điều kỳ diệu là tính liên hợp vẫn giữ nguyên cho từng thành phần hỗn hợp, chỉ cần cập nhật thêm &lt;strong&gt;trọng số hậu nghiệm&lt;/strong&gt; của từng thành phần bằng đúng bằng chứng biên (marginal likelihood)!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lab 6&lt;/strong&gt; rèn luyện kỹ năng tính toán với prior hỗn hợp và cho thấy rõ khi hậu nghiệm có nhiều đỉnh, sự khác biệt giữa Posterior Mean, Median và MAP trở nên sắc nét đến mức nào.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-prior-hỗn-hợp-liên-hợp-bằng-chứng-biên-và-hậu-nghiệm-đa-đỉnh&quot;&gt;Kiến thức cần nhớ: Prior Hỗn hợp Liên hợp, Bằng chứng Biên và Hậu nghiệm Đa đỉnh&lt;/h2&gt;

&lt;p&gt;Lab 6 mở rộng sức mạnh của họ liên hợp qua ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Định lý đóng của Hỗn hợp Liên hợp (Conjugate Mixture Closure):&lt;/strong&gt; Nếu prior là hỗn hợp \(p(\theta) = \sum_{m=1}^M w_m\, p_m(\theta)\) với mỗi \(p_m\) liên hợp với likelihood, thì hậu nghiệm vẫn là một hỗn hợp cùng họ: \(p(\theta \mid y) = \sum_{m=1}^M w_m^{\text{post}}\, p_m(\theta \mid y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật trọng số hỗn hợp qua Bằng chứng Biên:&lt;/strong&gt; Trọng số mới tỷ lệ với tích trọng số cũ và xác suất biên của dữ liệu dưới thành phần đó: \(w_m^{\text{post}} \propto w_m\, p(y \mid M_m)\) (với Beta–Binomial, \(p(y \mid M_m)\) chính là phân phối Beta–Binomial).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cảnh báo khi tóm tắt Hậu nghiệm Đa đỉnh:&lt;/strong&gt; Khi hậu nghiệm có hai đỉnh tách biệt, Posterior Mean có thể rơi vào đúng &lt;em&gt;thung lũng xác suất thấp&lt;/em&gt; ở giữa hai đỉnh — lúc này cần báo cáo toàn bộ đồ thị mật độ hoặc khoảng HDI gồm nhiều đoạn rời thay vì chỉ một con số trung bình.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Đề lab&lt;/h2&gt;
  &lt;p&gt;Bạn có thể xem trực tiếp notebook trên web, mở tệp HTML riêng hoặc tải tệp &lt;code&gt;.ipynb&lt;/code&gt; gốc về máy để thực hành.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-06.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Lab 6 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%206.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Lab 6 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-06.html&quot; title=&quot;Lab 6 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lời giải (Solution)&lt;/h2&gt;
  &lt;p&gt;Phần lời giải được đặt cùng trang để bạn đối chiếu quy trình, cách giải và mã nguồn sau khi đã tự hoàn thành đề lab.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-06-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Solution Lab 6 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_06_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Solution Lab 6 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-06-solution.html&quot; title=&quot;Lab 6 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;h2 id=&quot;giải-thích-bốn-bước-cập-nhật-một-prior-hỗn-hợp-2-thành-phần&quot;&gt;Giải thích: Bốn bước cập nhật một Prior Hỗn hợp 2 thành phần&lt;/h2&gt;

&lt;p&gt;Khi giải bài tập prior hỗn hợp trong Lab 6, hãy đi tuần tự qua 4 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật từng thành phần riêng lẻ&lt;/strong&gt; theo công thức liên hợp chuẩn để thu \(p_1(\theta \mid y)\) và \(p_2(\theta \mid y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính xác suất biên (marginal likelihood)&lt;/strong&gt; \(Z_m = p(y \mid M_m)\) của dữ liệu dưới từng thành phần prior.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật trọng số hỗn hợp:&lt;/strong&gt; \(w_m^{\text{post}} = \frac{w_m Z_m}{w_1 Z_1 + w_2 Z_2}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính kỳ vọng hậu nghiệm tổng:&lt;/strong&gt; \(\mathbb{E}[\theta \mid y] = w_1^{\text{post}}\,\mathbb{E}_1[\theta \mid y] + w_2^{\text{post}}\,\mathbb{E}_2[\theta \mid y]\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-hỗn-hợp-5050-của-hai-prior-beta-với-1-lần-tung-ra-ngửa&quot;&gt;Ví dụ tính toán làm từng bước: Hỗn hợp 50/50 của hai Prior Beta với 1 lần tung ra Ngửa&lt;/h3&gt;

&lt;p&gt;Xét prior hỗn hợp gồm \(w_1 = 0.5\) cho \(\text{Beta}(2, 8)\) (kỳ vọng \(0.2\)) và \(w_2 = 0.5\) cho \(\text{Beta}(8, 2)\) (kỳ vọng \(0.8\)). Quan sát \(n = 1\) lần tung và ra Ngửa (\(k = 1\)). Với \(n = 1, k = 1\), xác suất biên \(Z_m = P(k=1 \mid M_m)\) chính bằng kỳ vọng prior của từng thành phần!&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Thành phần&lt;/th&gt;
      &lt;th&gt;Prior&lt;/th&gt;
      &lt;th&gt;Trọng số cũ \(w_m\)&lt;/th&gt;
      &lt;th&gt;\(Z_m = P(k=1 \vert M_m)\)&lt;/th&gt;
      &lt;th&gt;\(w_m Z_m\)&lt;/th&gt;
      &lt;th&gt;Trọng số mới \(w_m^{\text{post}}\)&lt;/th&gt;
      &lt;th&gt;Hậu nghiệm thành phần&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Thành phần 1&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(2, 8)\)&lt;/td&gt;
      &lt;td&gt;\(0.50\)&lt;/td&gt;
      &lt;td&gt;\(0.20\)&lt;/td&gt;
      &lt;td&gt;\(0.10\)&lt;/td&gt;
      &lt;td&gt;\(0.10 / 0.50 = 0.20\)&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(3, 8)\) (mean \(3/11 \approx 0.273\))&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Thành phần 2&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(8, 2)\)&lt;/td&gt;
      &lt;td&gt;\(0.50\)&lt;/td&gt;
      &lt;td&gt;\(0.80\)&lt;/td&gt;
      &lt;td&gt;\(0.40\)&lt;/td&gt;
      &lt;td&gt;\(0.40 / 0.50 = 0.80\)&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(9, 2)\) (mean \(9/11 \approx 0.818\))&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Kỳ vọng hậu nghiệm tổng là:&lt;/p&gt;

\[\mathbb{E}[p \mid k=1] = 0.20 \times \frac{3}{11} + 0.80 \times \frac{9}{11} = \frac{0.6 + 7.2}{11} = \frac{7.8}{11} \approx 0.7091.\]

&lt;p&gt;Chỉ sau một lần ra Ngửa, trọng số của thành phần “thiên về Ngửa” đã nhảy từ \(50\%\) lên \(80\%\)!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Cập nhật từng thành phần \(\text{Beta}(\alpha_m + k, \beta_m + n - k)\) rồi &lt;em&gt;quên&lt;/em&gt; cập nhật trọng số \(w_m\) (giữ nguyên 50/50). Nếu quên bước trọng số, mô hình sẽ không bao giờ học được thành phần nào giải thích dữ liệu tốt hơn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu quan sát \(k = 1\) lần ra Sấp (thay vì Ngửa), tính đối xứng cho ngay trọng số mới đảo ngược thành \(w_1^{\text{post}} = 0.80, w_2^{\text{post}} = 0.20\) và kỳ vọng tổng bằng \(1 - 0.7091 = 0.2909\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-lab-6-cập-nhật-prior-hỗn-hợp-hai-đỉnh-50-beta28--50-beta82&quot;&gt;Video ngắn: Lab 6: Cập nhật Prior Hỗn hợp Hai Đỉnh (50% Beta(2,8) + 50% Beta(8,2))&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch12-06a-lab6-mixture-prior-bimodal.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): chỉ sau 1 lần tung ra Ngửa, trọng số đỉnh Ngửa vọt từ 50% lên 80%.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=brt2J5VgAHs&quot;&gt;Bayesian Statistics: What Are Priors?&lt;/a&gt; — Academia Elevated, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giới thiệu vai trò của phân phối tiên nghiệm trước khi quan sát dữ liệu; video dừng ở tiên nghiệm đơn thành phần nên phần tiên nghiệm hỗn hợp trong lab cần tự suy luận mở rộng.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kkhdIriddSI&quot;&gt;(ML 6.1) Maximum a posteriori (MAP) estimation&lt;/a&gt; — mathematicalmonk, English. Trình bày ước lượng MAP như một điểm tóm tắt rút từ hậu nghiệm, hỗ trợ phần ước lượng điểm của bài lab.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aPNrhR0dFi8&quot;&gt;What is a conjugate prior?&lt;/a&gt; — Ben Lambert, English. Minh họa trường hợp tính liên hợp bị phá vỡ khi tiên nghiệm không còn cùng họ với hàm hợp lý, làm lưu ý quan trọng khi chuyển sang tiên nghiệm hỗn hợp.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 12.5: Lab 5: Ước lượng điểm, liên hợp chuẩn, và khoảng tin cậy Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/lab-05/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/12_05_lab_05</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  Trang này được sinh tự động từ các notebook trong thư mục &lt;code&gt;labs/&lt;/code&gt; và &lt;code&gt;labs/solutions/&lt;/code&gt;.
  Khi tệp notebook thay đổi, hãy chạy lại &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; để cập nhật Chương 12.
&lt;/div&gt;

&lt;p&gt;Từ một phân phối hậu nghiệm liên tục, làm sao rút ra đúng một con số ước lượng điểm tối ưu (Mean, Median hay MAP) và xây dựng một khoảng tin cậy Bayes (Equal-Tailed hay HDI) đáng tin cậy? &lt;strong&gt;Lab 5&lt;/strong&gt; đưa bạn đi trọn vẹn quy trình đó trên mô hình liên hợp &lt;strong&gt;Normal–Normal&lt;/strong&gt; — nền tảng trực tiếp của hồi quy tuyến tính Bayes.&lt;/p&gt;

&lt;p&gt;Trước khi mở notebook, hãy xem nhanh quy tắc cộng độ chính xác (&lt;em&gt;precision&lt;/em&gt;) trong Normal–Normal để mọi công thức hậu nghiệm trở nên nhẹ nhàng và dễ nhớ.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-liên-hợp-normalnormal-ước-lượng-điểm-theo-hàm-mất-mát-và-khoảng-tin-cậy-bayes&quot;&gt;Kiến thức cần nhớ: Liên hợp Normal–Normal, Ước lượng Điểm theo Hàm Mất mát và Khoảng Tin cậy Bayes&lt;/h2&gt;

&lt;p&gt;Lab 5 tổng hợp ba trụ cột quan trọng của suy diễn tham số liên tục:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phép cộng Độ chính xác (Precision Adding) trong Normal–Normal:&lt;/strong&gt; Nếu định nghĩa độ chính xác là nghịch đảo phương sai (\(\tau_0^{-2}\) cho prior và \(n/\sigma^2\) cho dữ liệu), thì quy tắc cập nhật Normal–Normal trở nên cực kỳ trong sáng: &lt;strong&gt;độ chính xác hậu nghiệm = độ chính xác prior + độ chính xác dữ liệu&lt;/strong&gt;, và trung bình hậu nghiệm là trung bình có trọng số theo chính hai độ chính xác đó.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ba ước lượng điểm &amp;amp; Hàm mất mát tương ứng:&lt;/strong&gt; Posterior Mean tối thiểu hóa mất mát bình phương \(L_2\); Posterior Median tối thiểu hóa mất mát tuyệt đối \(L_1\); MAP tối thiểu hóa mất mát 0–1. Với hậu nghiệm đối xứng như Normal, cả ba trùng nhau tại một điểm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng tin cậy Bayes (Equal-Tailed vs. HDI):&lt;/strong&gt; Với phân phối chuẩn \(\mathcal{N}(\mu_n, \tau_n^2)\), khoảng 95% hai đuôi đều và khoảng 95% HDI trùng khít nhau: \(\mu_n \pm 1.96\,\tau_n\).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Đề lab&lt;/h2&gt;
  &lt;p&gt;Bạn có thể xem trực tiếp notebook trên web, mở tệp HTML riêng hoặc tải tệp &lt;code&gt;.ipynb&lt;/code&gt; gốc về máy để thực hành.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-05.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Lab 5 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%205.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Lab 5 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-05.html&quot; title=&quot;Lab 5 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lời giải (Solution)&lt;/h2&gt;
  &lt;p&gt;Phần lời giải được đặt cùng trang để bạn đối chiếu quy trình, cách giải và mã nguồn sau khi đã tự hoàn thành đề lab.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-05-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Solution Lab 5 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_05_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Solution Lab 5 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-05-solution.html&quot; title=&quot;Lab 5 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;h2 id=&quot;giải-thích-tính-nhanh-hậu-nghiệm-normalnormal-trong-3-bước-bằng-độ-chính-xác&quot;&gt;Giải thích: Tính nhanh hậu nghiệm Normal–Normal trong 3 bước bằng Độ chính xác&lt;/h2&gt;

&lt;p&gt;Thay vì thuộc lòng công thức phân số cồng kềnh, hãy tính theo độ chính xác (precision):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính độ chính xác prior&lt;/strong&gt; \(\Lambda_0 = 1/\tau_0^2\) và &lt;strong&gt;độ chính xác dữ liệu&lt;/strong&gt; \(\Lambda_d = n/\sigma^2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cộng hai độ chính xác:&lt;/strong&gt; \(\Lambda_n = \Lambda_0 + \Lambda_d \implies \tau_n^2 = 1/\Lambda_n\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính trung bình hậu nghiệm có trọng số:&lt;/strong&gt; \(\mu_n = \frac{\Lambda_0 \mu_0 + \Lambda_d \bar y}{\Lambda_0 + \Lambda_d}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-ước-lượng-điểm-trung-bình-thi-với-normalnormal&quot;&gt;Ví dụ tính toán làm từng bước: Ước lượng điểm trung bình thi với Normal–Normal&lt;/h3&gt;

&lt;p&gt;Giả sử điểm thi có độ lệch chuẩn đã biết \(\sigma = 10\) (\(\sigma^2 = 100\)). Prior cho điểm trung bình \(\mu\) là \(\mathcal{N}(\mu_0 = 70, \tau_0^2 = 25)\) (\(\tau_0 = 5\)). Quan sát \(n = 16\) sinh viên có điểm trung bình mẫu \(\bar y = 80\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Thành phần&lt;/th&gt;
      &lt;th&gt;Công thức&lt;/th&gt;
      &lt;th&gt;Giá trị tính tay&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Độ chính xác Prior \(\Lambda_0\)&lt;/td&gt;
      &lt;td&gt;\(1 / 25\)&lt;/td&gt;
      &lt;td&gt;\(0.04\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Độ chính xác Dữ liệu \(\Lambda_d\)&lt;/td&gt;
      &lt;td&gt;\(16 / 100\)&lt;/td&gt;
      &lt;td&gt;\(0.16\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Độ chính xác Hậu nghiệm \(\Lambda_n\)&lt;/td&gt;
      &lt;td&gt;\(0.04 + 0.16\)&lt;/td&gt;
      &lt;td&gt;\(0.20 \implies \tau_n^2 = 5.0,\; \tau_n \approx 2.236\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Trung bình Hậu nghiệm \(\mu_n\)&lt;/td&gt;
      &lt;td&gt;\(\frac{0.04(70) + 0.16(80)}{0.20}\)&lt;/td&gt;
      &lt;td&gt;\(0.2(70) + 0.8(80) = 78.0\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Khoảng tin cậy 95% Bayes&lt;/td&gt;
      &lt;td&gt;\(78.0 \pm 1.96 \times 2.236\)&lt;/td&gt;
      &lt;td&gt;\([73.62,\; 82.38]\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhầm giữa phương sai của từng quan sát \(\sigma^2\) (cố định bằng 100) với phương sai hậu nghiệm của trung bình \(\tau_n^2\) (giảm xuống chỉ còn 5.0).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nhờ \(\Lambda_d = 0.16\) gấp 4 lần \(\Lambda_0 = 0.04\), dữ liệu chiếm đúng \(80\%\) trọng số và prior chiếm \(20\%\) — kiểm tra ngay bằng nhẩm: \(70 + 0.8 \times (80 - 70) = 78.0\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-lab-5-cập-nhật-normalnormal-bằng-độ-chính-xác-τ--1σ&quot;&gt;Video ngắn: Lab 5: Cập nhật Normal–Normal bằng Độ chính xác τ = 1/σ²&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch12-05a-lab5-normal-precision-loss.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 15 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): cộng độ chính xác từ 25 bài thi để thu hẹp phân phối điểm trung bình N(70, 10²) → N(74.7, 2.09²).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YPceDssQFWo&quot;&gt;Bayesian Statistics: Credible vs Confidence Intervals&lt;/a&gt; — Academia Elevated, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Phân biệt khoảng tin cậy Bayes (credible interval) với khoảng tin cậy tần suất (confidence interval), hỗ trợ phần báo cáo khoảng hậu nghiệm của bài lab.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=MUhsT0U_nxY&quot;&gt;31 - Normal prior conjugate to normal likelihood - proof 1&lt;/a&gt; — Ox educ, English. Chứng minh tính liên hợp giữa tiên nghiệm chuẩn và hàm hợp lý chuẩn, bổ trợ trực tiếp cho mục liên hợp chuẩn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kkhdIriddSI&quot;&gt;(ML 6.1) Maximum a posteriori (MAP) estimation&lt;/a&gt; — mathematicalmonk, English. Giải thích ước lượng MAP như một điểm tóm tắt rút từ hậu nghiệm, hỗ trợ phần ước lượng điểm mà không thay thế toàn bộ phân phối.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 12.4: Lab 4: Mô hình liên hợp và cập nhật Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/lab-04/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/12_04_lab_04</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  Trang này được sinh tự động từ các notebook trong thư mục &lt;code&gt;labs/&lt;/code&gt; và &lt;code&gt;labs/solutions/&lt;/code&gt;.
  Khi tệp notebook thay đổi, hãy chạy lại &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; để cập nhật Chương 12.
&lt;/div&gt;

&lt;p&gt;Sau khi làm quen với phân phối liên tục ở Lab 3, &lt;strong&gt;Lab 4&lt;/strong&gt; đưa bạn vào thực hành trực tiếp &lt;strong&gt;cập nhật hậu nghiệm trong các mô hình liên hợp&lt;/strong&gt; (trọng tâm là Beta–Binomial và Gamma–Poisson). Đây là bài thực hành giúp bạn trực quan hóa tận mắt quá trình đường cong prior dịch chuyển và co hẹp dần thành đường cong posterior ngay trên cùng một hệ trục tọa độ.&lt;/p&gt;

&lt;p&gt;Trước khi mở notebook, hãy ôn lại công thức cập nhật nhanh và cách kiểm tra xác suất hậu nghiệm vượt ngưỡng dưới đây.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-liên-hợp-betabinomial-gammapoisson-và-trực-quan-hóa-hậu-nghiệm&quot;&gt;Kiến thức cần nhớ: Liên hợp Beta–Binomial, Gamma–Poisson và Trực quan hóa Hậu nghiệm&lt;/h2&gt;

&lt;p&gt;Lab 4 củng cố ba trụ cột của Chương 2 qua thực hành lập trình:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đại số cập nhật liên hợp (Closed-Form Updating):&lt;/strong&gt; Khi dữ liệu nhị phân \((n, k)\) kết hợp với prior \(\text{Beta}(\alpha, \beta)\), hậu nghiệm là \(\text{Beta}(\alpha+k, \beta+n-k)\); khi dữ liệu đếm \((n, \sum y_i)\) kết hợp với prior \(\text{Gamma}(\alpha, \beta)\), hậu nghiệm là \(\text{Gamma}(\alpha+\sum y_i, \beta+n)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất hậu nghiệm theo ngưỡng (Tail Probabilities):&lt;/strong&gt; Dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;beta.sf(threshold, a_post, b_post)&lt;/code&gt; để trả lời trực tiếp các câu hỏi nghiệp vụ như \(P(p &amp;gt; 0.6 \mid y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đọc hình dạng Prior – Likelihood – Posterior:&lt;/strong&gt; Vẽ cả ba đường cong trên cùng đồ thị cho thấy trực quan hậu nghiệm luôn là sự thỏa hiệp giữa prior và dữ liệu, đồng thời hẹp hơn cả hai.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Đề lab&lt;/h2&gt;
  &lt;p&gt;Bạn có thể xem trực tiếp notebook trên web, mở tệp HTML riêng hoặc tải tệp &lt;code&gt;.ipynb&lt;/code&gt; gốc về máy để thực hành.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-04.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Lab 4 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%204.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Lab 4 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-04.html&quot; title=&quot;Lab 4 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lời giải (Solution)&lt;/h2&gt;
  &lt;p&gt;Phần lời giải được đặt cùng trang để bạn đối chiếu quy trình, cách giải và mã nguồn sau khi đã tự hoàn thành đề lab.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-04-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Solution Lab 4 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_04_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Solution Lab 4 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-04-solution.html&quot; title=&quot;Lab 4 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;h2 id=&quot;giải-thích-bốn-bước-chuẩn-hoàn-thành-một-bài-toán-cập-nhật-liên-hợp-trong-lab-4&quot;&gt;Giải thích: Bốn bước chuẩn hoàn thành một bài toán cập nhật liên hợp trong Lab 4&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Xác định đúng siêu tham số prior&lt;/strong&gt; \((\alpha_0, \beta_0)\) và kiểm tra kỳ vọng ban đầu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trích xuất thống kê đủ từ dữ liệu&lt;/strong&gt; (số thành công \(k\) và thất bại \(n-k\), hoặc tổng số đếm \(\sum y_i\) và số khoảng quan sát \(n\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật siêu tham số hậu nghiệm&lt;/strong&gt; bằng phép cộng đơn giản, rồi tính kỳ vọng hậu nghiệm và xác suất vượt ngưỡng qua &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cdf&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sf&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vẽ đồ thị so sánh Prior và Posterior&lt;/strong&gt; với chú thích rõ ràng (nhãn trục, legend, đường dọc đánh dấu kỳ vọng hậu nghiệm).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-cập-nhật-betabinomial-cho-tỷ-lệ-hoàn-thành-bài-học&quot;&gt;Ví dụ tính toán làm từng bước: Cập nhật Beta–Binomial cho tỷ lệ hoàn thành bài học&lt;/h3&gt;

&lt;p&gt;Giả sử tỷ lệ sinh viên hoàn thành bài tập có prior \(p \sim \text{Beta}(3, 2)\) (kỳ vọng \(3/5 = 0.60\)). Khảo sát một lớp gồm \(n = 15\) sinh viên, có \(k = 12\) người hoàn thành (tỷ lệ mẫu \(12/15 = 0.80\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Đại lượng&lt;/th&gt;
      &lt;th&gt;Công thức&lt;/th&gt;
      &lt;th&gt;Giá trị cụ thể&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Prior&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(3, 2)\)&lt;/td&gt;
      &lt;td&gt;Kỳ vọng \(3 / 5 = 0.600\), SD \(\approx 0.200\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Hậu nghiệm&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(3+12,\; 2+3) = \text{Beta}(15, 5)\)&lt;/td&gt;
      &lt;td&gt;Kỳ vọng \(15 / 20 = 0.750\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Độ lệch chuẩn hậu nghiệm&lt;/td&gt;
      &lt;td&gt;\(\sqrt{\frac{15 \times 5}{20^2 \times 21}}\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{75 / 8400} \approx 0.0945\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Đỉnh hậu nghiệm (MAP)&lt;/td&gt;
      &lt;td&gt;\(\frac{15 - 1}{20 - 2}\)&lt;/td&gt;
      &lt;td&gt;\(14 / 18 \approx 0.778\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Độ lệch chuẩn giảm hơn một nửa (từ \(0.200\) xuống \(0.0945\)) và kỳ vọng dịch mượt từ \(0.600\) về \(0.750\) (nằm giữa prior \(0.600\) và dữ liệu \(0.800\)).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Cộng nhầm \(n\) (tổng số lần thử) vào \(\beta_0\) thay vì cộng \(n - k\) (số lần thất bại)! Luôn kiểm tra nhanh: tổng \(\alpha_{\text{post}} + \beta_{\text{post}}\) phải đúng bằng \(\alpha_0 + \beta_0 + n\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Trong ví dụ trên, \(\alpha_0 + \beta_0 + n = 3 + 2 + 15 = 20\), khớp hoàn toàn với \(\alpha_{\text{post}} + \beta_{\text{post}} = 15 + 5 = 20\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-lab-4-cập-nhật-liên-hợp-beta3-2--1825-đạt--beta21-9&quot;&gt;Video ngắn: Lab 4: Cập nhật Liên hợp Beta(3, 2) + 18/25 Đạt → Beta(21, 9)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch12-04a-lab4-beta-binomial-workflow.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): chuyển động mượt từ Prior đến Posterior và xuất khoảng tin cậy Bayes 95%.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aPNrhR0dFi8&quot;&gt;What is a conjugate prior?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giải thích khái niệm tiên nghiệm liên hợp, phù hợp với yêu cầu cập nhật hậu nghiệm dạng đóng mà không cần tính lại tích phân.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=hKYvZF9wXkk&quot;&gt;20 - Beta conjugate prior to Binomial and Bernoulli likelihoods&lt;/a&gt; — Ox educ, English. Minh họa cách mô hình Beta–Binomial cộng số lần thành công và thất bại trực tiếp vào tham số, hỗ trợ cặp liên hợp trọng tâm của bài lab.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=GqSX-8AQL90&quot;&gt;Bayesian Updates and Conjugate Priors&lt;/a&gt; — Steve Brunton, English. Trình bày nhiều cặp liên hợp được cập nhật tuần tự, giúp nhận ra cấu trúc chung khi đổi họ phân phối.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 12.3: Lab 3: Phân tích Bayes và phân phối liên tục</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/lab-03/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/12_03_lab_03</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  Trang này được sinh tự động từ các notebook trong thư mục &lt;code&gt;labs/&lt;/code&gt; và &lt;code&gt;labs/solutions/&lt;/code&gt;.
  Khi tệp notebook thay đổi, hãy chạy lại &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; để cập nhật Chương 12.
&lt;/div&gt;

&lt;p&gt;Từ thế giới rời rạc với bảng đếm hữu hạn, &lt;strong&gt;Lab 3&lt;/strong&gt; đưa bạn sang thế giới của các &lt;strong&gt;phân phối liên tục&lt;/strong&gt; — nơi xác suất được đo bằng diện tích dưới đường cong hàm mật độ (PDF), các hàm phân phối tích lũy (CDF) và hàm phân vị (PPF/quantile). Đây là bước chuẩn bị kỹ thuật không thể thiếu để đọc hiểu phân phối Beta, Gamma, Normal và khoảng tin cậy Bayes trong &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Hãy xem kỹ bản đồ kiến thức nền và ví dụ chuẩn hóa điểm \(z\) dưới đây trước khi bắt đầu làm bài thực hành.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-pdf-cdf-ppf-và-tính-toán-phân-phối-liên-tục-trong-scipystats&quot;&gt;Kiến thức cần nhớ: PDF, CDF, PPF và Tính toán Phân phối Liên tục trong &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;Lab 3 xoay quanh ba trụ cột toán học – lập trình của biến ngẫu nhiên liên tục:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bộ ba hàm cốt lõi (PDF – CDF – PPF):&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pdf(x)&lt;/code&gt; cho mật độ tại điểm \(x\); &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cdf(x)&lt;/code&gt; cho xác suất tích lũy \(P(X \le x)\); và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ppf(q)&lt;/code&gt; (hàm ngược của CDF) tìm ngưỡng \(x_q\) sao cho \(P(X \le x_q) = q\) — công cụ trực tiếp để tính khoảng tin cậy Bayes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa tuyến tính (Z-score Transformation):&lt;/strong&gt; Mọi biến phân phối chuẩn \(X \sim \mathcal{N}(\mu, \sigma^2)\) đều quy về chuẩn tắc \(Z = (X - \mu)/\sigma \sim \mathcal{N}(0, 1)\), giúp nhẩm nhanh xác suất và kiểm tra độ hợp lý của kết quả máy tính.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích phân số &amp;amp; Lưới cho mật độ hậu nghiệm liên tục:&lt;/strong&gt; Khi làm việc với tham số liên tục \(\theta\), ta thay tổng bằng tích phân \(\int p(y \mid \theta)p(\theta)\,d\theta\) và xấp xỉ trên lưới mịn bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.trapz&lt;/code&gt; hoặc chuẩn hóa trọng số.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Đề lab&lt;/h2&gt;
  &lt;p&gt;Bạn có thể xem trực tiếp notebook trên web, mở tệp HTML riêng hoặc tải tệp &lt;code&gt;.ipynb&lt;/code&gt; gốc về máy để thực hành.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-03.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Lab 3 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%203.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Lab 3 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-03.html&quot; title=&quot;Lab 3 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lời giải (Solution)&lt;/h2&gt;
  &lt;p&gt;Phần lời giải được đặt cùng trang để bạn đối chiếu quy trình, cách giải và mã nguồn sau khi đã tự hoàn thành đề lab.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-03-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Solution Lab 3 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_03_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Solution Lab 3 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-03-solution.html&quot; title=&quot;Lab 3 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;h2 id=&quot;giải-thích-ba-câu-hỏi-chuẩn-khi-tính-xác-suất-trên-phân-phối-liên-tục&quot;&gt;Giải thích: Ba câu hỏi chuẩn khi tính xác suất trên phân phối liên tục&lt;/h2&gt;

&lt;p&gt;Mọi bài toán về phân phối liên tục trong Lab 3 đều rơi vào một trong ba dạng sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất đuôi phải \(P(X &amp;gt; a)\):&lt;/strong&gt; Dùng \(1 - F(a)\) (trong &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats&lt;/code&gt; nên dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sf(a)&lt;/code&gt; — &lt;em&gt;survival function&lt;/em&gt; — để chính xác số học hơn ở đuôi rất nhỏ).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất trên một khoảng \(P(a \le X \le b)\):&lt;/strong&gt; Tính bằng hiệu hai giá trị CDF: \(F(b) - F(a)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tìm phân vị ngược (tìm \(x\) biết xác suất \(q\)):&lt;/strong&gt; Giải \(F(x) = q \iff x = F^{-1}(q)\) bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ppf(q)&lt;/code&gt; (hoặc \(x = \mu + z_q \sigma\) với phân phối chuẩn).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-tính-nhanh-với-phân-phối-chuẩn-x-sim-mathcaln100-152&quot;&gt;Ví dụ tính toán làm từng bước: Tính nhanh với phân phối chuẩn \(X \sim \mathcal{N}(100, 15^2)\)&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Câu hỏi&lt;/th&gt;
      &lt;th&gt;Công thức quy đổi chuẩn tắc&lt;/th&gt;
      &lt;th&gt;Lệnh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats.norm&lt;/code&gt;&lt;/th&gt;
      &lt;th&gt;Kết quả xấp xỉ&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(P(X &amp;gt; 115)\)&lt;/td&gt;
      &lt;td&gt;\(1 - \Phi\!\left(\frac{115-100}{15}\right) = 1 - \Phi(1.0)\)&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;norm.sf(115, 100, 15)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;\(1 - 0.8413 = 0.1587\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(P(85 \le X \le 130)\)&lt;/td&gt;
      &lt;td&gt;\(\Phi(2.0) - \Phi(-1.0)\)&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;norm.cdf(130,100,15) - norm.cdf(85,100,15)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;\(0.9772 - 0.1587 = 0.8185\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Tìm \(x\) để \(P(X \le x) = 0.95\)&lt;/td&gt;
      &lt;td&gt;\(100 + 1.645 \times 15\)&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;norm.ppf(0.95, 100, 15)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;\(124.67\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Truyền &lt;em&gt;phương sai&lt;/em&gt; \(\sigma^2\) (ví dụ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;225&lt;/code&gt;) thay vì &lt;em&gt;độ lệch chuẩn&lt;/em&gt; \(\sigma\) (ví dụ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;15&lt;/code&gt;) vào tham số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale&lt;/code&gt; của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats.norm(loc=mu, scale=sigma)&lt;/code&gt;. Đây là lỗi lập trình phổ biến nhất ở Lab 3!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Theo quy tắc kinh nghiệm 68–95–99.7, khoảng \([\mu - 2\sigma, \mu + 2\sigma] = [70, 130]\) phải chứa xấp xỉ \(95.4\%\) khối lượng xác suất — hãy luôn nhẩm nhanh mốc này để kiểm tra xem tham số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale&lt;/code&gt; đã nhập đúng chưa.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-lab-3-phân-biệt-pdf-cdf-và-ppf-trong-scipystats-trên-n100-15&quot;&gt;Video ngắn: Lab 3: Phân biệt PDF, CDF và PPF trong scipy.stats trên N(100, 15²)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch12-03a-lab3-pdf-cdf-ppf.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 15 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): quét diện tích tích lũy CDF và tìm mốc phân vị ngược PPF trực quan trên đường cong chuẩn.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Why “probability of 0” does not mean “impossible”&lt;/td&gt;
          &lt;td&gt;Probabilities of probabilities, part 2](https://www.youtube.com/watch?v=ZA4JkHKZM50) — 3Blue1Brown, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giải thích sự khác biệt giữa mật độ xác suất liên tục và xác suất tại một điểm, làm nền tảng khi chuyển từ phân phối rời rạc sang liên tục.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=juF3r12nM5A&quot;&gt;The Beta distribution in 12 minutes!&lt;/a&gt; — Luis Serrano Academy, English. Trình bày phân phối Beta cho một tham số xác suất chưa biết, hỗ trợ phần suy luận Bayes với biến liên tục.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=rzFX5NWojp0&quot;&gt;The Normal Distribution, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Ôn lại các tham số của phân phối chuẩn, hữu ích khi bài lab làm việc với mô hình liên tục dạng hình chuông.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 12.2: Lab 2: Mô phỏng và cập nhật Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/lab-02/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/12_02_lab_02</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  Trang này được sinh tự động từ các notebook trong thư mục &lt;code&gt;labs/&lt;/code&gt; và &lt;code&gt;labs/solutions/&lt;/code&gt;.
  Khi tệp notebook thay đổi, hãy chạy lại &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; để cập nhật Chương 12.
&lt;/div&gt;

&lt;p&gt;Đôi khi một bài toán xác suất có điều kiện (như trò chơi Monty Hall hay chuỗi cập nhật nhiều bước) khiến trực giác con người hoàn toàn bối rối dù phép toán chỉ dài vài dòng. Cách nhanh nhất để kiểm chứng xem công thức của bạn có đúng hay không là &lt;strong&gt;mô phỏng trực tiếp hàng chục nghìn lần bằng Python&lt;/strong&gt; và so sánh tần suất thực nghiệm với kết quả giải tích.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lab 2&lt;/strong&gt; rèn luyện kỹ năng kết hợp hai vũ khí mạnh nhất của người làm thống kê Bayes: mô phỏng Monte Carlo và cập nhật hậu nghiệm từng bước.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-mô-phỏng-monte-carlo-độ-hội-tụ-và-cập-nhật-bayes-từng-bước&quot;&gt;Kiến thức cần nhớ: Mô phỏng Monte Carlo, Độ hội tụ và Cập nhật Bayes từng bước&lt;/h2&gt;

&lt;p&gt;Lab 2 nối ba trụ cột thực hành cốt lõi:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô phỏng sinh dữ liệu (Generative Simulation):&lt;/strong&gt; Chuyển thẳng quy tắc của bài toán thành hàm ngẫu nhiên Python (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.random.default_rng&lt;/code&gt;), cố định &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seed&lt;/code&gt; để tái lập và đếm tần suất biến cố xảy ra.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sai số chuẩn Monte Carlo (MCSE):&lt;/strong&gt; Với \(M\) lần mô phỏng, sai số ước lượng xác suất giảm theo \(1/\sqrt{M}\) — giúp bạn biết cần chạy \(10^4\) hay \(10^5\) lần để khớp với công thức giải tích tới 2–3 chữ số thập phân.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật tuần tự trên không gian rời rạc:&lt;/strong&gt; Theo dõi cách phân phối hậu nghiệm co hẹp dần sau từng quan sát mới và kiểm chứng tính bất biến khi cập nhật gộp so với cập nhật từng bước.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Đề lab&lt;/h2&gt;
  &lt;p&gt;Bạn có thể xem trực tiếp notebook trên web, mở tệp HTML riêng hoặc tải tệp &lt;code&gt;.ipynb&lt;/code&gt; gốc về máy để thực hành.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-02.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Lab 2 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%202.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Lab 2 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-02.html&quot; title=&quot;Lab 2 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lời giải (Solution)&lt;/h2&gt;
  &lt;p&gt;Phần lời giải được đặt cùng trang để bạn đối chiếu quy trình, cách giải và mã nguồn sau khi đã tự hoàn thành đề lab.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-02-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Solution Lab 2 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_02_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Solution Lab 2 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-02-solution.html&quot; title=&quot;Lab 2 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;h2 id=&quot;giải-thích-đối-chiếu-mô-phỏng-và-công-thức-giải-tích-trong-3-bước&quot;&gt;Giải thích: Đối chiếu Mô phỏng và Công thức Giải tích trong 3 bước&lt;/h2&gt;

&lt;p&gt;Khi làm các bài mô phỏng trong Lab 2, hãy luôn kiểm tra chéo theo 3 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Chạy giải tích trước trên trường hợp nhỏ&lt;/strong&gt; để có mốc đối chiếu chính xác.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô phỏng \(M = 10\,000\) lần độc lập&lt;/strong&gt; và tính tỷ lệ thực nghiệm \(\hat p\) cùng sai số chuẩn \(\mathrm{MCSE} = \sqrt{\hat p(1-\hat p)/M}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra chênh lệch \(\vert\hat p - p_{\text{lý thuyết}}\vert\):&lt;/strong&gt; Nếu lớn hơn \(3\,\mathrm{MCSE}\), gần như chắc chắn mã mô phỏng đang có lỗi logic ở bước điều kiện hóa!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-kiểm-chứng-bài-toán-monty-hall-bằng-monte-carlo&quot;&gt;Ví dụ tính toán làm từng bước: Kiểm chứng bài toán Monty Hall bằng Monte Carlo&lt;/h3&gt;

&lt;p&gt;Với chiến lược “luôn đổi cửa”, xác suất thắng lý thuyết là \(p = 2/3 \approx 0.6667\). Khi chạy \(M = 10\,000\) ván mô phỏng:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Chiến lược&lt;/th&gt;
      &lt;th&gt;Xác suất lý thuyết \(p\)&lt;/th&gt;
      &lt;th&gt;\(\mathrm{MCSE} = \sqrt{p(1-p)/10000}\)&lt;/th&gt;
      &lt;th&gt;Vùng kết quả mô phỏng hợp lệ (\(p \pm 2\,\mathrm{MCSE}\))&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Giữ nguyên cửa&lt;/td&gt;
      &lt;td&gt;\(1/3 \approx 0.3333\)&lt;/td&gt;
      &lt;td&gt;\(\approx 0.0047\)&lt;/td&gt;
      &lt;td&gt;\([0.3239,\; 0.3427]\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Đổi cửa&lt;/td&gt;
      &lt;td&gt;\(2/3 \approx 0.6667\)&lt;/td&gt;
      &lt;td&gt;\(\approx 0.0047\)&lt;/td&gt;
      &lt;td&gt;\([0.6573,\; 0.6761]\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Nếu code của bạn in ra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.501&lt;/code&gt; cho chiến lược đổi cửa (lệch hơn \(35\,\mathrm{MCSE}\) so với \(0.6667\)!), bạn biết ngay mình đã mô phỏng sai hành vi người dẫn chương trình (ví dụ cho người dẫn mở cửa ngẫu nhiên thay vì luôn mở cửa có dê).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Dùng chung biến ngẫu nhiên hoặc quên đặt lại trạng thái giữa các lần lặp trong vòng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt;, làm các lần chạy bị phụ thuộc nhau và cho kết quả lệch hệ thống.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu tăng số lần mô phỏng từ \(10\,000\) lên \(160\,000\) (gấp 16 lần), \(\mathrm{MCSE}\) giảm \(4\) lần từ \(0.0047\) xuống khoảng \(0.0012\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-lab-2-mô-phỏng-monte-carlo-300-ván-monty-hall-đổi-cửa-667-vs-giữ-333&quot;&gt;Video ngắn: Lab 2: Mô phỏng Monte Carlo 300 ván Monty Hall (Đổi cửa 66.7% vs Giữ 33.3%)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch12-02a-lab2-monty-hall-sim.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 14 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): kiểm chứng trực tiếp trên Python lý do đổi cửa thắng gấp đôi giữ cửa.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R1vcdhPBlXA&quot;&gt;Statistical Rethinking 2023 - 02 - The Garden of Forking Data&lt;/a&gt; — Richard McElreath, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giải thích cách cập nhật Bayes bằng việc sinh và đếm các khả năng dữ liệu, phù hợp với trọng tâm mô phỏng của bài lab.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=7TqhmX92P6U&quot;&gt;What is Monte Carlo Simulation?&lt;/a&gt; — IBM Technology, English. Giới thiệu nguyên lý mô phỏng Monte Carlo từ một giả định xác suất, hỗ trợ phần thay thế tích phân dạng đóng bằng mô phỏng.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Minh họa trực quan bước nhân tiên nghiệm với hàm hợp lý rồi chuẩn hóa, làm khung tham chiếu cho vòng lặp cập nhật trong lab.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 12.1: Lab 1: Xác suất có điều kiện và quy tắc Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/lab-01/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/vi/chapter12/12_01_lab_01</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  Trang này được sinh tự động từ các notebook trong thư mục &lt;code&gt;labs/&lt;/code&gt; và &lt;code&gt;labs/solutions/&lt;/code&gt;.
  Khi tệp notebook thay đổi, hãy chạy lại &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; để cập nhật Chương 12.
&lt;/div&gt;

&lt;p&gt;Mọi kỹ năng suy diễn Bayes vững chắc đều bắt đầu từ việc tự tay biến một câu chữ đời thường thành công thức xác suất có điều kiện — rồi viết mã kiểm chứng lại kết quả đó. Trong &lt;strong&gt;Lab 1&lt;/strong&gt;, bạn sẽ thực hành trực tiếp quy tắc xác suất toàn phần và định lý Bayes trên các tình huống rời rạc kinh điển, nơi trực giác thông thường rất dễ mắc bẫy tỷ lệ nền (&lt;em&gt;base rate fallacy&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Trước khi mở notebook, hãy lướt qua bản đồ kiến thức nền và khung giải thích dưới đây để nắm chắc quy trình tách bảng tần suất trước khi viết dòng mã đầu tiên.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-từ-không-gian-mẫu-rời-rạc-đến-cập-nhật-bayes-bằng-python&quot;&gt;Kiến thức cần nhớ: Từ Không gian mẫu rời rạc đến Cập nhật Bayes bằng Python&lt;/h2&gt;

&lt;p&gt;Lab 1 kết nối ba trụ cột cốt lõi đã học ở Chương 0 và Chương 1:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất có điều kiện &amp;amp; Phân hoạch (Conditional Probability &amp;amp; Partitioning):&lt;/strong&gt; Biết biến cố \(B\) xảy ra đồng nghĩa với việc thu hẹp không gian mẫu từ \(\Omega\) xuống đúng tập \(B\), và mọi phép tính đều dựa trên tỷ số \(P(A \cap B)/P(B)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy tắc Xác suất Toàn phần &amp;amp; Định lý Bayes:&lt;/strong&gt; Mẫu số \(P(B) = \sum_i P(B \mid H_i)P(H_i)\) đóng vai trò hằng số chuẩn hóa, biến tích &lt;em&gt;prior × likelihood&lt;/em&gt; thành phân phối hậu nghiệm hợp lệ có tổng bằng 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lập trình kiểm chứng (Vectorized Normalization):&lt;/strong&gt; Trong Python/NumPy, toàn bộ bảng Bayes quy về hai dòng mã: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;unnorm = prior * likelihood&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;posterior = unnorm / unnorm.sum()&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Đề lab&lt;/h2&gt;
  &lt;p&gt;Bạn có thể xem trực tiếp notebook trên web, mở tệp HTML riêng hoặc tải tệp &lt;code&gt;.ipynb&lt;/code&gt; gốc về máy để thực hành.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-01.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Lab 1 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%201.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Lab 1 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-01.html&quot; title=&quot;Lab 1 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lời giải (Solution)&lt;/h2&gt;
  &lt;p&gt;Phần lời giải được đặt cùng trang để bạn đối chiếu quy trình, cách giải và mã nguồn sau khi đã tự hoàn thành đề lab.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-01-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Mở Solution Lab 1 dạng HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_01_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Tải Solution Lab 1 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-01-solution.html&quot; title=&quot;Lab 1 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;h2 id=&quot;giải-thích-quy-trình-4-bước-giải-mọi-bài-tập-lab-1-không-nhầm-chiều-điều-kiện&quot;&gt;Giải thích: Quy trình 4 bước giải mọi bài tập Lab 1 không nhầm chiều điều kiện&lt;/h2&gt;

&lt;p&gt;Khi đọc một đề bài chữ trong Lab 1, hãy tuân thủ đúng 4 bước sau trước khi bấm chạy code:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gọi tên rạch ròi giả thuyết \(H_i\) và bằng chứng \(E\):&lt;/strong&gt; Xác định rõ cái nào là nguyên nhân chưa biết (\(H_i\)), cái nào là dữ liệu đã quan sát (\(E\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đọc đúng chiều của từng con số trong đề:&lt;/strong&gt; Phân biệt \(P(E \mid H_i)\) (likelihood) với \(P(H_i \mid E)\) (posterior đang cần tìm).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính tích chưa chuẩn hóa&lt;/strong&gt; \(u_i = P(H_i)\,P(E \mid H_i)\) cho tất cả các giả thuyết.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa bằng tổng&lt;/strong&gt; \(P(E) = \sum_i u_i\) để thu \(P(H_i \mid E) = u_i / P(E)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-chọn-ngẫu-nhiên-1-trong-2-hộp-linh-kiện&quot;&gt;Ví dụ tính toán làm từng bước: Chọn ngẫu nhiên 1 trong 2 hộp linh kiện&lt;/h3&gt;

&lt;p&gt;Hộp A chiếm \(40\%\) kho hàng với tỷ lệ lỗi \(5\%\); Hộp B chiếm \(60\%\) kho hàng với tỷ lệ lỗi \(2\%\). Lấy ngẫu nhiên 1 linh kiện và thấy nó bị lỗi (\(E\)). Xác suất linh kiện đó từ Hộp A là bao nhiêu?&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Giả thuyết&lt;/th&gt;
      &lt;th&gt;Prior \(P(H)\)&lt;/th&gt;
      &lt;th&gt;Likelihood \(P(E \vert H)\)&lt;/th&gt;
      &lt;th&gt;Tích \(u = P(H)P(E \vert H)\)&lt;/th&gt;
      &lt;th&gt;Posterior \(P(H \vert E)\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Hộp A&lt;/td&gt;
      &lt;td&gt;\(0.40\)&lt;/td&gt;
      &lt;td&gt;\(0.05\)&lt;/td&gt;
      &lt;td&gt;\(0.020\)&lt;/td&gt;
      &lt;td&gt;\(0.020 / 0.032 = 0.625\; (62.5\%)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Hộp B&lt;/td&gt;
      &lt;td&gt;\(0.60\)&lt;/td&gt;
      &lt;td&gt;\(0.02\)&lt;/td&gt;
      &lt;td&gt;\(0.012\)&lt;/td&gt;
      &lt;td&gt;\(0.012 / 0.032 = 0.375\; (37.5\%)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Tổng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(1.00\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(P(E) = 0.032\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(1.000\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhầm \(P(\text{Lỗi} \mid \text{Hộp A}) = 5\%\) với \(P(\text{Hộp A} \mid \text{Lỗi}) = 62.5\%\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu Hộp A chỉ chiếm \(10\%\) kho hàng (Hộp B chiếm \(90\%\)), tích mới là \(0.005\) và \(0.018\), nên \(P(\text{Hộp A} \mid \text{Lỗi}) = 0.005 / 0.023 \approx 21.7\%\) — tỷ lệ nền nhỏ kéo hậu nghiệm xuống ngay lập tức.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-lab-1-giải-bài-toán-2-hộp-linh-kiện-bằng-bảng-bayes-4-cột&quot;&gt;Video ngắn: Lab 1: Giải Bài toán 2 Hộp Linh kiện bằng Bảng Bayes 4 Cột&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch12-01a-lab1-two-boxes-bayes.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Video dài khoảng 14 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): tính trực tiếp nhánh Hộp A (0.10) vs Hộp B (0.25) để suy ra P(Hộp B&lt;/td&gt;
      &lt;td&gt;Lỗi) = 71.4%.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Bài 2. Công Thức Xác Suất Toàn Phần. Công Thức Bayes (Full Dạng) - Toán 12 (Sgk Mới)&lt;/td&gt;
          &lt;td&gt; &lt;/td&gt;
          &lt;td&gt;Thầy Tiến](https://www.youtube.com/watch?v=n7bUihWfW4w) — Thầy Nguyễn Phan Tiến, Tiếng Việt. &lt;strong&gt;Xem trước&lt;/strong&gt;. Ôn tập các dạng bài tính xác suất có điều kiện và công thức Bayes bằng tay, sát với nội dung thực hành của bài lab.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=_IgyaD7vOOA&quot;&gt;Conditional Probabilities, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Minh họa cách đọc xác suất có điều kiện trên tình huống cụ thể, hỗ trợ bước diễn giải trước khi thay số.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Trực quan hóa ý nghĩa hình học của định lý Bayes như quá trình cập nhật niềm tin thay vì chỉ là một phép tính tỷ số.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 12.7: Lab 7: The Bayesian Regression Workflow</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/en/chapter12/lab-07/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/en/chapter12/12_07_lab_07</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  This page is auto-generated from the notebooks in &lt;code&gt;labs/&lt;/code&gt; and &lt;code&gt;labs/solutions/&lt;/code&gt;.
  When the notebook files change, rerun &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; to update Chapter 12.
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lab assignment&lt;/h2&gt;
  &lt;p&gt;You can read the notebook directly on the web, open the standalone HTML file, or download the original &lt;code&gt;.ipynb&lt;/code&gt; file to work locally.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-07.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 7 as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%207.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 7 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-07.html&quot; title=&quot;Lab 7 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Solution&lt;/h2&gt;
  &lt;p&gt;The solution is placed on the same page so you can compare the workflow, the answers, and the code after you have finished the lab on your own.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-07-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 7 Solution as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_07_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 7 Solution .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-07-solution.html&quot; title=&quot;Lab 7 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;p&gt;Everything in Chapters 0 through 8 comes together in &lt;strong&gt;Lab 7: The Complete Bayesian Regression Workflow&lt;/strong&gt;. Rather than jumping straight to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fit()&lt;/code&gt;, a disciplined Bayesian runs a &lt;strong&gt;five-step closed loop&lt;/strong&gt;: (1) standardize predictors &amp;amp; specify weakly informative priors, (2) run &lt;strong&gt;Prior Predictive Checks&lt;/strong&gt;, (3) sample the posterior &amp;amp; audit MCMC diagnostics (\(\hat{R} \le 1.01\), ESS, zero divergences), (4) inspect &lt;strong&gt;Posterior Predictive Checks&lt;/strong&gt;, and (5) evaluate out-of-sample generalization via &lt;strong&gt;PSIS-LOO&lt;/strong&gt;!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-five-step-bayesian-regression-workflow&quot;&gt;Key ideas: The Five-Step Bayesian Regression Workflow&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Standardization &amp;amp; Prior Predictive Check:&lt;/strong&gt; Center/scale predictors so priors like \(\alpha \sim \mathcal{N}(\bar{y}, s_y),\; \beta \sim \mathcal{N}(0, 1)\) generate plausible prior regression lines before touching real outcomes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior Sampling &amp;amp; Convergence Diagnostics:&lt;/strong&gt; Verify \(\hat{R} \le 1.01\), bulk/tail ESS \(\ge 400\), clean fuzzy-caterpillar trace plots, and zero HMC divergences.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior Parameter &amp;amp; Uncertainty Bands:&lt;/strong&gt; Plot the 94%/95% credible band around the mean line \(\mu(x)\) AND the wider &lt;strong&gt;Posterior Predictive Band&lt;/strong&gt; around individual future points \(\tilde{y}(x)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior Predictive Checks &amp;amp; LOO-CV Comparison:&lt;/strong&gt; Verify replicated datasets match observed residuals/extremes and compare linear vs. quadratic/robust models with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;az.loo&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-separating-credible-line-band-vs-posterior-predictive-band&quot;&gt;Worked Numerical Example: Separating Credible Line Band vs. Posterior Predictive Band&lt;/h3&gt;

&lt;p&gt;Suppose your Lab 7 Bayesian linear regression on standardized \(x\) yields posterior draws with mean line \(\hat{\mu}(x) = 50 + 6x\), slope SD \(0.8\), intercept SD \(1.0\), and residual noise \(\sigma = 8.0\). Evaluate uncertainty at \(x = 0\) (the center):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;95% Credible Interval for the &lt;em&gt;mean regression line&lt;/em&gt; \(\mu(0)\):&lt;/strong&gt;
\(50.0 \pm 1.96(1.0) = \mathbf{[48.04,\; 51.96]}\) (width \(\approx 3.9\) units).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;95% Posterior Predictive Interval for a &lt;em&gt;new individual observation&lt;/em&gt; \(\tilde{y}(0)\):&lt;/strong&gt;
\(\mathrm{SD}_{\text{pred}} = \sqrt{1.0^2 + 8.0^2} = \sqrt{65} \approx 8.06 \implies 50.0 \pm 1.96(8.06) = \mathbf{[34.20,\; 65.80]}\) (width \(\approx 31.6\) units — &lt;strong&gt;8× wider!&lt;/strong&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-lab-7-workflow-habits-to-keep-forever&quot;&gt;Explanation: Four Lab 7 Workflow Habits to Keep Forever&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Never interpret posterior plots before checking \(\hat{R}\) and divergences:&lt;/strong&gt; Unconverged MCMC chains produce crisp-looking plots that are completely wrong!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always plot &lt;em&gt;both&lt;/em&gt; the mean-line ribbon and the predictive ribbon:&lt;/strong&gt; Roughly 95% of actual data dots should fall inside the &lt;em&gt;predictive&lt;/em&gt; ribbon, NOT inside the narrow mean-line ribbon!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check residual plots against \(x\) for hidden curvature:&lt;/strong&gt; If residuals curve like a frown, compare a quadratic term using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;az.compare(..., ic=&quot;loo&quot;)&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Run a quick Student-\(t\) sensitivity check if outliers appear:&lt;/strong&gt; Seeing whether \(\beta_1\) shifts under Student-\(t\) immediately tells you if 2 extreme points were steering your line.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the Lab 7 regression above, why do almost &lt;em&gt;none&lt;/em&gt; of the raw scatter points fall inside the narrow 95% credible band of the mean line &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[48.04, 51.96]&lt;/code&gt;, while ~95% fall inside &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[34.20, 65.80]&lt;/code&gt;?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=tNOu-SEacNU&quot;&gt;Statistical Rethinking 2023 - 03 - Geocentric Models&lt;/a&gt; — Richard McElreath, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch regression written as a generative model before estimation, exactly the workflow the lab asks you to follow end to end.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=fpS0NjqNHn8&quot;&gt;L4: Interpretable Linear Regressions (State of Bayes Lecture Series)&lt;/a&gt; — PyMC Labs, English. Watch a Bayesian linear regression being fit and its coefficients read; it supports the lab’s posterior-inference part.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yDPJnV9vcHs&quot;&gt;What is a posterior predictive check and why is it useful?&lt;/a&gt; — Ben Lambert, English. Watch a posterior predictive check; use it for the lab step that does not stop once the chain has converged.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 12.6: Lab 6: Point Estimation and Mixture Priors</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/en/chapter12/lab-06/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/en/chapter12/12_06_lab_06</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  This page is auto-generated from the notebooks in &lt;code&gt;labs/&lt;/code&gt; and &lt;code&gt;labs/solutions/&lt;/code&gt;.
  When the notebook files change, rerun &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; to update Chapter 12.
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lab assignment&lt;/h2&gt;
  &lt;p&gt;You can read the notebook directly on the web, open the standalone HTML file, or download the original &lt;code&gt;.ipynb&lt;/code&gt; file to work locally.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-06.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 6 as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%206.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 6 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-06.html&quot; title=&quot;Lab 6 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Solution&lt;/h2&gt;
  &lt;p&gt;The solution is placed on the same page so you can compare the workflow, the answers, and the code after you have finished the lab on your own.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-06-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 6 Solution as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_06_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 6 Solution .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-06-solution.html&quot; title=&quot;Lab 6 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;p&gt;What if your prior belief isn’t a single neat bell curve—for example, you suspect a coin came &lt;em&gt;either&lt;/em&gt; from a trick factory biased toward 0.25 &lt;em&gt;or&lt;/em&gt; from a trick factory biased toward 0.75, with almost no chance it’s 0.50? No single Beta distribution can represent two separate humps—but a &lt;strong&gt;mixture of conjugate priors&lt;/strong&gt; \(p(\theta) = w_1 p_1(\theta) + w_2 p_2(\theta)\) can, and remarkably, &lt;strong&gt;the posterior is ALSO a clean mixture of the updated conjugate components&lt;/strong&gt; with updated component weights!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lab 6&lt;/strong&gt; explores &lt;strong&gt;mixture priors and multimodal posteriors&lt;/strong&gt;—revealing why reporting a single posterior mean on a bimodal distribution can land squarely in a zero-probability valley!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-core-lab-6-skills--conjugate-mixtures--multimodality&quot;&gt;Key ideas: Core Lab 6 Skills — Conjugate Mixtures &amp;amp; Multimodality&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mixture Priors Remain Conjugate:&lt;/strong&gt; Multiplying \(w_1\,\mathrm{Beta}(a_1, b_1) + w_2\,\mathrm{Beta}(a_2, b_2)\) by a Binomial likelihood yields \(w_1&apos;\,\mathrm{Beta}(a_1+k, b_1+n-k) + w_2&apos;\,\mathrm{Beta}(a_2+k, b_2+n-k)\), where each new weight \(w_j&apos; \propto w_j \cdot p(D\mid M_j)\) scales by its &lt;strong&gt;marginal likelihood&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why Point Summaries Fail on Bimodal Posteriors:&lt;/strong&gt; If 50% of mass sits at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.25&lt;/code&gt; and 50% sits at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.75&lt;/code&gt;, the posterior mean (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.50&lt;/code&gt;) sits in the least probable spot of all!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Loss-Function Sensitivity:&lt;/strong&gt; Comparing MAP, mean, and median on mixture posteriors teaches you to always &lt;em&gt;plot&lt;/em&gt; the density before summarizing.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-updating-a-2-component-mixture-prior-by-hand&quot;&gt;Worked Numerical Example: Updating a 2-Component Mixture Prior by Hand&lt;/h3&gt;

&lt;p&gt;Start with a 50–50 mixture of two Beta priors: \(w_1 = 0.5\) on \(\mathrm{Beta}(2, 8)\) (low rate) and \(w_2 = 0.5\) on \(\mathrm{Beta}(8, 2)\) (high rate). Now observe &lt;strong&gt;\(k = 1\) head in \(n = 1\) flip&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute each component’s marginal likelihood \(P(y=1\mid M_j) = \mathbb{E}_j[\theta]\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Component 1: \(P(y=1\mid M_1) = \frac{2}{10} = \mathbf{0.20}\).&lt;/li&gt;
      &lt;li&gt;Component 2: \(P(y=1\mid M_2) = \frac{8}{10} = \mathbf{0.80}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Update the mixture weights via Bayes’ rule:&lt;/strong&gt;
\(w_1&apos; = \frac{0.5(0.20)}{0.5(0.20)+0.5(0.80)} = \mathbf{0.20}, \qquad w_2&apos; = \frac{0.5(0.80)}{0.50} = \mathbf{0.80}!\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Updated mixture posterior:&lt;/strong&gt; \(0.20\,\mathrm{Beta}(3, 8) + 0.80\,\mathrm{Beta}(9, 2)\), with overall posterior mean \(0.20\!\left(\frac{3}{11}\right) + 0.80\!\left(\frac{9}{11}\right) = \frac{7.8}{11} \approx \mathbf{0.709}\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-three-lab-6-insights-on-mixture-priors&quot;&gt;Explanation: Three Lab 6 Insights on Mixture Priors&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Updating mixture weights IS Bayesian model averaging in miniature:&lt;/strong&gt; The data automatically shifts weight toward whichever prior component predicted the data better!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always plot the full posterior density for mixture models:&lt;/strong&gt; A bimodal posterior can have a &lt;em&gt;disconnected&lt;/em&gt; 95% HDI (two separate intervals)—a single ETI bridges right across the empty valley!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute marginal likelihoods in log space (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;betaln&lt;/code&gt;) for larger \(n\):&lt;/strong&gt; Use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log_ml = betaln(a+k, b+n-k) - betaln(a, b)&lt;/code&gt; to avoid underflow when updating mixture weights!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the 50–50 mixture example above, if the single flip had landed &lt;strong&gt;Tails (\(y = 0\))&lt;/strong&gt; instead of Heads, what would the updated mixture weights \((w_1&apos;, w_2&apos;)\) be?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=brt2J5VgAHs&quot;&gt;Bayesian Statistics: What Are Priors?&lt;/a&gt; — Academia Elevated, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the prior as a component of the model before any data; the video stops at single-component priors, so the lab’s mixture-prior part you still have to work out yourself.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kkhdIriddSI&quot;&gt;(ML 6.1) Maximum a posteriori (MAP) estimation&lt;/a&gt; — mathematicalmonk, English. Watch MAP as a point estimate drawn from the posterior; it supports the point-estimation half of the lab.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aPNrhR0dFi8&quot;&gt;What is a conjugate prior?&lt;/a&gt; — Ben Lambert, English. Watch conjugacy break when the prior is no longer in the same family as the likelihood; use it as a warning when the lab moves to mixture priors.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 12.5: Lab 5: Point Estimation, Normal Conjugacy, and Bayesian Credible Intervals</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/en/chapter12/lab-05/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/en/chapter12/12_05_lab_05</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  This page is auto-generated from the notebooks in &lt;code&gt;labs/&lt;/code&gt; and &lt;code&gt;labs/solutions/&lt;/code&gt;.
  When the notebook files change, rerun &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; to update Chapter 12.
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lab assignment&lt;/h2&gt;
  &lt;p&gt;You can read the notebook directly on the web, open the standalone HTML file, or download the original &lt;code&gt;.ipynb&lt;/code&gt; file to work locally.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-05.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 5 as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%205.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 5 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-05.html&quot; title=&quot;Lab 5 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Solution&lt;/h2&gt;
  &lt;p&gt;The solution is placed on the same page so you can compare the workflow, the answers, and the code after you have finished the lab on your own.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-05-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 5 Solution as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_05_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 5 Solution .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-05-solution.html&quot; title=&quot;Lab 5 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;p&gt;Once you have a continuous posterior distribution in Python, how do you summarize it cleanly for a report or decision? &lt;strong&gt;Lab 5&lt;/strong&gt; puts three core skills under your fingertips: &lt;strong&gt;Normal–Normal conjugate updating&lt;/strong&gt; (precision addition), comparing &lt;strong&gt;posterior mean, median, and MAP mode&lt;/strong&gt; under different loss functions, and computing &lt;strong&gt;Equal-Tailed (ETI) vs. Highest Density (HDI) credible intervals&lt;/strong&gt;!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-core-lab-5-skills--normal-conjugacy--credible-intervals&quot;&gt;Key ideas: Core Lab 5 Skills — Normal Conjugacy &amp;amp; Credible Intervals&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Normal–Normal Precision Updating:&lt;/strong&gt; Updating \(\tau_{\text{post}} = \tau_0 + n/\sigma^2\) and \(\mu_{\text{post}} = (\tau_0\mu_0 + (n/\sigma^2)\bar{y})/\tau_{\text{post}}\) in closed form.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Point Summary Trio (Mean, Median, MAP):&lt;/strong&gt; Matching squared loss (mean), absolute loss (median), and 0–1 loss (mode)—identical on symmetric Normal posteriors, distinct on skewed posteriors!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ETI vs. HDI Computation:&lt;/strong&gt; Extracting exact symmetric intervals with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;norm.ppf&lt;/code&gt; and computing narrowest HDI intervals on arbitrary posterior sample arrays (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;az.hdi&lt;/code&gt;).&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-hand-checking-normalnormal-update--95-credible-interval&quot;&gt;Worked Numerical Example: Hand-Checking Normal–Normal Update &amp;amp; 95% Credible Interval&lt;/h3&gt;

&lt;p&gt;Prior: \(\mu \sim \mathcal{N}(100,\; 10^2)\) (\(\tau_0 = 0.01\)). Observe \(n = 9\) measurements with known \(\sigma = 15\) (\(\sigma^2 = 225\)) and sample mean \(\bar{y} = 112\):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Data precision:&lt;/strong&gt; \(\tau_{\text{data}} = \frac{9}{225} = \mathbf{0.04}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior precision &amp;amp; SD:&lt;/strong&gt; \(\tau_{\text{post}} = 0.01 + 0.04 = \mathbf{0.05} \implies \sigma_{\text{post}} = \sqrt{20} \approx \mathbf{4.472}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior mean:&lt;/strong&gt; \(\mu_{\text{post}} = \frac{0.01(100) + 0.04(112)}{0.05} = \frac{1.0 + 4.48}{0.05} = \mathbf{109.60}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;95% Credible Interval (ETI = HDI here!):&lt;/strong&gt; \(109.60 \pm 1.96(4.472) = \mathbf{[100.83,\; 118.37]}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-three-lab-5-best-practices&quot;&gt;Explanation: Three Lab 5 Best Practices&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check \(\sigma_{\text{post}} &amp;lt; \min(\sigma_0,\; \sigma/\sqrt{n})\):&lt;/strong&gt; Adding data must strictly reduce posterior uncertainty in a Normal–Normal model.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Test HDI vs. ETI on a skewed distribution (e.g., \(\mathrm{Beta}(2, 10)\)):&lt;/strong&gt; Confirm that HDI is strictly narrower than ETI whenever the posterior is asymmetric.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never confuse &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale&lt;/code&gt; (SD \(\sigma\)) with variance \(\sigma^2\) in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats.norm&lt;/code&gt;:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;norm(loc=109.6, scale=4.472)&lt;/code&gt; takes SD, &lt;em&gt;not&lt;/em&gt; variance &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;20&lt;/code&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the Normal–Normal lab example above, why are the posterior mean, median, and MAP mode all identically equal to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;109.60&lt;/code&gt;?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YPceDssQFWo&quot;&gt;Bayesian Statistics: Credible vs Confidence Intervals&lt;/a&gt; — Academia Elevated, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch how a Bayesian credible interval differs from a frequentist confidence interval, exactly the part of the lab that reports a posterior interval.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=MUhsT0U_nxY&quot;&gt;31 - Normal prior conjugate to normal likelihood - proof 1&lt;/a&gt; — Ox educ, English. Watch a Normal prior conjugate to a Normal likelihood; it supports the lab’s normal-conjugacy section.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kkhdIriddSI&quot;&gt;(ML 6.1) Maximum a posteriori (MAP) estimation&lt;/a&gt; — mathematicalmonk, English. Watch MAP estimation as a point taken from the posterior; use it for the point-estimation part, which does not replace the whole distribution.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 12.4: Lab 4: Conjugate Models and Bayesian Updating</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/en/chapter12/lab-04/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/en/chapter12/12_04_lab_04</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  This page is auto-generated from the notebooks in &lt;code&gt;labs/&lt;/code&gt; and &lt;code&gt;labs/solutions/&lt;/code&gt;.
  When the notebook files change, rerun &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; to update Chapter 12.
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lab assignment&lt;/h2&gt;
  &lt;p&gt;You can read the notebook directly on the web, open the standalone HTML file, or download the original &lt;code&gt;.ipynb&lt;/code&gt; file to work locally.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-04.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 4 as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%204.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 4 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-04.html&quot; title=&quot;Lab 4 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Solution&lt;/h2&gt;
  &lt;p&gt;The solution is placed on the same page so you can compare the workflow, the answers, and the code after you have finished the lab on your own.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-04-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 4 Solution as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_04_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 4 Solution .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-04-solution.html&quot; title=&quot;Lab 4 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;p&gt;In Lab 3 you computed posteriors numerically on a grid; in &lt;strong&gt;Lab 4&lt;/strong&gt;, you verify that &lt;strong&gt;conjugate priors&lt;/strong&gt; (Beta–Binomial and Gamma–Poisson) produce the &lt;em&gt;exact same&lt;/em&gt; posterior curves in &lt;strong&gt;one closed-form line of arithmetic&lt;/strong&gt;—giving you a rock-solid analytical benchmark to validate every numerical approximation you build later!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-core-lab-4-skills--exact-conjugate-updating-in-python&quot;&gt;Key ideas: Core Lab 4 Skills — Exact Conjugate Updating in Python&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Beta–Binomial Updating (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats.beta&lt;/code&gt;):&lt;/strong&gt; Mapping &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(alpha_0, beta_0)&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(k, n)&lt;/code&gt; directly to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;beta(alpha_0 + k, beta_0 + n - k)&lt;/code&gt; and reading exact mean, variance, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.ppf([0.025, 0.975])&lt;/code&gt; credible intervals.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gamma–Poisson Updating (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats.gamma&lt;/code&gt;):&lt;/strong&gt; Watching the crucial &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy&lt;/code&gt; parameterization rule: Bayesian &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Gamma(shape=alpha, rate=beta)&lt;/code&gt; equals &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats.gamma(a=alpha, scale=1/beta)&lt;/code&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prior Sensitivity &amp;amp; Data-Dominance Plots:&lt;/strong&gt; Plotting prior, normalized likelihood, and posterior on the exact same axes for \(n = 5, 20, 200\) to visualize data overwhelming the prior.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-exact-parity-check-between-grid-and-conjugate-betabinomial&quot;&gt;Worked Numerical Example: Exact Parity Check Between Grid and Conjugate Beta–Binomial&lt;/h3&gt;

&lt;p&gt;Start with prior \(\mathrm{Beta}(3, 7)\) (mean \(0.30\)) and observe \(k = 12\) successes in \(n = 20\) trials (\(8\) failures):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Exact conjugate posterior:&lt;/strong&gt; \(\mathrm{Beta}(3 + 12,\; 7 + 8) = \mathbf{\mathrm{Beta}(15,\; 15)}\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exact posterior mean:&lt;/strong&gt; \(\frac{15}{30} = \mathbf{0.500}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exact posterior SD:&lt;/strong&gt; \(\sqrt{\frac{15\times 15}{30^2 \times 31}} = \sqrt{\frac{1}{124}} \approx \mathbf{0.0898}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lab check:&lt;/strong&gt; Your 1,001-point grid posterior mean from Lab 3 should match &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.5000&lt;/code&gt; to at least 4 decimal places!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-three-lab-4-checks-that-prevent-classic-bugs&quot;&gt;Explanation: Three Lab 4 Checks That Prevent Classic Bugs&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Double-check &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale = 1 / rate&lt;/code&gt; in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats.gamma&lt;/code&gt;:&lt;/strong&gt; Test &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gamma(a=10, scale=1/2).mean() == 5.0&lt;/code&gt; immediately—forgetting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1/&lt;/code&gt; turns a mean of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt; into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;20&lt;/code&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Plot prior, likelihood, and posterior together:&lt;/strong&gt; Visually confirming that the posterior sits &lt;em&gt;between&lt;/em&gt; the prior peak and the data peak catches parameter swaps instantly.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare exact &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.ppf&lt;/code&gt; quantiles against Monte Carlo quantiles:&lt;/strong&gt; Verifying that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;beta(15, 15).ppf([0.025, 0.975])&lt;/code&gt; matches &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.quantile(samples, [0.025, 0.975])&lt;/code&gt; proves your sampling pipeline is bug-free.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats.gamma&lt;/code&gt;, if your Bayesian Gamma–Poisson posterior is \(\mathrm{Gamma}(\text{shape}=18,\; \text{rate}=6)\), what values should you pass to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale&lt;/code&gt;?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aPNrhR0dFi8&quot;&gt;What is a conjugate prior?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch what a conjugate prior is, exactly what the lab needs to update without computing a new integral.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=hKYvZF9wXkk&quot;&gt;20 - Beta conjugate prior to Binomial and Bernoulli likelihoods&lt;/a&gt; — Ox educ, English. Watch Beta–Binomial add successes and failures to the parameters; it supports the lab’s main conjugate pair.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=GqSX-8AQL90&quot;&gt;Bayesian Updates and Conjugate Priors&lt;/a&gt; — Steve Brunton, English. Watch several conjugate pairs updated in sequence; use it when the lab switches distribution family but keeps the same scheme.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 12.3: Lab 3: Bayesian Analysis and Continuous Distributions</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/en/chapter12/lab-03/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/en/chapter12/12_03_lab_03</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  This page is auto-generated from the notebooks in &lt;code&gt;labs/&lt;/code&gt; and &lt;code&gt;labs/solutions/&lt;/code&gt;.
  When the notebook files change, rerun &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; to update Chapter 12.
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lab assignment&lt;/h2&gt;
  &lt;p&gt;You can read the notebook directly on the web, open the standalone HTML file, or download the original &lt;code&gt;.ipynb&lt;/code&gt; file to work locally.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-03.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 3 as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%203.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 3 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-03.html&quot; title=&quot;Lab 3 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Solution&lt;/h2&gt;
  &lt;p&gt;The solution is placed on the same page so you can compare the workflow, the answers, and the code after you have finished the lab on your own.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-03-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 3 Solution as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_03_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 3 Solution .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-03-solution.html&quot; title=&quot;Lab 3 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;p&gt;Stepping from 3 discrete mystery coins to a &lt;strong&gt;continuous parameter \(\theta \in [0, 1]\)&lt;/strong&gt; introduces one crucial computational shift: sums become integrals, and PMFs become &lt;strong&gt;PDFs&lt;/strong&gt; whose height can exceed 1! &lt;strong&gt;Lab 3&lt;/strong&gt; teaches &lt;strong&gt;grid approximation&lt;/strong&gt; on continuous distributions in Python—turning any continuous prior \(\times\) likelihood into a visualizable posterior curve and extracting exact posterior means and credible intervals.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-core-lab-3-skills--continuous-grid-approximation&quot;&gt;Key ideas: Core Lab 3 Skills — Continuous Grid Approximation&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Discretizing a Continuous Domain:&lt;/strong&gt; Creating a fine grid &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;theta = np.linspace(0, 1, 1001)&lt;/code&gt; with step size \(\Delta\theta = 0.001\) turns \(\int p(\theta\mid y)\,d\theta\) into a simple Riemann sum!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Density vs. Discrete Grid Weights:&lt;/strong&gt; Normalizing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w = unnorm / unnorm.sum()&lt;/code&gt; gives discrete grid probabilities (summing to 1); dividing by \(\Delta\theta\) (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pdf = w / dtheta&lt;/code&gt;) recovers the true continuous &lt;strong&gt;PDF height&lt;/strong&gt; (integrating to 1)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sampling From the Grid Posterior:&lt;/strong&gt; Drawing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rng.choice(theta, size=10_000, p=w)&lt;/code&gt; lets you compute &lt;em&gt;any&lt;/em&gt; quantile, HDI, or nonlinear function of \(\theta\) with one line of NumPy!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-converting-grid-weights-to-continuous-pdf-height&quot;&gt;Worked Numerical Example: Converting Grid Weights to Continuous PDF Height&lt;/h3&gt;

&lt;p&gt;Suppose on a coarse grid &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;theta = [0.0, 0.25, 0.50, 0.75, 1.0]&lt;/code&gt; (step \(\Delta\theta = 0.25\)), normalized discrete grid weights are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w = [0.0, 0.10, 0.50, 0.40, 0.0]&lt;/code&gt; (summing to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.00&lt;/code&gt;):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Grid posterior mean:&lt;/strong&gt; \(0.25(0.10) + 0.50(0.50) + 0.75(0.40) = 0.025 + 0.250 + 0.300 = \mathbf{0.575}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Continuous PDF height at \(\theta = 0.50\):&lt;/strong&gt; \(\hat{f}(0.50) = \frac{w}{\Delta\theta} = \frac{0.50}{0.25} = \mathbf{2.0}\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check area:&lt;/strong&gt; \(\sum \hat{f}(\theta_i)\,\Delta\theta = (0 + 0.4 + 2.0 + 1.6 + 0)\times 0.25 = \mathbf{1.00}\)—exact!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-three-lab-3-pitfalls-to-avoid&quot;&gt;Explanation: Three Lab 3 Pitfalls to Avoid&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check whether you plotted &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w&lt;/code&gt; (depends on grid resolution!) vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w / dtheta&lt;/code&gt; (true PDF):&lt;/strong&gt; Doubling grid points from 100 to 200 halves every &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w&lt;/code&gt;, whereas &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w / dtheta&lt;/code&gt; stays invariant!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute in log-space on large datasets:&lt;/strong&gt; Replace &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prior * lik&lt;/code&gt; with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log_post = log_prior + log_lik; w = np.exp(log_post - logsumexp(log_post))&lt;/code&gt; so \(n = 500\) never underflows.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Remember the curse of dimensionality:&lt;/strong&gt; A 1,000-point grid works in 1D (\(10^3\) points) and 2D (\(10^6\) points), but explodes in 5D (\(10^{15}\) points)—which is why Chapter 4 introduces MCMC!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If you refine a 1D grid on \([0, 1]\) from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;101&lt;/code&gt; points (\(\Delta\theta = 0.01\)) to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1001&lt;/code&gt; points (\(\Delta\theta = 0.001\)), what happens to the peak value of the discrete weight &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w.max()&lt;/code&gt;, and what happens to the continuous PDF peak &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(w / dtheta).max()&lt;/code&gt;?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Why “probability of 0” does not mean “impossible”&lt;/td&gt;
          &lt;td&gt;Probabilities of probabilities, part 2](https://www.youtube.com/watch?v=ZA4JkHKZM50) — 3Blue1Brown, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch why a continuous density differs from the probability of a single point, exactly the foundation the lab needs when leaving discrete distributions.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=juF3r12nM5A&quot;&gt;The Beta distribution in 12 minutes!&lt;/a&gt; — Luis Serrano Academy, English. Watch the Beta distribution placed on an unknown probability; it supports the Bayesian inference part with continuous variables.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=rzFX5NWojp0&quot;&gt;The Normal Distribution, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch the parameters of the Normal distribution; use it when the lab works with bell-shaped continuous models.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 12.2: Lab 2: Simulation and Bayesian Updating</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/en/chapter12/lab-02/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/en/chapter12/12_02_lab_02</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  This page is auto-generated from the notebooks in &lt;code&gt;labs/&lt;/code&gt; and &lt;code&gt;labs/solutions/&lt;/code&gt;.
  When the notebook files change, rerun &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; to update Chapter 12.
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lab assignment&lt;/h2&gt;
  &lt;p&gt;You can read the notebook directly on the web, open the standalone HTML file, or download the original &lt;code&gt;.ipynb&lt;/code&gt; file to work locally.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-02.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 2 as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%202.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 2 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-02.html&quot; title=&quot;Lab 2 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Solution&lt;/h2&gt;
  &lt;p&gt;The solution is placed on the same page so you can compare the workflow, the answers, and the code after you have finished the lab on your own.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-02-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 2 Solution as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_02_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 2 Solution .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-02-solution.html&quot; title=&quot;Lab 2 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;p&gt;How do you prove to yourself that Bayes’ theorem actually works in the real world—and not just on a blackboard? You &lt;strong&gt;simulate 100,000 virtual worlds in Python&lt;/strong&gt;, filter down to the worlds that produced the exact data you observed, and count what fraction came from each hypothesis! &lt;strong&gt;Lab 2&lt;/strong&gt; pairs &lt;strong&gt;Monte Carlo simulation&lt;/strong&gt; with &lt;strong&gt;sequential Bayesian updating&lt;/strong&gt;, showing that simulated frequencies converge straight onto exact analytical Bayes’ rule.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-core-lab-2-skills--monte-carlo-simulation--sequential-updates&quot;&gt;Key ideas: Core Lab 2 Skills — Monte Carlo Simulation &amp;amp; Sequential Updates&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Forward Generative Simulation:&lt;/strong&gt; Drawing hidden states \(H^{(s)} \sim P(H)\) and then data \(D^{(s)} \sim P(D\mid H^{(s)})\) creates an empirical joint distribution without writing a single integral!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Rejection / Conditioning by Filtering:&lt;/strong&gt; Keeping only simulated worlds where \(D^{(s)} == d_{\text{obs}}\) directly approximates \(P(H \mid D = d_{\text{obs}})\)—the exact conceptual ancestor of Approximate Bayesian Computation (ABC)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sequential Updating Invariance:&lt;/strong&gt; Updating a posterior one observation at a time matches batch updating on all observations simultaneously.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-verifying-rejection-conditioning-against-exact-bayes&quot;&gt;Worked Numerical Example: Verifying Rejection Conditioning Against Exact Bayes&lt;/h3&gt;

&lt;p&gt;Using the Lab 1 fixture (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;P(H1)=0.2, P(E|H1)=0.9, P(E|H2)=0.3&lt;/code&gt;) across \(S = 10{,}000\) simulated worlds:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Expected worlds with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(H1, E)&lt;/code&gt;: \(10{,}000 \times 0.2 \times 0.9 = \mathbf{1{,}800}\).&lt;/li&gt;
  &lt;li&gt;Expected worlds with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(H2, E)&lt;/code&gt;: \(10{,}000 \times 0.8 \times 0.3 = \mathbf{2{,}400}\).&lt;/li&gt;
  &lt;li&gt;Filtering to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;E&lt;/code&gt; leaves \(\approx 4{,}200\) worlds, of which \(\frac{1{,}800}{4{,}200} = \mathbf{42.86\%}\) came from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;H1&lt;/code&gt;—matching exact Bayes (\(3/7\)) with Monte Carlo SE \(\sqrt{\frac{0.429 \times 0.571}{4200}} \approx 0.76\%\)!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-three-lab-2-verification-habits&quot;&gt;Explanation: Three Lab 2 Verification Habits&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Check the surviving sample count after filtering:&lt;/strong&gt; If only 15 simulated worlds match rare evidence &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;E&lt;/code&gt;, your Monte Carlo SE is \(\sim 13\%\)—increase \(S\) to 100,000+ or compute analytically!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Plot the running posterior trajectory after each new data point:&lt;/strong&gt; Watching the belief curve smoothly sharpen from observation 1 to observation 50 builds deep intuition for sequential learning.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify batch vs. sequential equality:&lt;/strong&gt; Assert that updating on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[1, 0, 1]&lt;/code&gt; one step at a time gives the exact same posterior as updating on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k=2, n=3&lt;/code&gt; at once.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the \(S = 10{,}000\) simulation above, why does filtering to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;E&lt;/code&gt; discard roughly \(58\%\) of all simulated worlds?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R1vcdhPBlXA&quot;&gt;Statistical Rethinking 2023 - 02 - The Garden of Forking Data&lt;/a&gt; — Richard McElreath, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch Bayesian updating done by generating and counting data samples, exactly the simulation lab for updating beliefs.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=7TqhmX92P6U&quot;&gt;What is Monte Carlo Simulation?&lt;/a&gt; — IBM Technology, English. Watch Monte Carlo generate many scenarios from one assumption; it supports the part of the lab that uses simulation instead of closed-form integrals.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Watch the prior multiplied by the likelihood and then normalized; use it as a map for the update loop in the lab.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 12.1: Lab 1: Conditional Probability and Bayes' Rule</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/en/chapter12/lab-01/"/>
   <updated>2026-03-14T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/en/chapter12/12_01_lab_01</id>
   <content type="html">&lt;!-- AUTO-GENERATED. DO NOT EDIT MANUALLY. --&gt;

&lt;div class=&quot;lab-generation-note&quot;&gt;
  This page is auto-generated from the notebooks in &lt;code&gt;labs/&lt;/code&gt; and &lt;code&gt;labs/solutions/&lt;/code&gt;.
  When the notebook files change, rerun &lt;code&gt;python scripts/generate_lab_chapter.py&lt;/code&gt; to update Chapter 12.
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Lab assignment&lt;/h2&gt;
  &lt;p&gt;You can read the notebook directly on the web, open the standalone HTML file, or download the original &lt;code&gt;.ipynb&lt;/code&gt; file to work locally.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-01.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 1 as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/Bayesian%20Inference%20-%20Lab%201.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 1 .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-01.html&quot; title=&quot;Lab 1 notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;div class=&quot;lab-section&quot;&gt;
  &lt;h2&gt;Solution&lt;/h2&gt;
  &lt;p&gt;The solution is placed on the same page so you can compare the workflow, the answers, and the code after you have finished the lab on your own.&lt;/p&gt;
  &lt;div class=&quot;lab-resource-links&quot;&gt;
  &lt;a href=&quot;/public/generated/labs/lab-01-solution.html&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Open Lab 1 Solution as HTML&lt;/a&gt;
  &lt;a href=&quot;/labs/solutions/Lab_01_Solutions.ipynb&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Download Lab 1 Solution .ipynb&lt;/a&gt;
&lt;/div&gt;
  &lt;iframe class=&quot;lab-notebook-frame&quot; src=&quot;/public/generated/labs/lab-01-solution.html&quot; title=&quot;Lab 1 solution notebook&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;p&gt;Reading Bayes’ theorem on slides makes it look deceptively easy—until you sit down in front of a blank Python cell and have to compute conditional probabilities from raw data, verify the Law of Total Probability, and avoid accidentally dividing by the wrong marginal! &lt;strong&gt;Lab 1&lt;/strong&gt; turns Chapter 1’s conditional probability and Bayes’ rule into hands-on code you can inspect, test, and verify by hand.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-core-lab-1-skills--tables-conditioning-and-bayes-rule&quot;&gt;Key ideas: Core Lab 1 Skills — Tables, Conditioning, and Bayes’ Rule&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Frequency Tables to Joint Probabilities:&lt;/strong&gt; Turning raw contingency counts into a normalized joint matrix \(P(A, B)\) where every entry is non-negative and the whole table sums to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.0&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Marginalization (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;axis=0&lt;/code&gt; vs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;axis=1&lt;/code&gt;):&lt;/strong&gt; Summing across rows vs. columns in NumPy/Pandas to extract \(P(A)\) and \(P(B)\) accurately.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayes’ Rule Verification in Code:&lt;/strong&gt; Computing \(P(H\mid E) = \frac{P(E\mid H)P(H)}{\sum_i P(E\mid H_i)P(H_i)}\) and verifying it matches direct slicing of the joint table to machine precision!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-hand-checking-lab-1s-bayes-function-on-a-2-hypothesis-test-case&quot;&gt;Worked Numerical Example: Hand-Checking Lab 1’s Bayes Function on a 2-Hypothesis Test Case&lt;/h3&gt;

&lt;p&gt;Before running your Lab 1 notebook on real data, verify your Python helper against this exact 2-hypothesis fixture (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prior = [0.2, 0.8]&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;likelihood = [0.9, 0.3]&lt;/code&gt;):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Unnormalized products: \(0.2 \times 0.9 = \mathbf{0.18}\) and \(0.8 \times 0.3 = \mathbf{0.24}\).&lt;/li&gt;
  &lt;li&gt;Total evidence: \(P(E) = 0.18 + 0.24 = \mathbf{0.42}\).&lt;/li&gt;
  &lt;li&gt;Exact posterior: \(P(H_1\mid E) = \frac{0.18}{0.42} = \frac{3}{7} \approx \mathbf{0.4286}\), \(P(H_2\mid E) = \frac{0.24}{0.42} = \frac{4}{7} \approx \mathbf{0.5714}\).
Assert &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.isclose(post.sum(), 1.0)&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.isclose(post[0], 3/7)&lt;/code&gt; right inside your lab notebook!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-three-lab-1-debugging-habits&quot;&gt;Explanation: Three Lab 1 Debugging Habits&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always assert normalization (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sum == 1.0&lt;/code&gt;) after every Bayes update:&lt;/strong&gt; A forgotten denominator shows up immediately.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Test extreme edge cases (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prior = [0, 1]&lt;/code&gt; or equal likelihoods):&lt;/strong&gt; If all hypotheses have identical likelihoods, your posterior must equal your prior verbatim!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;P(A|B)&lt;/code&gt; vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;P(B|A)&lt;/code&gt; labels carefully:&lt;/strong&gt; Print the row/column axis names whenever slicing a contingency table.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the 2-hypothesis fixture above, if both likelihoods were equal (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0.5, 0.5]&lt;/code&gt;), what must the posterior vector equal?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Bài 2. Công Thức Xác Suất Toàn Phần. Công Thức Bayes (Full Dạng) - Toán 12 (Sgk Mới)&lt;/td&gt;
          &lt;td&gt; &lt;/td&gt;
          &lt;td&gt;Thầy Tiến](https://www.youtube.com/watch?v=n7bUihWfW4w) — Thầy Nguyễn Phan Tiến, Vietnamese. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the types of conditional-probability and Bayes-formula problems, exactly the two calculations this lab asks you to do by hand.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=_IgyaD7vOOA&quot;&gt;Conditional Probabilities, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch conditional probability read off a concrete scenario; it supports the interpretation step before plugging in numbers.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Watch the picture of Bayes’ rule; use it when the lab asks you to update a belief rather than output a single ratio.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 11.4: Học sâu Bayes & Lượng hóa Bất định (BNN, MC Dropout, Deep Ensembles)</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter11/11_04_bayesian_deep_learning/"/>
   <updated>2025-01-11T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter11/11_04_bayesian_deep_learning</id>
   <content type="html">&lt;p&gt;Một mạng nơ-ron chuẩn được huấn luyện trên ảnh chó và mèo đôi khi vẫn tự tin &lt;strong&gt;99.8% là “mèo”&lt;/strong&gt; khi gặp một bức ảnh hoàn toàn xa lạ như chiếc xe tăng hay nhiễu trắng! Nguyên nhân là mạng nơ-ron thông thường chỉ tìm một điểm ước lượng trọng số (MAP/MLE) mà bỏ qua toàn bộ độ bất định của tham số. &lt;strong&gt;Học sâu Bayes (Bayesian Deep Learning — BDL)&lt;/strong&gt; đưa tư duy phân phối hậu nghiệm lên trọng số mạng nơ-ron để mô hình biết khi nào cần nói &lt;strong&gt;“Tôi không chắc chắn”&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-học-sâu-bayes-phân-tách-aleatoric--epistemic&quot;&gt;Video ngắn: Học sâu Bayes: Phân tách Aleatoric &amp;amp; Epistemic&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/bdl-epistemic-aleatoric.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 31 giây (có thuyết minh tiếng Việt): 5 mạng nơ-ron Ensemble/MC Dropout khớp khít trên vùng dữ liệu nhưng tách tỏa mạnh ở khoảng trống, làm bất định Epistemic tăng vọt.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Phân biệt hai loại bất định cốt lõi trong học máy: &lt;strong&gt;Bất định Ngẫu nhiên (Aleatoric Uncertainty)&lt;/strong&gt; và &lt;strong&gt;Bất định Nhận thức (Epistemic Uncertainty)&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Hiểu cách mạng nơ-ron Bayes (BNN) đặt prior \(p(\mathbf{W})\) lên trọng số (và mối liên hệ trực tiếp với &lt;strong&gt;Weight Decay / L2 Regularization&lt;/strong&gt;).&lt;/li&gt;
  &lt;li&gt;Nắm ba phương pháp thực tế dễ triển khai trong công nghiệp: &lt;strong&gt;Laplace Approximation&lt;/strong&gt;, &lt;strong&gt;Monte Carlo Dropout&lt;/strong&gt;, và &lt;strong&gt;Deep Ensembles&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hai-nguồn-bất-định-và-ba-công-cụ-thực-chiến&quot;&gt;Kiến thức cần nhớ: Hai nguồn Bất định và Ba công cụ Thực chiến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Aleatoric vs. Epistemic Uncertainty:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;em&gt;Aleatoric (nhiễu dữ liệu vốn có):&lt;/em&gt; Không giảm đi dù có thêm dữ liệu (ví dụ cảm biến mờ, nhãn trùng lặp).&lt;/li&gt;
      &lt;li&gt;&lt;em&gt;Epistemic (thiếu dữ liệu / thiếu hiểu biết mô hình):&lt;/em&gt; Cao vọt ở vùng ngoài phân phối huấn luyện (&lt;em&gt;Out-of-Distribution — OOD&lt;/em&gt;) và thu hẹp khi thu thập thêm dữ liệu ở vùng đó!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dự báo hậu nghiệm trong BNN:&lt;/strong&gt;
\(p(y_* \mid x_*, D) = \int p(y_* \mid x_*, \mathbf{W})\,p(\mathbf{W} \mid D)\,d\mathbf{W} \approx \frac{1}{M}\sum_{m=1}^{M} p(y_* \mid x_*, \mathbf{W}^{(m)}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ba xấp xỉ thực tế thay cho MCMC toàn mạng:&lt;/strong&gt;
    &lt;ol&gt;
      &lt;li&gt;&lt;strong&gt;MC Dropout (Gal &amp;amp; Ghahramani, 2016):&lt;/strong&gt; Giữ nguyên tầng Dropout &lt;strong&gt;bật ngay cả lúc suy luận (inference)&lt;/strong&gt;, chạy \(M = 30\text{–}50\) lần forward pass rồi lấy trung bình và phương sai — tương đương xấp xỉ biến phân!&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Deep Ensembles (Lakshminarayanan et al., 2017):&lt;/strong&gt; Huấn luyện \(M = 5\text{–}10\) mạng độc lập từ các hạt giống khởi tạo ngẫu nhiên khác nhau để khám phá nhiều đỉnh hậu nghiệm khác nhau (đa đỉnh).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Last-Layer Laplace:&lt;/strong&gt; Chỉ áp dụng xấp xỉ Laplace (Bài 3.2) lên tầng tuyến tính cuối cùng — cực nhanh và hiệu chỉnh xác suất rất tốt.&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter11/bdl_uncertainty.png&quot; alt=&quot;Phân tách Bất định Aleatoric và Epistemic trong Học sâu Bayes&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 11.4. Trong vùng có dữ liệu huấn luyện, bất định nhỏ và chủ yếu là nhiễu aleatoric; ở khoảng trống \([-0.6, 0.6]\) và ngoài biên, bất định epistemic tự động tăng vọt cảnh báo mô hình đang ngoại suy.&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phân loại bất định:&lt;/strong&gt; Trong bài toán chẩn đoán X-quang phổi, hãy nêu một ví dụ cụ thể về &lt;em&gt;aleatoric uncertainty&lt;/em&gt; và một ví dụ về &lt;em&gt;epistemic uncertainty&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng phương sai (Law of Total Variance):&lt;/strong&gt; Với \(M\) lần chạy MC Dropout trả về cặp \((\mu_m(x), \sigma_m^2(x))\), viết công thức tách tổng phương sai dự báo thành phần aleatoric \(\frac{1}{M}\sum \sigma_m^2(x)\) và phần epistemic \(\operatorname{Var}_m(\mu_m(x))\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thực hành PyTorch/NumPy:&lt;/strong&gt; Huấn luyện một mạng MLP nhỏ có Dropout trên hàm \(y = \sin(x) + \epsilon\) trên đoạn \([-2, -0.5] \cup [0.5, 2]\), sau đó chạy 50 lần MC Dropout trên toàn đoạn \([-3, 3]\) và kiểm chứng dải bất định phình to tại khoảng trống giữa.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 11.3: Mạng Bayes (Bayesian Networks) & Lan truyền Niềm tin</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter11/11_03_bayesian_networks/"/>
   <updated>2025-01-11T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter11/11_03_bayesian_networks</id>
   <content type="html">&lt;p&gt;Một hệ thống chẩn đoán y khoa hay phát hiện lỗi phần cứng có 50 biến nhị phân. Bảng phân phối đồng thời đầy đủ cần tới \(2^{50} \approx 10^{15}\) xác suất — không máy tính nào lưu nổi! &lt;strong&gt;Mạng Bayes (Bayesian Networks)&lt;/strong&gt; giải quyết sự bùng nổ tổ hợp này bằng cách biểu diễn các &lt;strong&gt;tính độc lập có điều kiện&lt;/strong&gt; trên một &lt;strong&gt;đồ thị có hướng không chu trình (DAG)&lt;/strong&gt;, phân rã phân phối khổng lồ thành tích của các bảng xác suất có điều kiện (CPT) nhỏ gọn.&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-mạng-bayes--hiệu-ứng-explaining-away&quot;&gt;Video ngắn: Mạng Bayes &amp;amp; Hiệu ứng Explaining Away&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/bayesian-network-explaining-away.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 47 giây (có thuyết minh tiếng Việt): bật bằng chứng Cỏ ướt (W=1) khiến cả Vòi phun và Mưa cùng tăng, rồi bật thêm Mưa (R=1) làm xác suất Vòi phun tụt mạnh từ 43.0% xuống 19.4%.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Viết định lý phân rã phân phối đồng thời của một Mạng Bayes theo tập nút cha \(\operatorname{Pa}(X_i)\).&lt;/li&gt;
  &lt;li&gt;Nhận diện ba cấu trúc cơ bản trong DAG (&lt;strong&gt;Chuỗi — Chain&lt;/strong&gt;, &lt;strong&gt;Nhánh rẽ — Fork&lt;/strong&gt;, &lt;strong&gt;Hội tụ — Collider&lt;/strong&gt;) và hiểu hiện tượng &lt;strong&gt;Giải thích loại trừ (Explaining Away)&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Thực hiện tính tay suy luận chính xác (Variable Elimination / Bayes update) trên mạng kinh điển &lt;em&gt;Mây – Vòi phun – Mưa – Cỏ ướt&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-phân-rã-mạng-bayes-và-explaining-away&quot;&gt;Kiến thức cần nhớ: Phân rã Mạng Bayes và Explaining Away&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân rã phân phối đồng thời:&lt;/strong&gt; Với DAG gồm các biến \(X_1, \dots, X_n\):
\(P(X_1, \dots, X_n) = \prod_{i=1}^{n} P\!\left(X_i \mid \operatorname{Pa}(X_i)\right).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mạng Cỏ ướt (Sprinkler Network):&lt;/strong&gt;
\(P(C, S, R, W) = P(C)\,P(S \mid C)\,P(R \mid C)\,P(W \mid S, R).\)
Thay vì cần \(2^4 - 1 = 15\) tham số tự do, mạng chỉ cần \(1 + 2 + 2 + 4 = 9\) tham số!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiện tượng Explaining Away (tại nút Collider \(S \to W \leftarrow R\)):&lt;/strong&gt; Khi chưa nhìn thấy cỏ ướt (\(W\) chưa biết), vòi phun \(S\) và trời mưa \(R\) độc lập có điều kiện khi biết trời mây \(C\). Nhưng ngay khi quan sát thấy &lt;strong&gt;cỏ ướt (\(W = 1\))&lt;/strong&gt;, nếu biết thêm &lt;strong&gt;trời mưa (\(R = 1\))&lt;/strong&gt; thì xác suất vòi phun đã bật \(P(S = 1 \mid W = 1, R = 1)\) lập tức &lt;strong&gt;giảm mạnh&lt;/strong&gt; — vì trời mưa đã “giải thích thay” nguyên nhân làm ướt cỏ!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter11/bayesian_network_dag.png&quot; alt=&quot;Mạng Bayes kinh điển Mây - Vòi phun - Mưa - Cỏ ướt&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 11.3. Đồ thị Mạng Bayes 4 nút minh họa phân rã xác suất và hiện tượng “explaining away” khi quan sát nút hội tụ Wet Grass.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-ví-dụ-cầm-tay-chỉ-việc-suy-luận-ngược-trong-mạng-cỏ-ướt&quot;&gt;1. Ví dụ cầm tay chỉ việc: Suy luận ngược trong Mạng Cỏ ướt&lt;/h2&gt;

&lt;p&gt;Giả sử \(P(C=1)=0.5\); \(P(S=1 \mid C=1)=0.1,\ P(S=1 \mid C=0)=0.5\); \(P(R=1 \mid C=1)=0.8,\ P(R=1 \mid C=0)=0.2\); và \(P(W=1 \mid S, R)\) bằng \(0.99\) khi cả hai bật, \(0.90\) khi chỉ một trong hai bật, và \(0.00\) khi cả hai tắt.
Khi quan sát thấy cỏ ướt (\(W=1\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tính tổng xác suất \(P(W=1) = \sum_{c,s,r} P(c)P(s\mid c)P(r\mid c)P(W=1\mid s,r) \approx 0.6471\).&lt;/li&gt;
  &lt;li&gt;Xác suất trời mưa là \(P(R=1 \mid W=1) \approx 70.8\%\) và xác suất vòi phun bật là \(P(S=1 \mid W=1) \approx 43.0\%\).&lt;/li&gt;
  &lt;li&gt;Nếu bước ra cửa thấy &lt;strong&gt;trời đang mưa (\(R=1\))&lt;/strong&gt;, xác suất vòi phun bật lập tức tụt từ \(43.0\%\) xuống chỉ còn \(P(S=1 \mid W=1, R=1) \approx 19.4\%\)!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;thực-hành-tương-tác-bậttắt-bằng-chứng--quan-sát-explaining-away&quot;&gt;Thực hành tương tác: Bật/tắt Bằng chứng &amp;amp; Quan sát Explaining Away&lt;/h3&gt;

&lt;div style=&quot;margin:1.5rem 0;&quot;&gt;
&lt;iframe src=&quot;/public/interactive/bayesian_network_lab.html&quot; style=&quot;width:100%;height:560px;border:1px solid #ddd;border-radius:10px;background:#fff;&quot; loading=&quot;lazy&quot; title=&quot;Bayesian Network Interactive Lab&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đếm số tham số tiết kiệm được:&lt;/strong&gt; Một Mạng Bayes dạng chuỗi \(X_1 \to X_2 \to \dots \to X_{10}\) gồm 10 biến nhị phân cần bao nhiêu tham số độc lập so với phân phối đồng thời đầy đủ (\(2^{10} - 1\))?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra d-separation:&lt;/strong&gt; Trong mạng Hình 11.3, \(S\) và \(R\) có độc lập có điều kiện khi chỉ biết \(C\) không? Còn khi biết cả \(C\) và \(W\) thì sao?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lập trình suy luận chính xác:&lt;/strong&gt; Viết hàm Python tính \(P(R=1 \mid W=1, S=1)\) cho bảng CPT ở ví dụ trên và so sánh với \(P(R=1 \mid W=1)\).&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 11.2: Tối ưu hóa Bayes (Bayesian Optimization) & Hàm Thu nhận</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter11/11_02_bayesian_optimization/"/>
   <updated>2025-01-11T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter11/11_02_bayesian_optimization</id>
   <content type="html">&lt;p&gt;Giả sử bạn cần tìm tổ hợp siêu tham số tối ưu cho một mô hình học sâu hoặc công thức pha chế vật liệu mới, trong đó &lt;strong&gt;mỗi lần thử tốn 4 tiếng GPU hoặc hàng nghìn đô la thí nghiệm&lt;/strong&gt; và bạn &lt;strong&gt;không hề có đạo hàm&lt;/strong&gt; của hàm mục tiêu \(f(x)\). Grid search hay Random search quá lãng phí. &lt;strong&gt;Tối ưu hóa Bayes (Bayesian Optimization)&lt;/strong&gt; giải bài toán hộp đen tốn kém này bằng cách ghép &lt;strong&gt;Mô hình thay thế (Surrogate Model — thường là GP)&lt;/strong&gt; với &lt;strong&gt;Hàm thu nhận (Acquisition Function)&lt;/strong&gt; để quyết định điểm thử tiếp theo thông minh nhất!&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-tối-ưu-hóa-bayes-với-mô-hình-gp--hàm-ucb&quot;&gt;Video ngắn: Tối ưu hóa Bayes với Mô hình GP &amp;amp; Hàm UCB&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/bayesian-optimization-ucb.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 26 giây (có thuyết minh tiếng Việt): vòng lặp Bayesian Optimization dùng GP thay thế và cực đại hàm thu nhận UCB để khóa trúng cực đại toàn cục chỉ sau 6 lần đánh giá.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Hiểu kiến trúc vòng lặp 2 thành phần của Bayesian Optimization: &lt;strong&gt;GP Surrogate&lt;/strong&gt; + &lt;strong&gt;Acquisition Function&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Phân biệt hai hàm thu nhận phổ biến nhất: &lt;strong&gt;Upper Confidence Bound (UCB)&lt;/strong&gt; và &lt;strong&gt;Expected Improvement (EI)&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Giải thích cách hàm thu nhận cân bằng giữa &lt;strong&gt;khai thác vùng có trung bình cao&lt;/strong&gt; và &lt;strong&gt;khám phá vùng có bất định lớn&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-surrogate-model-và-acquisition-function&quot;&gt;Kiến thức cần nhớ: Surrogate Model và Acquisition Function&lt;/h2&gt;

&lt;p&gt;Sau \(t\) lần đánh giá \(\{(x_i, y_i)\}_{i=1}^t\), GP cho ta trung bình hậu nghiệm \(\mu_t(x)\) và độ lệch chuẩn \(\sigma_t(x)\) tại mọi điểm ứng viên \(x\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Upper Confidence Bound (UCB):&lt;/strong&gt;
\(\operatorname{UCB}(x) = \mu_t(x) + \kappa\,\sigma_t(x).\)
Tham số \(\kappa &amp;gt; 0\) (ví dụ \(\kappa = 2\)) điều chỉnh độ “tò mò”: \(\kappa\) nhỏ thiên về khai thác đỉnh đã biết, \(\kappa\) lớn ưu tiên khám phá vùng trống.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Expected Improvement (EI):&lt;/strong&gt; Đo kỳ vọng mức cải thiện vượt qua giá trị tốt nhất hiện có \(f^+ = \max_{i \le t} y_i\):
\(\operatorname{EI}(x) = \mathbb{E}\!\left[\max(f(x) - f^+,\ 0)\right] = (\mu_t(x) - f^+)\Phi(Z) + \sigma_t(x)\phi(Z), \quad Z = \frac{\mu_t(x) - f^+}{\sigma_t(x)}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chọn điểm thử tiếp theo:&lt;/strong&gt; \(x_{t+1} = \arg\max_x \alpha_t(x)\), đánh giá hàm hộp đen \(y_{t+1} = f(x_{t+1})\), cập nhật GP và lặp lại!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter11/bayesian_optimization_ucb.png&quot; alt=&quot;Tối ưu hóa Bayes với mô hình thay thế GP và hàm thu nhận UCB&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 11.2. Trên: hàm mục tiêu ẩn (nét chấm), mô hình GP thay thế (xanh) và 4 điểm đã thử (đỏ). Dưới: hàm thu nhận UCB đạt cực đại tại \(x^*\) — điểm kết hợp cả kỳ vọng cao lẫn độ bất định lớn.&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính tay UCB và EI:&lt;/strong&gt; Tại một vòng lặp với \(f^+ = 1.2\), điểm \(A\) có \((\mu_A = 1.15, \sigma_A = 0.05)\) và điểm \(B\) có \((\mu_B = 1.00, \sigma_B = 0.30)\). Điểm nào được chọn theo \(\operatorname{UCB}\) với \(\kappa = 2\)?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khi nào KHÔNG nên dùng Bayesian Optimization?&lt;/strong&gt; Nêu 2 tình huống thực tế (ví dụ hàm đánh giá cực rẻ, hoặc không gian 500 chiều) khiến Bayesian Optimization chuẩn kém hiệu quả hơn tối ưu gradient hoặc tìm kiếm ngẫu nhiên.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt 20 dòng Python:&lt;/strong&gt; Viết vòng lặp Bayesian Optimization 1D tìm cực đại của \(f(x) = \sin(1.2x) + 0.4\cos(2.5x)\) trên \([0, 6]\) dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy&lt;/code&gt; / NumPy và ghi nhận số bước cần để đạt sai số dưới \(0.02\).&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 11.1: Thử nghiệm A/B Bayes & Thompson Sampling (Multi-Armed Bandits)</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter11/11_01_bayesian_ab_thompson/"/>
   <updated>2025-01-11T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter11/11_01_bayesian_ab_thompson</id>
   <content type="html">&lt;p&gt;Trong thử nghiệm A/B truyền thống (frequentist), bạn phải khóa cố định cỡ mẫu từ đầu, cấm “nhìn trộm” kết quả giữa chừng (nếu không sẽ làm phồng sai lầm loại I), và chịu cảnh chia đều 50% lưu lượng vào phiên bản kém hơn suốt nhiều tuần. &lt;strong&gt;Thử nghiệm A/B Bayes&lt;/strong&gt; và thuật toán &lt;strong&gt;Thompson Sampling&lt;/strong&gt; giải phóng bạn khỏi cả hai xiềng xích đó: vừa cho biết trực tiếp &lt;em&gt;xác suất B tốt hơn A&lt;/em&gt; cùng &lt;em&gt;tổn thất kỳ vọng nếu chọn nhầm&lt;/em&gt;, vừa tự động dồn lưu lượng sang phương án thắng cuộc theo thời gian thực!&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-thompson-sampling-trên-multi-armed-bandit&quot;&gt;Video ngắn: Thompson Sampling trên Multi-Armed Bandit&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/thompson-sampling-bandit.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video minh họa sống động 3 nhánh A, B, C cạnh tranh bằng phân phối Beta: ở mỗi lượt, hệ thống rút mẫu ngẫu nhiên \(\tilde{\theta}_k\) từ từng đường cong, kéo nhánh có mẫu cao nhất, nhận thưởng/thất bại và lập tức cập nhật hình dạng đường cong hậu nghiệm theo thời gian thực.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Tính trực tiếp &lt;strong&gt;Xác suất thắng&lt;/strong&gt; \(P(\theta_B &amp;gt; \theta_A \mid D)\) và &lt;strong&gt;Tổn thất kỳ vọng (Expected Loss)&lt;/strong&gt; trong A/B Testing Bayes.&lt;/li&gt;
  &lt;li&gt;Hiểu cơ chế cân bằng &lt;strong&gt;Khám phá – Khai thác (Exploration vs. Exploitation)&lt;/strong&gt; cực kỳ thanh lịch của &lt;strong&gt;Thompson Sampling&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Cài đặt và chạy thử vòng lặp Thompson Sampling cho bài toán Multi-Armed Bandit nhiều phiên bản.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-quyết-định-ab-và-quy-tắc-thompson&quot;&gt;Kiến thức cần nhớ: Quyết định A/B và Quy tắc Thompson&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình Beta–Binomial cho từng biến thể \(k\):&lt;/strong&gt; Với prior \(\operatorname{Beta}(\alpha_0, \beta_0)\), sau \(s_k\) lượt chuyển đổi và \(f_k\) lượt không chuyển đổi, hậu nghiệm là \(\theta_k \mid D \sim \operatorname{Beta}(\alpha_0 + s_k,\ \beta_0 + f_k)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tiêu chí dừng theo Tổn thất kỳ vọng (Expected Loss):&lt;/strong&gt; Nếu ta quyết định chọn B, tổn thất kỳ vọng khi thực ra A tốt hơn B là:
\(\text{Expected Loss}(B) = \mathbb{E}\!\left[\max(\theta_A - \theta_B,\ 0) \mid D\right].\)
Khi \(\text{Expected Loss}(B) &amp;lt; \epsilon\) (ví dụ \(0.001\) — chấp nhận rủi ro tối đa 0.1% CTR), ta dừng thử nghiệm an toàn mà không sợ lỗi &lt;em&gt;peeking&lt;/em&gt; như p-value!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thuật toán Thompson Sampling (chỉ 3 dòng):&lt;/strong&gt; Ở mỗi lượt người dùng mới đến:
    &lt;ol&gt;
      &lt;li&gt;Với mỗi nhánh \(k\), rút một mẫu \(\tilde{\theta}_k \sim \operatorname{Beta}(\alpha_k, \beta_k)\).&lt;/li&gt;
      &lt;li&gt;Chọn nhánh \(k^* = \arg\max_k \tilde{\theta}_k\) để hiển thị.&lt;/li&gt;
      &lt;li&gt;Quan sát kết quả \(r \in \{0, 1\}\) và cập nhật: \(\alpha_{k^*} \leftarrow \alpha_{k^*} + r,\ \beta_{k^*} \leftarrow \beta_{k^*} + (1 - r)\).&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter11/thompson_sampling_ab.png&quot; alt=&quot;Phân phối hậu nghiệm Beta của 3 phiên bản sản phẩm trong Thompson Sampling&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 11.1. Ba biến thể A, B, C sau 100 lượt thử mỗi nhánh: Thompson Sampling tự động phân bổ phần lớn lưu lượng tương lai cho biến thể B (\(\text{CTR} \approx 18\%\)) trong khi vẫn dành xác suất nhỏ để kiểm tra A.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;thực-hành-tương-tác-mô-phỏng-multi-armed-bandit-với-thompson-sampling&quot;&gt;Thực hành tương tác: Mô phỏng Multi-Armed Bandit với Thompson Sampling&lt;/h3&gt;

&lt;div style=&quot;margin:1.5rem 0;&quot;&gt;
&lt;iframe src=&quot;/public/interactive/thompson_bandit_lab.html&quot; style=&quot;width:100%;height:560px;border:1px solid #ddd;border-radius:10px;background:#fff;&quot; loading=&quot;lazy&quot; title=&quot;Thompson Sampling Bandit Lab&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính xác suất thắng &amp;amp; tổn thất kỳ vọng:&lt;/strong&gt; Biết nhánh A có hậu nghiệm \(\operatorname{Beta}(12, 88)\) và nhánh B có hậu nghiệm \(\operatorname{Beta}(18, 82)\). Dùng 50.000 mẫu NumPy tính \(P(\theta_B &amp;gt; \theta_A \mid D)\) và \(\text{Expected Loss}(B)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tại sao Thompson Sampling tự giảm khám phá theo thời gian?&lt;/strong&gt; Giải thích dựa trên độ rộng phương sai của phân phối \(\operatorname{Beta}(\alpha_k, \beta_k)\) khi số lượt thử \(n_k\) tăng lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh Regret:&lt;/strong&gt; Mô phỏng 1.000 lượt cho 3 nhánh có tỷ lệ thực \((0.10, 0.18, 0.07)\); vẽ đường tổng hối tiếc tích lũy (cumulative regret) của A/B Test 50–50 so với Thompson Sampling.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 11.4: Bayesian Deep Learning & Uncertainty Quantification</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter11/11_04_bayesian_deep_learning/"/>
   <updated>2025-01-11T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter11/11_04_bayesian_deep_learning</id>
   <content type="html">&lt;p&gt;A standard neural network trained on cats and dogs can still output &lt;strong&gt;99.8% confidence for “cat”&lt;/strong&gt; when shown pure noise or an out-of-distribution image. &lt;strong&gt;Bayesian Deep Learning (BDL)&lt;/strong&gt; brings posterior uncertainty to neural network weights so models know when to say &lt;strong&gt;“I don’t know.”&lt;/strong&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Distinguish &lt;strong&gt;Aleatoric Uncertainty&lt;/strong&gt; (irreducible data noise) from &lt;strong&gt;Epistemic Uncertainty&lt;/strong&gt; (model/data ignorance).&lt;/li&gt;
  &lt;li&gt;Understand weight priors \(p(\mathbf{W})\) and their link to L2 weight decay.&lt;/li&gt;
  &lt;li&gt;Apply practical scalable approximations: &lt;strong&gt;MC Dropout&lt;/strong&gt;, &lt;strong&gt;Deep Ensembles&lt;/strong&gt;, and &lt;strong&gt;Last-Layer Laplace&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-two-uncertainties--scalable-approximations&quot;&gt;Key Ideas: Two Uncertainties &amp;amp; Scalable Approximations&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Predictive posterior:&lt;/strong&gt; \(p(y_* \mid x_*, D) \approx \frac{1}{M}\sum_{m=1}^M p(y_* \mid x_*, \mathbf{W}^{(m)})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;MC Dropout:&lt;/strong&gt; Keep dropout active at test time and average \(M\) stochastic forward passes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Deep Ensembles:&lt;/strong&gt; Train \(M = 5\text{–}10\) independently initialized networks to capture multimodal weight posteriors.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter11/bdl_uncertainty.png&quot; alt=&quot;Aleatoric vs Epistemic Uncertainty in BDL&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 11.4. Epistemic uncertainty surges inside the data gap \([-0.6, 0.6]\) and outside the training range.&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Uncertainty taxonomy:&lt;/strong&gt; Give one concrete example of aleatoric uncertainty and one of epistemic uncertainty in medical imaging.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Law of Total Variance:&lt;/strong&gt; Given \(M\) MC Dropout passes outputting \((\mu_m(x), \sigma_m^2(x))\), write the decomposition into aleatoric and epistemic variance.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;MC Dropout demo:&lt;/strong&gt; Train a small dropout MLP on \(y = \sin(x) + \epsilon\) over \([-2, -0.5] \cup [0.5, 2]\) and plot 50 stochastic predictions across \([-3, 3]\).&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 11.3: Bayesian Networks & Belief Propagation</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter11/11_03_bayesian_networks/"/>
   <updated>2025-01-11T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter11/11_03_bayesian_networks</id>
   <content type="html">&lt;p&gt;A medical diagnosis system with 50 binary variables would require \(2^{50} \approx 10^{15}\) entries in a raw joint probability table. &lt;strong&gt;Bayesian Networks&lt;/strong&gt; tame this combinatorial explosion by encoding &lt;strong&gt;conditional independence&lt;/strong&gt; in a &lt;strong&gt;Directed Acyclic Graph (DAG)&lt;/strong&gt;, factoring the joint distribution into compact Conditional Probability Tables (CPTs).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Factor a Bayesian Network’s joint distribution over parent sets \(\operatorname{Pa}(X_i)\).&lt;/li&gt;
  &lt;li&gt;Distinguish &lt;strong&gt;Chain&lt;/strong&gt;, &lt;strong&gt;Fork&lt;/strong&gt;, and &lt;strong&gt;Collider&lt;/strong&gt; structures and explain &lt;strong&gt;Explaining Away&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Perform exact inference on the classic &lt;em&gt;Cloudy–Sprinkler–Rain–Wet Grass&lt;/em&gt; network.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-factorization--explaining-away&quot;&gt;Key Ideas: Factorization &amp;amp; Explaining Away&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Chain rule for DAGs:&lt;/strong&gt; \(P(X_1, \dots, X_n) = \prod_{i=1}^n P(X_i \mid \operatorname{Pa}(X_i))\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Explaining away:&lt;/strong&gt; In the collider \(S \to W \leftarrow R\), observing Wet Grass (\(W=1\)) makes Sprinkler and Rain dependent; subsequently learning it rained (\(R=1\)) sharply drops \(P(S=1 \mid W=1, R=1)\) from \(43.0\%\) down to \(19.4\%\)!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter11/bayesian_network_dag.png&quot; alt=&quot;Classic Bayesian Network DAG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 11.3. Four-node Sprinkler Bayesian Network illustrating DAG factorization and explaining away.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;interactive-lab-toggle-evidence--watch-explaining-away&quot;&gt;Interactive Lab: Toggle Evidence &amp;amp; Watch Explaining Away&lt;/h3&gt;

&lt;div style=&quot;margin:1.5rem 0;&quot;&gt;
&lt;iframe src=&quot;/public/interactive/bayesian_network_lab.html&quot; style=&quot;width:100%;height:560px;border:1px solid #ddd;border-radius:10px;background:#fff;&quot; loading=&quot;lazy&quot; title=&quot;Bayesian Network Interactive Lab&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Parameter savings:&lt;/strong&gt; How many independent parameters does a 10-node binary chain \(X_1 \to \dots \to X_{10}\) require versus a full joint table (\(2^{10}-1\))?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;d-separation:&lt;/strong&gt; In Figure 11.3, are \(S\) and \(R\) conditionally independent given \(C\)? What about given both \(C\) and \(W\)?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exact inference:&lt;/strong&gt; Write a short Python function to compute \(P(R=1 \mid W=1, S=1)\) and compare it with \(P(R=1 \mid W=1)\).&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 11.2: Bayesian Optimization & Acquisition Functions</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter11/11_02_bayesian_optimization/"/>
   <updated>2025-01-11T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter11/11_02_bayesian_optimization</id>
   <content type="html">&lt;p&gt;When tuning deep-learning hyperparameters or designing physical experiments where &lt;strong&gt;each evaluation costs hours of compute or thousands of dollars&lt;/strong&gt; and gradients do not exist, grid search is hopeless. &lt;strong&gt;Bayesian Optimization&lt;/strong&gt; pairs a &lt;strong&gt;GP surrogate model&lt;/strong&gt; with an &lt;strong&gt;acquisition function&lt;/strong&gt; to pick the most informative next query at every step.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Understand the two-part Bayesian Optimization loop: &lt;strong&gt;GP Surrogate&lt;/strong&gt; + &lt;strong&gt;Acquisition Function&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Compare &lt;strong&gt;Upper Confidence Bound (UCB)&lt;/strong&gt; and &lt;strong&gt;Expected Improvement (EI)&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Explain how acquisition functions trade off high predicted mean (exploitation) against high uncertainty (exploration).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-ucb--expected-improvement&quot;&gt;Key Ideas: UCB &amp;amp; Expected Improvement&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;UCB:&lt;/strong&gt; \(\operatorname{UCB}(x) = \mu_t(x) + \kappa\,\sigma_t(x)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;EI:&lt;/strong&gt; \(\operatorname{EI}(x) = (\mu_t(x) - f^+)\Phi(Z) + \sigma_t(x)\phi(Z),\quad Z = \frac{\mu_t(x) - f^+}{\sigma_t(x)}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Next query:&lt;/strong&gt; \(x_{t+1} = \arg\max_x \alpha_t(x)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter11/bayesian_optimization_ucb.png&quot; alt=&quot;Bayesian Optimization with GP Surrogate and UCB&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 11.2. Top: unknown objective, GP surrogate, and evaluated points. Bottom: UCB acquisition selecting the optimal next query \(x^*\).&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hand comparison:&lt;/strong&gt; With \(f^+ = 1.2\), compare point \(A\ (\mu=1.15, \sigma=0.05)\) and point \(B\ (\mu=1.00, \sigma=0.30)\) under UCB with \(\kappa = 2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;When NOT to use BO:&lt;/strong&gt; Identify two problem regimes where standard GP-based Bayesian Optimization is outperformed by gradient descent or random search.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;1D BO script:&lt;/strong&gt; Maximize \(f(x) = \sin(1.2x) + 0.4\cos(2.5x)\) on \([0, 6]\) in Python and report iterations to reach error \(&amp;lt; 0.02\).&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 11.1: Bayesian A/B Testing & Thompson Sampling</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter11/11_01_bayesian_ab_thompson/"/>
   <updated>2025-01-11T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter11/11_01_bayesian_ab_thompson</id>
   <content type="html">&lt;p&gt;Traditional frequentist A/B testing locks you into fixed sample sizes, forbids peeking mid-experiment, and wastes half your traffic on an inferior variant for weeks. &lt;strong&gt;Bayesian A/B Testing&lt;/strong&gt; and &lt;strong&gt;Thompson Sampling&lt;/strong&gt; remove both limitations—reporting direct win probabilities and expected loss while dynamically routing traffic toward winning variants in real time.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;short-video-thompson-sampling-on-a-multi-armed-bandit&quot;&gt;Short Video: Thompson Sampling on a Multi-Armed Bandit&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/thompson-sampling-bandit.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Live bandit animation of 3 competing Beta posteriors: each round samples \(\tilde{\theta}_k\) from every curve, pulls the winning arm, observes reward/loss, and sharpens the winning posterior in real time (Vietnamese narration).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Compute &lt;strong&gt;Probability of Being Best&lt;/strong&gt; \(P(\theta_B &amp;gt; \theta_A \mid D)\) and &lt;strong&gt;Expected Loss&lt;/strong&gt; in Bayesian A/B tests.&lt;/li&gt;
  &lt;li&gt;Understand how &lt;strong&gt;Thompson Sampling&lt;/strong&gt; naturally balances exploration and exploitation.&lt;/li&gt;
  &lt;li&gt;Implement a Beta–Bernoulli Thompson Sampling bandit loop.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-expected-loss--thompson-sampling&quot;&gt;Key Ideas: Expected Loss &amp;amp; Thompson Sampling&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Beta–Binomial updating:&lt;/strong&gt; \(\theta_k \mid D \sim \operatorname{Beta}(\alpha_0 + s_k,\ \beta_0 + f_k)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Expected Loss of choosing B:&lt;/strong&gt; \(\mathbb{E}[\max(\theta_A - \theta_B, 0) \mid D]\). Stop as soon as expected loss drops below your business threshold \(\epsilon\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thompson Sampling loop:&lt;/strong&gt; Sample \(\tilde{\theta}_k \sim \operatorname{Beta}(\alpha_k, \beta_k)\) for each arm, pull \(k^* = \arg\max_k \tilde{\theta}_k\), observe \(r \in \{0, 1\}\), and update \(\alpha_{k^*} \mathrel{+}= r,\ \beta_{k^*} \mathrel{+}= 1-r\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter11/thompson_sampling_ab.png&quot; alt=&quot;Thompson Sampling Posteriors over 3 Variants&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 11.1. Posterior Beta curves for three variants: Thompson Sampling automatically routes most traffic to Variant B.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;interactive-lab-multi-armed-bandit-simulator&quot;&gt;Interactive Lab: Multi-Armed Bandit Simulator&lt;/h3&gt;

&lt;div style=&quot;margin:1.5rem 0;&quot;&gt;
&lt;iframe src=&quot;/public/interactive/thompson_bandit_lab.html&quot; style=&quot;width:100%;height:560px;border:1px solid #ddd;border-radius:10px;background:#fff;&quot; loading=&quot;lazy&quot; title=&quot;Thompson Sampling Bandit Lab&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Win probability &amp;amp; loss:&lt;/strong&gt; Compute \(P(\theta_B &amp;gt; \theta_A \mid D)\) and \(\text{Expected Loss}(B)\) for \(\operatorname{Beta}(12, 88)\) vs. \(\operatorname{Beta}(18, 82)\) using 50,000 NumPy draws.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Self-annealing exploration:&lt;/strong&gt; Explain why Thompson Sampling explores less as sample size \(n_k\) grows.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Regret comparison:&lt;/strong&gt; Simulate 1,000 rounds for true rates \((0.10, 0.18, 0.07)\) and plot cumulative regret for 50/50 A/B testing vs. Thompson Sampling.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 10.4: Suy luận Biến phân (Variational Inference), ELBO & ADVI</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter10/10_04_variational_inference/"/>
   <updated>2025-01-10T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter10/10_04_variational_inference</id>
   <content type="html">&lt;p&gt;MCMC là tiêu chuẩn vàng về độ chính xác tiệm cận, nhưng khi mô hình có 100.000 tham số trên hàng triệu quan sát (như mô hình chủ đề văn bản hay mạng nơ-ron Bayes), chạy NUTS có thể mất nhiều ngày. &lt;strong&gt;Suy luận Biến phân (Variational Inference — VI)&lt;/strong&gt; biến bài toán &lt;strong&gt;lấy mẫu&lt;/strong&gt; thành bài toán &lt;strong&gt;tối ưu hóa&lt;/strong&gt;: chọn một họ phân phối đơn giản \(q_\phi(\theta)\) rồi dùng gradient ascent kéo nó lại gần hậu nghiệm thực \(p(\theta \mid y)\) nhất có thể.&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-suy-luận-biến-phân-vi-cực-đại-elbo--co-hẹp-phương-sai&quot;&gt;Video ngắn: Suy luận Biến phân (VI): Cực đại ELBO &amp;amp; Co hẹp phương sai&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/variational-inference-elbo.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 30 giây (có thuyết minh tiếng Việt): elip Mean-Field VI dịch chuyển theo gradient ascent tăng ELBO, hạ KL và cho thấy lý do Reverse KL đánh giá thấp phương sai ở hai đuôi.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Hiểu cách đo khoảng cách giữa \(q_\phi(\theta)\) và \(p(\theta \mid y)\) bằng &lt;strong&gt;phân kỳ Kullback–Leibler (KL Divergence)&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Chứng minh và diễn giải &lt;strong&gt;Cận dưới Bằng chứng (ELBO — Evidence Lower Bound)&lt;/strong&gt; như sự cân bằng giữa độ khớp dữ liệu và lực kéo về prior.&lt;/li&gt;
  &lt;li&gt;Hiểu ưu/nhược điểm của &lt;strong&gt;Mean-Field VI / ADVI&lt;/strong&gt; trong PyMC, đặc biệt là xu hướng đánh giá thấp phương sai hậu nghiệm.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-từ-kl-divergence-đến-elbo&quot;&gt;Kiến thức cần nhớ: Từ KL Divergence đến ELBO&lt;/h2&gt;

&lt;p&gt;Ta muốn cực tiểu hóa \(\operatorname{KL}\!\left(q_\phi(\theta) \parallel p(\theta \mid y)\right) = \mathbb{E}_q\!\left[\log \frac{q_\phi(\theta)}{p(\theta \mid y)}\right]\). Biến đổi bằng quy tắc Bayes \(p(\theta \mid y) = \frac{p(y, \theta)}{p(y)}\), ta thu được đẳng thức nền tảng của VI:&lt;/p&gt;

\[\log p(y) = \underbrace{\mathbb{E}_{q_\phi}\!\left[\log p(y \mid \theta)\right] - \operatorname{KL}\!\left(q_\phi(\theta) \parallel p(\theta)\right)}_{\text{ELBO}(\phi)} + \operatorname{KL}\!\left(q_\phi(\theta) \parallel p(\theta \mid y)\right).\]

&lt;p&gt;Vì \(\log p(y)\) không phụ thuộc vào \(\phi\) và \(\operatorname{KL} \ge 0\), việc &lt;strong&gt;cực đại hóa \(\text{ELBO}(\phi)\) tương đương tuyệt đối với cực tiểu hóa \(\operatorname{KL}(q_\phi \parallel p(\theta \mid y))\)&lt;/strong&gt; — mà hoàn toàn không cần biết \(p(y)\)!&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter10/variational_inference_kl.png&quot; alt=&quot;Mean-Field VI đánh giá thấp phương sai của hậu nghiệm tương quan&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 10.4. Khi hậu nghiệm thực tương quan chéo (đường liền xanh), xấp xỉ Mean-Field độc lập \(q(\theta_1, \theta_2) = q_1(\theta_1)q_2(\theta_2)\) (đường đứt đỏ) co lại vào vùng lõi để tránh bị phạt nặng ở nơi \(p \approx 0\) — dẫn tới đánh giá thấp phương sai.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-chạy-advi-chỉ-với-một-dòng-trong-pymc&quot;&gt;1. Chạy ADVI chỉ với một dòng trong PyMC&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;ADVI (Automatic Differentiation Variational Inference)&lt;/strong&gt; tự động biến đổi mọi tham số bị chặn về \(\mathbb{R}^d\) rồi tối ưu ELBO bằng gradient ngẫu nhiên:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;approx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20_000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;method&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;advi&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;idata_vi&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;approx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draws&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Tiêu chí&lt;/th&gt;
      &lt;th&gt;MCMC (NUTS)&lt;/th&gt;
      &lt;th&gt;Variational Inference (ADVI)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Bản chất&lt;/td&gt;
      &lt;td&gt;Lấy mẫu chuỗi Markov&lt;/td&gt;
      &lt;td&gt;Tối ưu hóa hàm ELBO&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Độ chính xác tiệm cận&lt;/td&gt;
      &lt;td&gt;Hội tụ đúng hậu nghiệm thực&lt;/td&gt;
      &lt;td&gt;Có sai số xấp xỉ (thường đánh giá thấp phương sai)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Tốc độ trên dữ liệu lớn&lt;/td&gt;
      &lt;td&gt;Chậm&lt;/td&gt;
      &lt;td&gt;Rất nhanh (hỗ trợ mini-batch)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Chứng minh đẳng thức ELBO:&lt;/strong&gt; Tự viết lại 4 dòng biến đổi đại số chứng minh \(\log p(y) - \operatorname{KL}(q \parallel p(\cdot \mid y)) = \mathbb{E}_q[\log p(y, \theta) - \log q(\theta)]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tại sao Reverse KL lại “né đuôi” (zero-forcing)?&lt;/strong&gt; Dựa vào biểu thức \(\int q(\theta)\log\frac{q(\theta)}{p(\theta \mid y)}\,d\theta\), giải thích chuyện gì xảy ra nếu \(q(\theta) &amp;gt; 0\) tại vùng mà \(p(\theta \mid y) \approx 0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh ADVI vs. NUTS:&lt;/strong&gt; Chạy cùng một mô hình hồi quy logistic trong PyMC bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.sample()&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.fit(method=&quot;advi&quot;)&lt;/code&gt;; so sánh thời gian chạy và độ rộng 95% HDI của các hệ số.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 10.3: Chuỗi thời gian Bayes, Không gian trạng thái & Bộ lọc Kalman</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter10/10_03_state_space_kalman/"/>
   <updated>2025-01-10T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter10/10_03_state_space_kalman</id>
   <content type="html">&lt;p&gt;Một chiếc tàu vũ trụ Apollo bay tới Mặt Trăng hay một xe tự lái chạy trong đường hầm liên tục nhận tín hiệu cảm biến nhiễu loạn. Làm thế nào hệ thống kết hợp &lt;strong&gt;định luật vật lý dự đoán chuyển động&lt;/strong&gt; với &lt;strong&gt;số đo cảm biến có sai số&lt;/strong&gt; theo từng mili-giây để ước lượng vị trí chính xác nhất? Câu trả lời kinh điển — &lt;strong&gt;Bộ lọc Kalman (Kalman Filter)&lt;/strong&gt; — thực chất chính là &lt;strong&gt;cập nhật Bayes tuần tự (Sequential Bayesian Updating)&lt;/strong&gt; trong mô hình không gian trạng thái tuyến tính Gaussian!&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-bộ-lọc-kalman-qua-mô-phỏng-vật-lý-chuyển-động-thực&quot;&gt;Video ngắn: Bộ lọc Kalman qua mô phỏng vật lý chuyển động thực&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/kalman-filter-tracking.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video mô phỏng vật thể di chuyển có quán tính dưới tín hiệu radar nhiễu: vòng bất định prior giãn rộng khi dự đoán theo động học, rồi co chặt lại thành hậu nghiệm ngay khi phép đo mới xuất hiện cùng quỹ đạo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TracedPath&lt;/code&gt; và chỉ số Kalman Gain theo thời gian thực.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Mô hình hóa chuỗi thời gian bằng &lt;strong&gt;Mô hình Không gian Trạng thái (State-Space Model)&lt;/strong&gt;: phương trình chuyển trạng thái và phương trình quan sát.&lt;/li&gt;
  &lt;li&gt;Hiểu hai bước lặp &lt;strong&gt;Dự đoán (Predict)&lt;/strong&gt; và &lt;strong&gt;Cập nhật (Update)&lt;/strong&gt; của Bộ lọc Kalman như một vòng lặp Bayes chuẩn–chuẩn liên hợp.&lt;/li&gt;
  &lt;li&gt;Diễn giải trực giác &lt;strong&gt;Hệ số khuếch đại Kalman (Kalman Gain \(K_t\))&lt;/strong&gt; như trọng số cân bằng giữa độ tin cậy của mô hình vật lý và độ tin cậy của cảm biến.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-vòng-lặp-dự-đoán--cập-nhật-1-chiều&quot;&gt;Kiến thức cần nhớ: Vòng lặp Dự đoán – Cập nhật 1 Chiều&lt;/h2&gt;

&lt;p&gt;Xét trạng thái ẩn \(x_t\) (vị trí thực) và phép đo nhiễu \(y_t\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phương trình trạng thái:&lt;/strong&gt; \(x_t = x_{t-1} + v\,\Delta t + w_t, \quad w_t \sim \mathcal{N}(0, Q)\) (\(Q\): nhiễu quá trình).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương trình quan sát:&lt;/strong&gt; \(y_t = x_t + \nu_t, \quad \nu_t \sim \mathcal{N}(0, R)\) (\(R\): nhiễu cảm biến).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tại mỗi bước thời gian \(t\), xuất phát từ hậu nghiệm bước trước \(x_{t-1} \mid y_{1:t-1} \sim \mathcal{N}(m_{t-1}, P_{t-1})\):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước Dự đoán (Prior ở thời điểm \(t\)):&lt;/strong&gt;
\(m_t^- = m_{t-1} + v\,\Delta t, \qquad P_t^- = P_{t-1} + Q.\)
&lt;em&gt;(Độ bất định luôn tăng thêm \(Q\) vì thế giới thực có nhiễu động lực.)&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước Cập nhật (Posterior khi nhận đo lường \(y_t\)):&lt;/strong&gt;
\(K_t = \frac{P_t^-}{P_t^- + R}, \qquad m_t = m_t^- + K_t (y_t - m_t^-), \qquad P_t = (1 - K_t) P_t^-.\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter10/kalman_filter_tracking.png&quot; alt=&quot;Bộ lọc Kalman 1D bám theo quỹ đạo thực từ số đo nhiễu&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 10.3. Quỹ đạo thực (đen), số đo cảm biến nhiễu mạnh (chấm đỏ) và ước lượng hậu nghiệm của Bộ lọc Kalman (xanh) kèm dải bất định 95%.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-ví-dụ-cầm-tay-chỉ-việc-1-bước-bộ-lọc-kalman&quot;&gt;1. Ví dụ cầm tay chỉ việc: 1 bước Bộ lọc Kalman&lt;/h2&gt;

&lt;p&gt;Giả sử ước lượng trước là \(m_0 = 10.0,\ P_0 = 4.0\), vận tốc \(v\,\Delta t = 2.0\), nhiễu quá trình \(Q = 1.0\), nhiễu cảm biến \(R = 5.0\), và cảm biến đo được \(y_1 = 15.0\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Dự đoán:&lt;/strong&gt; \(m_1^- = 10.0 + 2.0 = 12.0\), \(P_1^- = 4.0 + 1.0 = 5.0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kalman Gain:&lt;/strong&gt; \(K_1 = \frac{5.0}{5.0 + 5.0} = 0.50\) (vì bất định dự đoán và nhiễu cảm biến bằng nhau!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật:&lt;/strong&gt; \(m_1 = 12.0 + 0.50(15.0 - 12.0) = 13.5\), và phương sai hậu nghiệm giảm một nửa còn \(P_1 = (1 - 0.50)\times 5.0 = 2.5\)!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;thực-hành-tương-tác-mô-phỏng-bộ-lọc-kalman-theo-thời-gian-thực&quot;&gt;Thực hành tương tác: Mô phỏng Bộ lọc Kalman theo thời gian thực&lt;/h3&gt;

&lt;div style=&quot;margin:1.5rem 0;&quot;&gt;
&lt;iframe src=&quot;/public/interactive/kalman_filter_lab.html&quot; style=&quot;width:100%;height:560px;border:1px solid #ddd;border-radius:10px;background:#fff;&quot; loading=&quot;lazy&quot; title=&quot;Kalman Filter Interactive Lab&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính tay bước thứ 2:&lt;/strong&gt; Tiếp nối ví dụ trên (\(m_1 = 13.5, P_1 = 2.5\)), nếu ở bước \(t = 2\) cảm biến đo được \(y_2 = 14.0\) (giữ nguyên \(v\Delta t = 2, Q = 1, R = 5\)), hãy tính \(m_2^-, P_2^-, K_2, m_2, P_2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hai trường hợp giới hạn của \(K_t\):&lt;/strong&gt; Điều gì xảy ra với \(K_t\) và \(m_t\) khi cảm biến gần như hoàn hảo (\(R \to 0\)) so với khi cảm biến cực kỳ nhiễu (\(R \to \infty\))?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mất tín hiệu GPS:&lt;/strong&gt; Trong thực tế khi xe đi vào hầm và không có phép đo \(y_t\) trong 5 giây liên tiếp, công thức Bộ lọc Kalman xử lý thế nào và phương sai \(P_t\) thay đổi ra sao?&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 10.2: Mô hình Hỗn hợp Bayes (Bayesian Mixture Models) & Nhãn ẩn</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter10/10_02_mixture_models/"/>
   <updated>2025-01-10T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter10/10_02_mixture_models</id>
   <content type="html">&lt;p&gt;Dữ liệu chiều cao của một quần thể hỗn hợp hay thời gian phản hồi của một hệ thống máy chủ thường có &lt;strong&gt;hai hoặc nhiều đỉnh&lt;/strong&gt; — không một phân phối chuẩn đơn lẻ nào khớp nổi. &lt;strong&gt;Mô hình hỗn hợp Bayes (Bayesian Mixture Models)&lt;/strong&gt; mô tả dữ liệu như sự pha trộn của \(K\) phân phối thành phần, trong đó mỗi điểm dữ liệu \(y_i\) mang một &lt;strong&gt;biến ẩn (latent variable)&lt;/strong&gt; \(z_i \in \{1, \dots, K\}\) cho biết nó sinh ra từ cụm nào.&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-mô-hình-hỗn-hợp--xác-suất-thuộc-cụm&quot;&gt;Video ngắn: Mô hình Hỗn hợp &amp;amp; Xác suất thuộc cụm&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/mixture-model-responsibilities.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Video dài khoảng 29 giây (có thuyết minh tiếng Việt): trượt điểm quan sát y dọc hỗn hợp 2 phân phối chuẩn để xem 2 thanh xác suất hậu nghiệm P(Cụm 1&lt;/td&gt;
      &lt;td&gt;y) và P(Cụm 2&lt;/td&gt;
      &lt;td&gt;y) đổi nhịp trực tiếp.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Viết mô hình sinh dữ liệu của Gaussian Mixture Model (GMM) với prior Dirichlet cho trọng số cụm \(\boldsymbol{\pi}\).&lt;/li&gt;
  &lt;li&gt;Tính xác suất hậu nghiệm thuộc cụm (responsibility) \(P(z_i = k \mid y_i, \boldsymbol{\theta})\) bằng định lý Bayes.&lt;/li&gt;
  &lt;li&gt;Nhận diện và khắc phục hiện tượng &lt;strong&gt;Hoán vị nhãn (Label Switching)&lt;/strong&gt; khi chạy MCMC trên mô hình hỗn hợp.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-phép-biên-hóa-biến-ẩn-và-prior-dirichlet&quot;&gt;Kiến thức cần nhớ: Phép biên hóa biến ẩn và Prior Dirichlet&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối hỗn hợp (Marginalized Likelihood):&lt;/strong&gt;
\(p(y_i \mid \boldsymbol{\pi}, \boldsymbol{\mu}, \boldsymbol{\sigma}) = \sum_{k=1}^{K} \pi_k\,\mathcal{N}(y_i \mid \mu_k, \sigma_k^2), \qquad \sum_{k=1}^K \pi_k = 1,\ \boldsymbol{\pi} \sim \operatorname{Dirichlet}(\boldsymbol{\alpha}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khử biến rời rạc cho HMC/NUTS:&lt;/strong&gt; HMC không lấy đạo hàm qua biến rời rạc \(z_i\) được, nên trong PyMC ta luôn dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.NormalMixture&lt;/code&gt; (cộng biên theo \(k = 1 \dots K\)) rồi tính lại xác suất thuộc cụm sau khi lấy mẫu!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bẫy Label Switching:&lt;/strong&gt; Đổi tên Cụm 1 thành Cụm 2 cho cùng giá trị likelihood! Cách khắc phục chuẩn trong PyMC là áp ràng buộc thứ tự &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;transform=pm.distributions.transforms.ordered&lt;/code&gt; lên vector trung bình \(\mu_1 &amp;lt; \mu_2 &amp;lt; \dots &amp;lt; \mu_K\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter10/mixture_model.png&quot; alt=&quot;Mô hình hỗn hợp hai phân phối chuẩn&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 10.2. Phân phối hỗn hợp gồm 40% thành phần \(\mathcal{N}(0.5, 1.0^2)\) và 60% thành phần \(\mathcal{N}(5.0, 1.3^2)\).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-ví-dụ-cầm-tay-chỉ-việc-tính-xác-suất-thuộc-cụm&quot;&gt;1. Ví dụ cầm tay chỉ việc: Tính xác suất thuộc cụm&lt;/h2&gt;

&lt;p&gt;Với hỗn hợp ở Hình 10.2 (\(\pi_1 = 0.4, \mathcal{N}(0.5, 1^2)\) và \(\pi_2 = 0.6, \mathcal{N}(5.0, 1.3^2)\)), xét một điểm quan sát \(y = 2.5\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Thành phần 1: \(\pi_1 \mathcal{N}(2.5 \mid 0.5, 1^2) \approx 0.4 \times 0.0540 = 0.0216\).&lt;/li&gt;
  &lt;li&gt;Thành phần 2: \(\pi_2 \mathcal{N}(2.5 \mid 5.0, 1.3^2) \approx 0.6 \times 0.0484 = 0.0290\).&lt;/li&gt;
  &lt;li&gt;Xác suất hậu nghiệm thuộc cụm 2: \(P(z = 2 \mid y = 2.5) = \frac{0.0290}{0.0216 + 0.0290} \approx 57.3\%\). Thay vì gán cứng 0/1 như K-means, mô hình Bayes báo trung thực độ mơ hồ 42.7% vs. 57.3%!&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gmm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dirichlet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                   &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;distributions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ordered&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;NormalMixture&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính tay responsibility:&lt;/strong&gt; Dùng cùng mô hình Hình 10.2, tính \(P(z = 1 \mid y = 1.0)\) và \(P(z = 1 \mid y = 4.0)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prior hỗn hợp liên hợp (Wiley):&lt;/strong&gt; Nếu prior cho \(\theta\) là hỗn hợp \(0.9\,\operatorname{Beta}(10, 10) + 0.1\,\operatorname{Beta}(1, 1)\), chứng minh hậu nghiệm sau khi quan sát \(k\) lần ngửa trên \(n\) lần tung vẫn là hỗn hợp hai phân phối Beta và giải thích vì sao prior này “chống sốc” tốt khi dữ liệu mâu thuẫn với niềm tin ban đầu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chọn số cụm \(K\):&lt;/strong&gt; So sánh mô hình \(K = 2\) và \(K = 3\) trên dữ liệu mô phỏng bằng PSIS-LOO trong ArviZ.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 10.1: Quá trình Gaussian (Gaussian Processes) & Hàm Nhân (Kernels)</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter10/10_01_gaussian_processes/"/>
   <updated>2025-01-10T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter10/10_01_gaussian_processes</id>
   <content type="html">&lt;p&gt;Ở hồi quy tuyến tính hay đa thức, ta đặt phân phối prior lên một số hữu hạn hệ số \(\beta_0, \beta_1, \dots, \beta_p\) — nghĩa là ép hàm cần tìm nằm trong một khuôn hình định sẵn. Nhưng điều gì xảy ra nếu ta đặt phân phối prior &lt;strong&gt;trực tiếp lên toàn bộ không gian các hàm trơn \(f(x)\)&lt;/strong&gt;? Đó chính là phép màu của &lt;strong&gt;Quá trình Gaussian (Gaussian Process — GP)&lt;/strong&gt;: một mô hình Bayes phi tham số có khả năng uốn lượn linh hoạt theo dữ liệu và tự động mở rộng dải bất định ở những vùng chưa có quan sát.&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-quá-trình-gaussian--ảnh-hưởng-của-length-scale-ℓ&quot;&gt;Video ngắn: Quá trình Gaussian &amp;amp; Ảnh hưởng của Length-Scale ℓ&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/gp-kernel-posterior.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 41 giây (có thuyết minh tiếng Việt): thêm từng điểm dữ liệu làm thắt chặt dải bất định 95% của GP và trượt độ dài tương quan ℓ trong kernel RBF từ 0.45 đến 2.60.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Hiểu định nghĩa Quá trình Gaussian như phân phối chuẩn đa biến mở rộng sang vô hạn chiều.&lt;/li&gt;
  &lt;li&gt;Phân biệt vai trò của các &lt;strong&gt;hàm nhân hiệp phương sai (kernels)&lt;/strong&gt;: RBF (Squared Exponential), Matérn, Periodic, và tác động của độ dài tương quan \(\ell\) cùng biên độ \(\sigma_f\).&lt;/li&gt;
  &lt;li&gt;Tự tính tay được trung bình và phương sai hậu nghiệm GP tại một điểm dự báo mới \(x_*\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hàm-nhân-quyết-định-hình-dạng-hàm-số&quot;&gt;Kiến thức cần nhớ: Hàm Nhân Quyết Định Hình Dạng Hàm Số&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Định nghĩa GP:&lt;/strong&gt; \(f(x) \sim \mathcal{GP}\!\left(m(x),\ k(x, x&apos;)\right)\) nghĩa là với mọi tập hữu hạn điểm \(x_1, \dots, x_n\), vector giá trị hàm \((f(x_1), \dots, f(x_n))^T\) tuân theo phân phối chuẩn đa biến với ma trận hiệp phương sai \(K_{ij} = k(x_i, x_j)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm nhân RBF (Squared Exponential):&lt;/strong&gt;
\(k_{\text{RBF}}(x, x&apos;) = \sigma_f^2 \exp\!\left(-\frac{(x - x&apos;)^2}{2\ell^2}\right).\)
    &lt;ul&gt;
      &lt;li&gt;\(\ell\) (&lt;em&gt;length-scale&lt;/em&gt;): hai điểm cách nhau dưới \(\ell\) có giá trị hàm tương quan mạnh; \(\ell\) lớn cho hàm rất mượt, \(\ell\) nhỏ cho hàm dao động nhanh.&lt;/li&gt;
      &lt;li&gt;\(\sigma_f\) (&lt;em&gt;output scale&lt;/em&gt;): quyết định biên độ biến thiên theo trục tung.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật hậu nghiệm dạng đóng:&lt;/strong&gt; Với dữ liệu nhiễu \(y = f(X) + \epsilon,\ \epsilon \sim \mathcal{N}(0, \sigma_n^2 I)\), phân phối hậu nghiệm tại điểm mới \(X_*\) vẫn là phân phối chuẩn:
\(\boldsymbol{\mu}_* = K_* (K + \sigma_n^2 I)^{-1} \mathbf{y}, \qquad \mathbf{\Sigma}_* = K_{**} - K_* (K + \sigma_n^2 I)^{-1} K_*^T.\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter10/gaussian_process_posterior.png&quot; alt=&quot;Hồi quy Quá trình Gaussian với dải bất định 95%&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 10.1. Quá trình Gaussian với kernel RBF: dải bất định 95% thu hẹp sát tại 5 điểm quan sát và tự động phình rộng ở các khoảng trống.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-ví-dụ-cầm-tay-chỉ-việc-dự-báo-tại-1-điểm-mới&quot;&gt;1. Ví dụ cầm tay chỉ việc: Dự báo tại 1 điểm mới&lt;/h2&gt;

&lt;p&gt;Giả sử \(m(x) = 0\), kernel RBF với \(\sigma_f = 1, \ell = 1\), nhiễu \(\sigma_n = 0\), và ta quan sát đúng 1 điểm \(x_1 = 0, y_1 = 2.0\). Hãy dự báo tại \(x_* = 1\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(K = [k(0, 0)] = [1]\); \(K_* = [k(1, 0)] = [e^{-0.5}] \approx [0.6065]\); \(K_{**} = [1]\).&lt;/li&gt;
  &lt;li&gt;Trung bình hậu nghiệm: \(\mu_* = 0.6065 \times 1^{-1} \times 2.0 \approx 1.213\).&lt;/li&gt;
  &lt;li&gt;Phương sai hậu nghiệm: \(\Sigma_* = 1 - 0.6065^2 = 1 - e^{-1} \approx 0.632\) (giảm so với phương sai prior bằng 1 nhờ thông tin từ \(x_1\)!).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;thực-hành-tương-tác-khám-phá-kernel--hậu-nghiệm-gp&quot;&gt;Thực hành tương tác: Khám phá Kernel &amp;amp; Hậu nghiệm GP&lt;/h3&gt;

&lt;div style=&quot;margin:1.5rem 0;&quot;&gt;
&lt;iframe src=&quot;/public/interactive/gp_kernel_lab.html&quot; style=&quot;width:100%;height:560px;border:1px solid #ddd;border-radius:10px;background:#fff;&quot; loading=&quot;lazy&quot; title=&quot;Gaussian Process Kernel Lab&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính tay với 2 điểm dữ liệu:&lt;/strong&gt; Dùng cùng kernel RBF (\(\sigma_f = 1, \ell = 1, \sigma_n = 0\)), tính \(\mu_*\) và \(\Sigma_*\) tại \(x_* = 0.5\) khi có hai quan sát \((0, 1)\) và \((1, 1)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ phức tạp tính toán:&lt;/strong&gt; Vì sao GP chuẩn tốn \(O(n^3)\) khi nghịch đảo ma trận \(K + \sigma_n^2 I\), và khi \(n = 50{,}000\) ta cần các kỹ thuật xấp xỉ nào (ví dụ: Inducing Points / HSGP)?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thử nghiệm PyMC:&lt;/strong&gt; Dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.gp.Marginal&lt;/code&gt; với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.gp.cov.Matern52&lt;/code&gt; để khớp chuỗi dữ liệu phi tuyến có nhiễu và vẽ 10 đường hàm rút từ hậu nghiệm.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 10.4: Variational Inference, ELBO & ADVI</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter10/10_04_variational_inference/"/>
   <updated>2025-01-10T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter10/10_04_variational_inference</id>
   <content type="html">&lt;p&gt;MCMC is the gold standard for asymptotic accuracy, yet on models with 100,000 parameters and millions of rows, NUTS can take days. &lt;strong&gt;Variational Inference (VI)&lt;/strong&gt; turns &lt;strong&gt;sampling&lt;/strong&gt; into &lt;strong&gt;optimization&lt;/strong&gt;: pick a tractable family \(q_\phi(\theta)\) and use gradient ascent to pull it as close as possible to the true posterior \(p(\theta \mid y)\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Measure distributional distance with &lt;strong&gt;Kullback–Leibler (KL) Divergence&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Derive and interpret the &lt;strong&gt;Evidence Lower Bound (ELBO)&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Understand &lt;strong&gt;Mean-Field VI / ADVI&lt;/strong&gt; in PyMC, including its classic variance-underestimation behavior.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-maximizing-the-elbo&quot;&gt;Key Ideas: Maximizing the ELBO&lt;/h2&gt;

&lt;p&gt;By Bayes’ theorem:
\(\log p(y) = \underbrace{\mathbb{E}_{q_\phi}\!\left[\log p(y \mid \theta)\right] - \operatorname{KL}\!\left(q_\phi(\theta) \parallel p(\theta)\right)}_{\text{ELBO}(\phi)} + \operatorname{KL}\!\left(q_\phi(\theta) \parallel p(\theta \mid y)\right).\)
Because \(\log p(y)\) is constant in \(\phi\) and \(\operatorname{KL} \ge 0\), maximizing the &lt;strong&gt;ELBO&lt;/strong&gt; minimizes \(\operatorname{KL}(q_\phi \parallel p(\theta \mid y))\) without ever computing \(p(y)\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter10/variational_inference_kl.png&quot; alt=&quot;Mean-Field VI Underestimates Variance&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 10.4. Mean-field VI (dashed red) fits an axis-aligned Gaussian inside a correlated posterior (solid blue), underestimating marginal variance.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-running-advi-in-pymc&quot;&gt;1. Running ADVI in PyMC&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;approx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20_000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;method&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;advi&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;idata_vi&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;approx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draws&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Derive the ELBO:&lt;/strong&gt; Prove in 4 lines that \(\log p(y) - \operatorname{KL}(q \parallel p(\cdot \mid y)) = \mathbb{E}_q[\log p(y, \theta) - \log q(\theta)]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Zero-forcing property:&lt;/strong&gt; Explain why minimizing reverse KL penalizes placing mass where \(p(\theta \mid y) \approx 0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ADVI vs. NUTS benchmark:&lt;/strong&gt; Compare runtime and 95% HDI width between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.sample()&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.fit(method=&quot;advi&quot;)&lt;/code&gt; on a logistic regression model.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 10.3: Bayesian Time Series, State-Space Models & Kalman Filter</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter10/10_03_state_space_kalman/"/>
   <updated>2025-01-10T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter10/10_03_state_space_kalman</id>
   <content type="html">&lt;p&gt;Whether guiding an Apollo spacecraft to the Moon or tracking an autonomous vehicle through noisy radar returns, engineers combine &lt;strong&gt;physical motion predictions&lt;/strong&gt; with &lt;strong&gt;noisy sensor measurements&lt;/strong&gt; millisecond by millisecond. That celebrated algorithm—the &lt;strong&gt;Kalman Filter&lt;/strong&gt;—is literally &lt;strong&gt;exact sequential Bayesian updating&lt;/strong&gt; for a linear Gaussian state-space model!&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;short-video-physics-simulation-of-a-bayesian-kalman-filter&quot;&gt;Short Video: Physics Simulation of a Bayesian Kalman Filter&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/kalman-filter-tracking.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Physics-driven animation of a moving body tracked under noisy radar readings: watch the prior uncertainty expand with process noise, snap tighter on each measurement update, and trace the filtered path with live Kalman Gain readouts (Vietnamese narration).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Formulate dynamic time series as &lt;strong&gt;State-Space Models&lt;/strong&gt; (state transition + observation equations).&lt;/li&gt;
  &lt;li&gt;Derive the 1D Kalman &lt;strong&gt;Predict&lt;/strong&gt; and &lt;strong&gt;Update&lt;/strong&gt; steps as conjugate Normal–Normal Bayesian updating.&lt;/li&gt;
  &lt;li&gt;Interpret the &lt;strong&gt;Kalman Gain \(K_t\)&lt;/strong&gt; as the precision-weighted balance between physics prediction and sensor data.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-predictupdate-cycle&quot;&gt;Key Ideas: Predict–Update Cycle&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;State equation:&lt;/strong&gt; \(x_t = x_{t-1} + v\,\Delta t + w_t,\quad w_t \sim \mathcal{N}(0, Q)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Observation equation:&lt;/strong&gt; \(y_t = x_t + \nu_t,\quad \nu_t \sim \mathcal{N}(0, R)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Predict:&lt;/strong&gt; \(m_t^- = m_{t-1} + v\,\Delta t,\quad P_t^- = P_{t-1} + Q\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Update:&lt;/strong&gt; \(K_t = \frac{P_t^-}{P_t^- + R},\quad m_t = m_t^- + K_t(y_t - m_t^-),\quad P_t = (1 - K_t)P_t^-\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter10/kalman_filter_tracking.png&quot; alt=&quot;1D Kalman Filter Tracking&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 10.3. True latent position (black), noisy radar measurements (red dots), and Kalman posterior mean with 95% credible band (blue).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-worked-example-one-step-by-hand&quot;&gt;1. Worked Example: One Step by Hand&lt;/h2&gt;

&lt;p&gt;Start with \(m_0 = 10.0,\ P_0 = 4.0,\ v\Delta t = 2.0,\ Q = 1.0,\ R = 5.0\), and observe \(y_1 = 15.0\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Predict:&lt;/strong&gt; \(m_1^- = 12.0,\ P_1^- = 5.0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gain:&lt;/strong&gt; \(K_1 = \frac{5.0}{5.0 + 5.0} = 0.50\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Update:&lt;/strong&gt; \(m_1 = 12.0 + 0.50(15.0 - 12.0) = 13.5,\quad P_1 = (1 - 0.50)\times 5.0 = 2.5\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;interactive-lab-real-time-kalman-filter-simulator&quot;&gt;Interactive Lab: Real-Time Kalman Filter Simulator&lt;/h3&gt;

&lt;div style=&quot;margin:1.5rem 0;&quot;&gt;
&lt;iframe src=&quot;/public/interactive/kalman_filter_lab.html&quot; style=&quot;width:100%;height:560px;border:1px solid #ddd;border-radius:10px;background:#fff;&quot; loading=&quot;lazy&quot; title=&quot;Kalman Filter Interactive Lab&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Second step by hand:&lt;/strong&gt; Continuing from \(m_1 = 13.5, P_1 = 2.5\), observe \(y_2 = 14.0\) and compute \(m_2^-, P_2^-, K_2, m_2, P_2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Limiting regimes:&lt;/strong&gt; Analyze \(K_t\) and \(m_t\) as \(R \to 0\) (perfect sensor) vs. \(R \to \infty\) (useless sensor).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tunnel blackout:&lt;/strong&gt; How does the filter behave during 5 consecutive time steps with no sensor measurement \(y_t\)?&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 10.2: Bayesian Mixture Models & Latent Clusters</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter10/10_02_mixture_models/"/>
   <updated>2025-01-10T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter10/10_02_mixture_models</id>
   <content type="html">&lt;p&gt;Server latencies or biological measurements from mixed subpopulations often exhibit &lt;strong&gt;two or more peaks&lt;/strong&gt; that no single Gaussian can fit. &lt;strong&gt;Bayesian Mixture Models&lt;/strong&gt; represent such data as a weighted blend of \(K\) component distributions, each datum carrying a &lt;strong&gt;latent cluster indicator&lt;/strong&gt; \(z_i \in \{1, \dots, K\}\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Write the generative Gaussian Mixture Model (GMM) with a Dirichlet prior on mixing weights \(\boldsymbol{\pi}\).&lt;/li&gt;
  &lt;li&gt;Compute posterior cluster membership probabilities (responsibilities) via Bayes’ theorem.&lt;/li&gt;
  &lt;li&gt;Prevent &lt;strong&gt;label switching&lt;/strong&gt; in MCMC using ordered parameter constraints.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-marginalization--label-switching&quot;&gt;Key Ideas: Marginalization &amp;amp; Label Switching&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Marginalized likelihood (HMC-friendly):&lt;/strong&gt;
\(p(y_i \mid \boldsymbol{\pi}, \boldsymbol{\mu}, \boldsymbol{\sigma}) = \sum_{k=1}^{K} \pi_k\,\mathcal{N}(y_i \mid \mu_k, \sigma_k^2), \qquad \boldsymbol{\pi} \sim \operatorname{Dirichlet}(\boldsymbol{\alpha}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Label switching:&lt;/strong&gt; Swapping component 1 and component 2 leaves the likelihood unchanged! Enforcing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;transform=pm.distributions.transforms.ordered&lt;/code&gt; on \(\mu_1 &amp;lt; \dots &amp;lt; \mu_K\) breaks this symmetry cleanly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter10/mixture_model.png&quot; alt=&quot;Two-Component Gaussian Mixture Model&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 10.2. Two-component Gaussian mixture: 40% \(\mathcal{N}(0.5, 1.0^2)\) and 60% \(\mathcal{N}(5.0, 1.3^2)\).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-worked-example-responsibility-calculation&quot;&gt;1. Worked Example: Responsibility Calculation&lt;/h2&gt;

&lt;p&gt;At \(y = 2.5\) in Figure 10.2:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Weighted density 1: \(0.4 \times \mathcal{N}(2.5 \mid 0.5, 1^2) \approx 0.0216\).&lt;/li&gt;
  &lt;li&gt;Weighted density 2: \(0.6 \times \mathcal{N}(2.5 \mid 5.0, 1.3^2) \approx 0.0290\).&lt;/li&gt;
  &lt;li&gt;Posterior responsibility: \(P(z = 2 \mid y = 2.5) = \frac{0.0290}{0.0216 + 0.0290} \approx 57.3\%\).&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gmm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dirichlet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                   &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;distributions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ordered&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;NormalMixture&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Responsibilities:&lt;/strong&gt; Compute \(P(z = 1 \mid y = 1.0)\) and \(P(z = 1 \mid y = 4.0)\) for the mixture in Figure 10.2.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Robust mixture priors:&lt;/strong&gt; Show that a mixture of conjugate Beta priors yields a mixture of Beta posteriors and explain why it protects against prior–data conflict.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Selecting \(K\):&lt;/strong&gt; Compare \(K=2\) vs. \(K=3\) GMMs on simulated data using ArviZ PSIS-LOO.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 10.1: Gaussian Processes & Covariance Kernels</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter10/10_01_gaussian_processes/"/>
   <updated>2025-01-10T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter10/10_01_gaussian_processes</id>
   <content type="html">&lt;p&gt;In parametric linear or polynomial regression, we place a prior over finitely many coefficients \(\beta_0, \dots, \beta_p\), forcing the curve into a rigid template. What if we instead place a prior &lt;strong&gt;directly over entire smooth functions \(f(x)\)&lt;/strong&gt;? That is the elegance of a &lt;strong&gt;Gaussian Process (GP)&lt;/strong&gt;: a nonparametric Bayesian model that bends flexibly through observed data while widening its uncertainty bands wherever data are scarce.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Understand a Gaussian Process as an infinite-dimensional generalization of the multivariate normal distribution.&lt;/li&gt;
  &lt;li&gt;Interpret covariance &lt;strong&gt;kernels&lt;/strong&gt; (RBF, Matérn, Periodic) and their hyperparameters \(\ell\) (length-scale) and \(\sigma_f\) (amplitude).&lt;/li&gt;
  &lt;li&gt;Compute the closed-form GP posterior mean and variance at a new query point \(x_*\) by hand.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-kernels-encode-function-shape&quot;&gt;Key Ideas: Kernels Encode Function Shape&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Definition:&lt;/strong&gt; \(f(x) \sim \mathcal{GP}(m(x), k(x, x&apos;))\) means any finite vector \((f(x_1), \dots, f(x_n))^T\) is multivariate normal with covariance \(K_{ij} = k(x_i, x_j)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;RBF kernel:&lt;/strong&gt; \(k_{\text{RBF}}(x, x&apos;) = \sigma_f^2 \exp\!\left(-\frac{(x - x&apos;)^2}{2\ell^2}\right)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Closed-form posterior:&lt;/strong&gt; Given noisy observations \(y = f(X) + \epsilon,\ \epsilon \sim \mathcal{N}(0, \sigma_n^2 I)\):
\(\boldsymbol{\mu}_* = K_* (K + \sigma_n^2 I)^{-1} \mathbf{y}, \qquad \mathbf{\Sigma}_* = K_{**} - K_* (K + \sigma_n^2 I)^{-1} K_*^T.\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter10/gaussian_process_posterior.png&quot; alt=&quot;Gaussian Process Posterior with 95% Credible Band&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 10.1. GP regression with an RBF kernel: uncertainty collapses near data points and expands smoothly across unobserved gaps.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-worked-example-predicting-one-new-point&quot;&gt;1. Worked Example: Predicting One New Point&lt;/h2&gt;

&lt;p&gt;With \(m(x)=0\), RBF kernel (\(\sigma_f=1, \ell=1\)), zero noise, and one datum \((x_1=0, y_1=2.0)\), predict at \(x_*=1\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(K = [1]\), \(K_* = [e^{-0.5}] \approx [0.6065]\), \(K_{**} = [1]\).&lt;/li&gt;
  &lt;li&gt;Posterior mean: \(\mu_* = 0.6065 \times 2.0 \approx 1.213\); posterior variance: \(\Sigma_* = 1 - 0.6065^2 \approx 0.632\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;interactive-lab-explore-gp-kernels--posterior-uncertainty&quot;&gt;Interactive Lab: Explore GP Kernels &amp;amp; Posterior Uncertainty&lt;/h3&gt;

&lt;div style=&quot;margin:1.5rem 0;&quot;&gt;
&lt;iframe src=&quot;/public/interactive/gp_kernel_lab.html&quot; style=&quot;width:100%;height:560px;border:1px solid #ddd;border-radius:10px;background:#fff;&quot; loading=&quot;lazy&quot; title=&quot;Gaussian Process Kernel Lab&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Two-point hand calculation:&lt;/strong&gt; With the same RBF kernel (\(\sigma_f=1, \ell=1, \sigma_n=0\)), compute \(\mu_*\) and \(\Sigma_*\) at \(x_* = 0.5\) given observations \((0, 1)\) and \((1, 1)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Computational scaling:&lt;/strong&gt; Why does exact GP inference cost \(O(n^3)\), and how do inducing points or Hilbert-space GP (HSGP) approximations help?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;PyMC practice:&lt;/strong&gt; Fit a noisy nonlinear curve with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.gp.Marginal&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.gp.cov.Matern52&lt;/code&gt;, then plot 10 posterior function draws.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 9.4: Phễu Neal & Tái tham số hóa Centered vs. Non-Centered</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter09/09_04_neals_funnel_reparameterization/"/>
   <updated>2025-01-09T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter09/09_04_neals_funnel_reparameterization</id>
   <content type="html">&lt;p&gt;Bạn viết một mô hình phân cấp cực kỳ gọn gàng bằng PyMC, bấm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.sample()&lt;/code&gt;, và màn hình lập tức báo &lt;strong&gt;87 divergences&lt;/strong&gt; kèm \(\hat{R} = 1.15\). Dữ liệu không sai, công thức toán không sai — thủ phạm chính là &lt;strong&gt;hình học “Phễu Neal” (Neal’s Funnel)&lt;/strong&gt;, chiếc bẫy kinh điển nhất khi chạy HMC/NUTS trên mô hình đa tầng.&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-thoát-phễu-neal-bằng-tái-tham-số-hóa-non-centered&quot;&gt;Video ngắn: Thoát Phễu Neal bằng Tái tham số hóa Non-Centered&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/neals-funnel-reparam.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 30 giây (có thuyết minh tiếng Việt): so sánh trực quan hạt HMC bị kẹt divergence đỏ ở đáy Phễu Neal (Centered) rồi biến hình sang đám mây tròn trơn tru (Non-Centered).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Hiểu nguồn gốc hình học của &lt;strong&gt;Phễu Neal (Neal’s Funnel)&lt;/strong&gt; khi độ lệch chuẩn liên nhóm \(\tau\) tiến gần 0.&lt;/li&gt;
  &lt;li&gt;Biết cách chuyển đổi chính xác giữa &lt;strong&gt;Centered Parameterization&lt;/strong&gt; và &lt;strong&gt;Non-Centered Parameterization&lt;/strong&gt; mà không làm thay đổi mô hình toán học.&lt;/li&gt;
  &lt;li&gt;Biết quy tắc thực hành: khi nào dùng Non-Centered (dữ liệu ít/nhiễu) và khi nào Centered lại tốt hơn (dữ liệu mỗi nhóm rất lớn).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hai-cách-viết-cùng-một-mô-hình&quot;&gt;Kiến thức cần nhớ: Hai cách viết cùng một Mô hình&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Centered Parameterization (Tham số hóa tâm hóa):&lt;/strong&gt;
\(\theta_j \sim \mathcal{N}(\mu, \tau^2).\)
Khi \(\tau\) nhỏ, cổ phễu co hẹp theo hàm mũ; bước nhảy Leapfrog cố định \(\epsilon\) của HMC bị bật văng khỏi thành phễu gây &lt;strong&gt;divergences&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Non-Centered Parameterization (Tham số hóa phi tâm hóa):&lt;/strong&gt; Tách biến ngẫu nhiên chuẩn tắc độc lập \(z_j \sim \mathcal{N}(0, 1)\) rồi biến đổi tất định:
\(\theta_j = \mu + \tau \cdot z_j.\)
Về mặt xác suất, \(\theta_j\) có &lt;strong&gt;đúng cùng phân phối&lt;/strong&gt; \(\mathcal{N}(\mu, \tau^2)\), nhưng không gian mà bộ lấy mẫu HMC phải duyệt nay là \((z_j, \log \tau)\) — hoàn toàn đẳng hướng và trơn tru!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter09/neals_funnel.png&quot; alt=&quot;So sánh Phễu Neal Centered và hình học sạch Non-Centered&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 9.4. Trái: Centered parameterization tạo ra “cổ phễu” cực hẹp khi \(\log \tau &amp;lt; -2\) khiến HMC sinh divergence. Phải: Non-centered parameterization biến không gian lấy mẫu thành đám mây tròn dễ duyệt.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-ví-dụ-cầm-tay-chỉ-việc-bài-toán-8-schools-trong-pymc&quot;&gt;1. Ví dụ cầm tay chỉ việc: Bài toán 8 Schools trong PyMC&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Dữ liệu 8 Schools kinh điển (Rubin 1981 / Gelman BDA3)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sigma_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eight_schools_nc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;tau&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfCauchy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;tau&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Non-centered parameterization: thoát hoàn toàn Neal&apos;s Funnel
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Deterministic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tau&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_accept&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;2-khi-nào-chọn-centered-vs-non-centered&quot;&gt;2. Khi nào chọn Centered vs. Non-Centered?&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Tình huống dữ liệu&lt;/th&gt;
      &lt;th&gt;Hình học hậu nghiệm&lt;/th&gt;
      &lt;th&gt;Khuyến nghị&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Dữ liệu mỗi nhóm ít, \(\tau\) nhỏ hoặc bất định lớn&lt;/td&gt;
      &lt;td&gt;Cổ phễu sâu (prior chi phối)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Non-Centered&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Dữ liệu mỗi nhóm rất lớn, likelihood sắc nét&lt;/td&gt;
      &lt;td&gt;Dữ liệu ghim chặt \(\theta_j\), \(z_j = (\theta_j - \mu)/\tau\) lại bị méo&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Centered&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tái hiện lỗi và sửa lỗi:&lt;/strong&gt; Chạy bài toán 8 Schools ở trên theo cả hai phiên bản Centered (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;theta = pm.Normal(&quot;theta&quot;, mu, tau, shape=8)&lt;/code&gt;) và Non-Centered. So sánh số lượng divergence, \(\hat{R}\) và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ess_bulk&lt;/code&gt; của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tau&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chứng minh tương đương phân phối:&lt;/strong&gt; Chứng minh rằng nếu \(z \sim \mathcal{N}(0, 1)\) độc lập với \((\mu, \tau)\), thì biến ngẫu nhiên \(\theta = \mu + \tau z\) có phân phối điều kiện \(\theta \mid \mu, \tau \sim \mathcal{N}(\mu, \tau^2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp dụng cho Varying Slopes:&lt;/strong&gt; Viết dạng Non-Centered cho mô hình Varying Slopes ở Bài 9.3 bằng cách dùng ma trận chuẩn tắc \(Z \sim \mathcal{N}(0, 1)\) nhân với nhân tử Cholesky &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chol @ Z&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 9.3: Hệ số góc Biến thiên & Prior LKJ cho Tương quan</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter09/09_03_varying_slopes_lkj/"/>
   <updated>2025-01-09T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter09/09_03_varying_slopes_lkj</id>
   <content type="html">&lt;p&gt;Trong một chuỗi quán cà phê (ví dụ kinh điển của McElreath), quán nào có thời gian chờ buổi sáng vốn đã rất lâu (hệ số chặn \(\alpha_j\) cao) thường lại giảm thời gian chờ mạnh hơn hẳn vào buổi chiều (hệ số góc \(\beta_j\) âm sâu hơn). Nghĩa là &lt;strong&gt;hệ số chặn và hệ số góc không chỉ biến thiên theo nhóm — chúng còn tương quan với nhau&lt;/strong&gt;!&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-hệ-số-góc-biến-thiên--prior-lkjη&quot;&gt;Video ngắn: Hệ số góc biến thiên &amp;amp; Prior LKJ(η)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/varying-slopes-lkj.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 28 giây (có thuyết minh tiếng Việt): đường mật độ LKJ(η) biến đổi khi η tăng 1 → 2 → 6, kết hợp 4 đường hồi quy xoay độ dốc theo tương quan ρ từ −0.85 sang +0.85.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Mở rộng mô hình phân cấp sang &lt;strong&gt;Varying Intercepts &amp;amp; Varying Slopes&lt;/strong&gt; dùng phân phối chuẩn đa biến (Multivariate Normal).&lt;/li&gt;
  &lt;li&gt;Hiểu cấu trúc phân rã ma trận hiệp phương sai \(\mathbf{\Sigma} = \operatorname{diag}(\boldsymbol{\sigma})\,\mathbf{R}\,\operatorname{diag}(\boldsymbol{\sigma})\) và vai trò của &lt;strong&gt;prior LKJ(\(\eta\))&lt;/strong&gt; cho ma trận tương quan \(\mathbf{R}\).&lt;/li&gt;
  &lt;li&gt;Nắm lợi ích của &lt;strong&gt;tương quan chéo (borrowing strength across parameters)&lt;/strong&gt; trong suy luận phân cấp.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ma-trận-hiệp-phương-sai-và-lkj-prior&quot;&gt;Kiến thức cần nhớ: Ma trận Hiệp phương sai và LKJ Prior&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình song biến cho từng nhóm \(j\):&lt;/strong&gt;
\(\begin{pmatrix} \alpha_j \\ \beta_j \end{pmatrix} \sim \mathcal{N}\!\left(\begin{pmatrix} \mu_\alpha \\ \mu_\beta \end{pmatrix},\ \mathbf{\Sigma}\right), \qquad \mathbf{\Sigma} = \begin{pmatrix} \sigma_\alpha &amp;amp; 0 \\ 0 &amp;amp; \sigma_\beta \end{pmatrix} \begin{pmatrix} 1 &amp;amp; \rho \\ \rho &amp;amp; 1 \end{pmatrix} \begin{pmatrix} \sigma_\alpha &amp;amp; 0 \\ 0 &amp;amp; \sigma_\beta \end{pmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;LKJ Correlation Prior \(\mathbf{R} \sim \operatorname{LKJ}(\eta)\):&lt;/strong&gt; Trong 2 chiều, mật độ tỷ lệ với \((1 - \rho^2)^{\eta - 1}\):
    &lt;ul&gt;
      &lt;li&gt;\(\eta = 1\): phân phối đều trên \([-1, 1]\) (mọi mức tương quan đều khả dĩ như nhau).&lt;/li&gt;
      &lt;li&gt;\(\eta = 2\): ưu tiên nhẹ các tương quan vừa phải, đẩy nhẹ xác suất ra khỏi hai cực đoan \(\pm 1\) (khuyến nghị mặc định trong PyMC/Stan).&lt;/li&gt;
      &lt;li&gt;\(\eta = 4\) trở lên: ép mạnh ma trận tương quan về gần ma trận đơn vị.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter09/varying_slopes_lkj.png&quot; alt=&quot;Prior LKJ và các đường hồi quy có hệ số chặn &amp;amp; hệ số góc tương quan âm&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 9.3. Trái: phân phối LKJ trên \(\rho\) với \(\eta = 1, 2, 4\). Phải: 4 nhóm có hệ số chặn \(\alpha_j\) và độ dốc \(\beta_j\) tương quan âm — nhóm xuất phát càng cao thì độ dốc càng thoải.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-cài-đặt-chuẩn-bằng-pmlkjcholeskycov-trong-pymc&quot;&gt;1. Cài đặt chuẩn bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.LKJCholeskyCov&lt;/code&gt; trong PyMC&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;varying_slopes_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;chol&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;corr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LKJCholeskyCov&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;chol&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_dist&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Exponential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;compute_corr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mu_ab&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mu_ab&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ab&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MvNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ab&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_ab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chol&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chol&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_groups&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;group_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;group_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Exponential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giải thích mật độ LKJ:&lt;/strong&gt; Với \(\eta = 2\) trong 2 chiều, hãy tính tỷ số mật độ giữa \(\rho = 0\) và \(\rho = 0.8\) bằng công thức \(p(\rho) \propto (1 - \rho^2)^{\eta - 1}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tại sao không đặt prior độc lập cho \(\alpha_j\) và \(\beta_j\)?&lt;/strong&gt; Hãy nêu một ví dụ thực tế (y học, giáo dục hoặc kinh doanh) trong đó việc ước lượng thêm tương quan \(\rho\) giúp cải thiện dự báo cho nhóm ít dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra ma trận tương quan hậu nghiệm:&lt;/strong&gt; Từ mô hình PyMC trên, viết mã ArviZ trích xuất 95% HDI của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;corr[0, 1]&lt;/code&gt; để kiểm tra xem tương quan giữa \(\alpha_j\) và \(\beta_j\) có khác 0 một cách rõ rệt hay không.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 9.2: Mô hình Hệ số chặn Biến thiên (Varying Intercepts)</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter09/09_02_varying_intercepts/"/>
   <updated>2025-01-09T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter09/09_02_varying_intercepts</id>
   <content type="html">&lt;p&gt;Khi khảo sát ảnh hưởng của số giờ tự học \(x\) đến điểm thi \(y\) trên 30 lớp học khác nhau, mỗi lớp có một mặt bằng nền \(\alpha_j\) riêng (do giáo viên, điều kiện cơ sở vật chất), nhưng tốc độ tăng điểm theo mỗi giờ học \(\beta\) có thể khá tương đồng. &lt;strong&gt;Mô hình hệ số chặn biến thiên (Varying Intercepts)&lt;/strong&gt; cho phép mỗi nhóm có đường hồi quy song song riêng với độ cao \(\alpha_j\) được học chung qua phân phối quần thể.&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-hệ-số-chặn-biến-thiên--chỉ-số-icc&quot;&gt;Video ngắn: Hệ số chặn biến thiên &amp;amp; Chỉ số ICC&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/varying-intercepts-icc.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 23 giây (có thuyết minh tiếng Việt): 4 đường hồi quy song song tách nhau theo độ lệch liên nhóm σ_α cùng đồng hồ chỉ số tương quan nội nhóm ICC cập nhật theo thời gian thực.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Viết đầy đủ mô hình sinh dữ liệu cho hồi quy tuyến tính có hệ số chặn biến thiên.&lt;/li&gt;
  &lt;li&gt;Hiểu cách tách tổng phương sai thành phương sai &lt;strong&gt;giữa các nhóm&lt;/strong&gt; (\(\sigma_\alpha^2\)) và phương sai &lt;strong&gt;trong từng nhóm&lt;/strong&gt; (\(\sigma^2\)) qua hệ số tương quan nội nhóm &lt;strong&gt;ICC&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Cài đặt và diễn giải mô hình Varying Intercepts bằng PyMC.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hệ-số-tương-quan-nội-nhóm-icc&quot;&gt;Kiến thức cần nhớ: Hệ số tương quan nội nhóm (ICC)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình sinh dữ liệu:&lt;/strong&gt;
\(y_i \sim \mathcal{N}(\mu_i, \sigma^2), \qquad \mu_i = \alpha_{g[i]} + \beta x_i, \qquad \alpha_j \sim \mathcal{N}(\mu_\alpha, \sigma_\alpha^2).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Siêu tiền nghiệm:&lt;/strong&gt; \(\mu_\alpha \sim \mathcal{N}(0, 10),\ \sigma_\alpha \sim \operatorname{HalfNormal}(5),\ \beta \sim \mathcal{N}(0, 5),\ \sigma \sim \operatorname{HalfNormal}(5)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Intraclass Correlation Coefficient (ICC):&lt;/strong&gt;
\(\text{ICC} = \frac{\sigma_\alpha^2}{\sigma_\alpha^2 + \sigma^2}.\)
ICC đo tỷ lệ phương sai của \(y\) đến từ sự khác biệt giữa các nhóm. Nếu \(\text{ICC} \approx 0.45\), gần một nửa biến thiên đến từ cấp độ nhóm — bỏ qua cấu trúc nhóm sẽ làm sai lệch nghiêm trọng độ bất định!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter09/varying_intercepts.png&quot; alt=&quot;Mô hình Varying Intercepts với hệ số góc chung beta và nền nhóm alpha_j&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 9.2. Các đường hồi quy có chung độ dốc \(\beta = 1.6\) nhưng khác nhau ở hệ số chặn \(\alpha_j\) theo từng nhóm.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-ví-dụ-cầm-tay-chỉ-việc--cài-đặt-pymc&quot;&gt;1. Ví dụ cầm tay chỉ việc &amp;amp; Cài đặt PyMC&lt;/h2&gt;

&lt;p&gt;Giả sử ta có 4 trường học với \(\sigma_\alpha = 3.0\) và nhiễu trong trường \(\sigma = 1.0\). Khi đó \(\text{ICC} = \frac{3^2}{3^2 + 1^2} = 0.90\) — tức 90% biến thiên điểm nền nằm ở sự chênh lệch giữa các trường.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;varying_intercept_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Hyperpriors
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mu_a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mu_a&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma_a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma_a&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Varying intercepts
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma_a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_groups&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Shared slope &amp;amp; noise
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;group_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_accept&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính ICC:&lt;/strong&gt; Một mô hình cho hậu nghiệm \(\sigma_\alpha = 1.5\) và \(\sigma = 2.0\). Tính ICC và giải thích ý nghĩa thực tế của con số này.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dự báo cho nhóm mới hoàn toàn:&lt;/strong&gt; Nếu xuất hiện một lớp học mới thứ 31 chưa có học sinh nào trong tập huấn luyện, bạn sẽ rút \(\alpha_{31}\) từ đâu để dự báo hậu nghiệm?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh với dummy variable:&lt;/strong&gt; Vì sao mô hình Varying Intercepts thường cho dự báo ngoài mẫu tốt hơn hồi quy thường dùng biến giả (one-hot encoding) cho từng nhóm?&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 9.1: Pooling, No-Pooling & Hiệu ứng Co cụm (Partial Pooling & Shrinkage)</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter09/09_01_partial_pooling_shrinkage/"/>
   <updated>2025-01-09T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter09/09_01_partial_pooling_shrinkage</id>
   <content type="html">&lt;p&gt;Giả sử bạn đánh giá tỷ lệ hồi phục sau phẫu thuật tim của 8 bệnh viện. Bệnh viện G1 chỉ mới mổ 5 ca và thành công 4 ca (tỷ lệ thô \(80\%\)), trong khi bệnh viện G8 đã mổ 120 ca và thành công 59 ca (\(49.2\%\)). Bạn có thực sự tin G1 giỏi gần gấp đôi G8, hay con số 80% chỉ là nhiễu của cỡ mẫu quá nhỏ? &lt;strong&gt;Mô hình phân cấp (Hierarchical / Multilevel Models)&lt;/strong&gt; giải bài toán này một cách tự nhiên bằng cơ chế &lt;strong&gt;chia sẻ thông tin (partial pooling)&lt;/strong&gt; và &lt;strong&gt;hiệu ứng co cụm (shrinkage)&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-hiệu-ứng-co-cụm-shrinkage-trong-mô-hình-phân-cấp&quot;&gt;Video ngắn: Hiệu ứng Co cụm (Shrinkage) trong Mô hình Phân cấp&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/hierarchical-shrinkage.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video minh họa trực quan cách 8 nhóm có cỡ mẫu khác nhau tự động “co” về trung bình quần thể \(\mu\) khi thay đổi độ phân tán liên nhóm \(\tau\): nhóm ít dữ liệu chịu lực kéo mạnh hơn hẳn nhóm nhiều dữ liệu.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;So sánh ba chiến lược ước lượng cho dữ liệu phân nhóm: &lt;strong&gt;Complete Pooling&lt;/strong&gt;, &lt;strong&gt;No Pooling&lt;/strong&gt;, và &lt;strong&gt;Partial Pooling&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Hiểu cơ chế toán học của &lt;strong&gt;hyperprior&lt;/strong&gt; và &lt;strong&gt;shrinkage&lt;/strong&gt;: nhóm càng ít dữ liệu hoặc càng cực đoan càng bị kéo mạnh về trung bình quần thể.&lt;/li&gt;
  &lt;li&gt;Nhận ra vì sao &lt;em&gt;shrinkage&lt;/em&gt; giúp giảm sai số dự báo ngoài mẫu (nghịch lý Stein).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-cấu-trúc-2-tầng-của-mô-hình-phân-cấp&quot;&gt;Kiến thức cần nhớ: Cấu trúc 2 Tầng của Mô hình Phân cấp&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tầng quan sát (Likelihood):&lt;/strong&gt; \(y_j \sim \operatorname{Binomial}(n_j, \theta_j)\) với mỗi nhóm \(j = 1, \dots, J\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng quần thể (Adaptive Prior):&lt;/strong&gt; Thay vì cố định prior cho từng \(\theta_j\), ta coi mọi \(\theta_j\) cùng rút từ một phân phối chung có siêu tham số (hyperparameters) chưa biết — ví dụ \(\operatorname{logit}(\theta_j) \sim \mathcal{N}(\mu, \tau^2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng siêu tiền nghiệm (Hyperprior):&lt;/strong&gt; \(\mu \sim \mathcal{N}(0, 1.5), \quad \tau \sim \operatorname{HalfNormal}(1)\). Khi \(\tau \to 0\) ta quay về &lt;em&gt;complete pooling&lt;/em&gt;; khi \(\tau \to \infty\) ta quay về &lt;em&gt;no pooling&lt;/em&gt;. Dữ liệu của &lt;strong&gt;tất cả các nhóm&lt;/strong&gt; cùng nhau ước lượng \(\tau\)!&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1-ví-dụ-cầm-tay-chỉ-việc-phép-tính-co-cụm-trên-8-bệnh-viện&quot;&gt;1. Ví dụ cầm tay chỉ việc: Phép tính co cụm trên 8 bệnh viện&lt;/h2&gt;

&lt;p&gt;Trong mô hình liên hợp phân cấp Beta–Binomial (Kruschke, Chương 9) với trung bình quần thể \(\mu = 0.50\) và độ tập trung ước lượng \(\kappa = 12\) (tương đương 12 ca “ảo” từ quần thể), ước lượng hậu nghiệm của nhóm \(j\) có \(k_j\) ca thành công trên \(n_j\) ca là trung bình trọng số:&lt;/p&gt;

\[\hat{\theta}_j = \frac{k_j + \kappa \mu}{n_j + \kappa} = \frac{n_j}{n_j + \kappa}\cdot \frac{k_j}{n_j} + \frac{\kappa}{n_j + \kappa}\cdot \mu.\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bệnh viện G1 (\(n_1 = 5, k_1 = 4 \implies 80\%\)):&lt;/strong&gt; \(\hat{\theta}_1 = \frac{4 + 12(0.5)}{5 + 12} = \frac{10}{17} \approx 58.8\%\) — bị co mạnh tới &lt;strong&gt;21.2 điểm phần trăm&lt;/strong&gt; về phía \(50\%\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bệnh viện G8 (\(n_8 = 120, k_8 = 59 \implies 49.2\%\)):&lt;/strong&gt; \(\hat{\theta}_8 = \frac{59 + 6}{120 + 12} = \frac{65}{132} \approx 49.24\%\) — hầu như không đổi vì dữ liệu riêng đã rất dồi dào.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter09/partial_pooling_shrinkage.png&quot; alt=&quot;Hiệu ứng Shrinkage trên 8 nhóm có cỡ mẫu khác nhau&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 9.1. Mũi tên chỉ hướng co cụm từ tỷ lệ thô (no pooling, chấm đỏ) sang ước lượng phân cấp (partial pooling, ô vuông xanh). Các nhóm ít mẫu (G1–G4) co mạnh hơn hẳn các nhóm lớn (G7–G8).&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;tương-tác-trải-nghiệm-partial-pooling--shrinkage&quot;&gt;Tương tác: Trải nghiệm Partial Pooling &amp;amp; Shrinkage&lt;/h3&gt;

&lt;div data-demo=&quot;pooling-explainer&quot; data-data=&quot;schools&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính tay hệ số co cụm:&lt;/strong&gt; Với \(\mu = 0.50, \kappa = 12\), tính ước lượng partial pooling cho nhóm G2 (\(n_2 = 8, k_2 = 2\)) và so sánh với trường hợp \(\kappa = 40\) (các nhóm rất đồng nhất).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hai cực trị của \(\tau\):&lt;/strong&gt; Giải thích bằng công thức điều gì xảy ra với \(\hat{\theta}_j\) khi \(\tau \to 0\) và khi \(\tau \to \infty\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô phỏng sai số dự báo:&lt;/strong&gt; Tạo 20 nhóm có xác suất thực \(\theta_j \sim \operatorname{Beta}(10, 10)\), mỗi nhóm rút \(n_j = 8\) mẫu. Tính tổng sai số bình phương (MSE) của No-Pooling, Complete-Pooling và Partial-Pooling so với \(\theta_j\) thực.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 9.4: Neal's Funnel & Centered vs. Non-Centered Reparameterization</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter09/09_04_neals_funnel_reparameterization/"/>
   <updated>2025-01-09T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter09/09_04_neals_funnel_reparameterization</id>
   <content type="html">&lt;p&gt;You write a clean hierarchical model in PyMC, hit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.sample()&lt;/code&gt;, and suddenly see &lt;strong&gt;87 divergences&lt;/strong&gt; and \(\hat{R} = 1.15\). Neither your data nor your math is wrong—you have met &lt;strong&gt;Neal’s Funnel&lt;/strong&gt;, the most famous geometric trap in HMC/NUTS sampling of multilevel models.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Diagnose why &lt;strong&gt;Neal’s Funnel&lt;/strong&gt; causes HMC divergences when group-level scale \(\tau\) approaches 0.&lt;/li&gt;
  &lt;li&gt;Switch cleanly between &lt;strong&gt;Centered&lt;/strong&gt; and &lt;strong&gt;Non-Centered&lt;/strong&gt; parameterizations without changing the statistical model.&lt;/li&gt;
  &lt;li&gt;Know when each parameterization excels (small vs. large per-group sample sizes).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-same-model-different-sampling-geometry&quot;&gt;Key Ideas: Same Model, Different Sampling Geometry&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Centered:&lt;/strong&gt; \(\theta_j \sim \mathcal{N}(\mu, \tau^2)\). As \(\tau \to 0\), the posterior pinches into an exponentially narrow neck that breaks fixed-step-size Leapfrog integration.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Non-Centered:&lt;/strong&gt; Sample standard normal offsets \(z_j \sim \mathcal{N}(0, 1)\) and define \(\theta_j = \mu + \tau z_j\) deterministically. The mathematical distribution of \(\theta_j\) is identical, but the sampler explores a smooth, isotropic Gaussian cloud!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter09/neals_funnel.png&quot; alt=&quot;Neal&apos;s Funnel Centered vs Non-Centered&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 9.4. Left: centered parameterization creates a narrow funnel neck for small \(\tau\). Right: non-centered parameterization yields clean, divergence-free geometry.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-worked-example-eight-schools-in-pymc&quot;&gt;1. Worked Example: Eight Schools in PyMC&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sigma_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eight_schools_nc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;tau&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfCauchy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;tau&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Deterministic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tau&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_accept&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Reproduce and fix:&lt;/strong&gt; Run the Eight Schools model with both centered and non-centered parameterizations and compare divergences, \(\hat{R}\), and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ess_bulk&lt;/code&gt; for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tau&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Distributional equivalence:&lt;/strong&gt; Prove that if \(z \sim \mathcal{N}(0, 1)\) independently of \((\mu, \tau)\), then \(\theta = \mu + \tau z \mid \mu, \tau \sim \mathcal{N}(\mu, \tau^2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multivariate extension:&lt;/strong&gt; Write the non-centered form for varying slopes using a standard normal matrix \(Z\) multiplied by the Cholesky factor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chol&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 9.3: Varying Slopes & LKJ Correlation Priors</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter09/09_03_varying_slopes_lkj/"/>
   <updated>2025-01-09T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter09/09_03_varying_slopes_lkj</id>
   <content type="html">&lt;p&gt;In McElreath’s classic café waiting-time example, cafés that are busiest in the morning (high intercept \(\alpha_j\)) also experience the sharpest afternoon drop in wait time (steeper negative slope \(\beta_j\)). Not only do intercepts and slopes vary across groups—they &lt;strong&gt;covary&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Extend hierarchical regression to &lt;strong&gt;Varying Intercepts and Slopes&lt;/strong&gt; via a multivariate normal population prior.&lt;/li&gt;
  &lt;li&gt;Understand covariance decomposition \(\mathbf{\Sigma} = \operatorname{diag}(\boldsymbol{\sigma})\,\mathbf{R}\,\operatorname{diag}(\boldsymbol{\sigma})\) and the &lt;strong&gt;LKJ(\(\eta\))&lt;/strong&gt; correlation prior.&lt;/li&gt;
  &lt;li&gt;Implement correlated varying effects in PyMC with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.LKJCholeskyCov&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-covariance--lkj-priors&quot;&gt;Key Ideas: Covariance &amp;amp; LKJ Priors&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bivariate group prior:&lt;/strong&gt; \(\begin{pmatrix} \alpha_j \\ \beta_j \end{pmatrix} \sim \mathcal{N}\!\left(\begin{pmatrix} \mu_\alpha \\ \mu_\beta \end{pmatrix}, \mathbf{\Sigma}\right)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;LKJ(\(\eta\)) prior on correlation \(\mathbf{R}\):&lt;/strong&gt; In 2D, \(p(\rho) \propto (1 - \rho^2)^{\eta - 1}\). \(\eta = 1\) is flat on \([-1, 1]\); \(\eta = 2\) gently regularizes away from \(\pm 1\); larger \(\eta\) shrinks toward the identity matrix.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter09/varying_slopes_lkj.png&quot; alt=&quot;LKJ Priors and Correlated Varying Slopes&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 9.3. Left: LKJ densities for \(\eta \in \{1, 2, 4\}\). Right: negatively correlated group intercepts and slopes.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-pymc-implementation&quot;&gt;1. PyMC Implementation&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;varying_slopes_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;chol&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;corr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LKJCholeskyCov&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;chol&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_dist&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Exponential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;compute_corr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mu_ab&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mu_ab&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ab&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MvNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ab&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_ab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chol&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chol&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_groups&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;group_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;group_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Exponential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;LKJ density ratio:&lt;/strong&gt; For \(\eta = 2\) in 2D, compute the density ratio between \(\rho = 0\) and \(\rho = 0.8\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Borrowing strength across parameters:&lt;/strong&gt; Give a real-world example where modeling \(\operatorname{Corr}(\alpha_j, \beta_j)\) improves small-group estimates.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior check:&lt;/strong&gt; Write an ArviZ snippet to extract the 95% HDI of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;corr[0, 1]&lt;/code&gt; from the PyMC model above.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 9.2: Varying Intercepts Models</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter09/09_02_varying_intercepts/"/>
   <updated>2025-01-09T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter09/09_02_varying_intercepts</id>
   <content type="html">&lt;p&gt;When studying how study hours \(x\) affect test scores \(y\) across 30 classrooms, each classroom has its own baseline \(\alpha_j\) while sharing a similar learning slope \(\beta\). &lt;strong&gt;Varying-intercepts models&lt;/strong&gt; give every group its own parallel regression line while partially pooling all baselines through a shared population distribution.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Specify a generative varying-intercepts Bayesian linear regression model.&lt;/li&gt;
  &lt;li&gt;Decompose variance into between-group (\(\sigma_\alpha^2\)) and within-group (\(\sigma^2\)) components using the &lt;strong&gt;Intraclass Correlation Coefficient (ICC)&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Implement and interpret varying intercepts in PyMC.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-variance-decomposition--icc&quot;&gt;Key Ideas: Variance Decomposition &amp;amp; ICC&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Generative model:&lt;/strong&gt;
\(y_i \sim \mathcal{N}(\mu_i, \sigma^2), \qquad \mu_i = \alpha_{g[i]} + \beta x_i, \qquad \alpha_j \sim \mathcal{N}(\mu_\alpha, \sigma_\alpha^2).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ICC:&lt;/strong&gt; \(\text{ICC} = \frac{\sigma_\alpha^2}{\sigma_\alpha^2 + \sigma^2}\) measures the fraction of total outcome variance explained by group membership.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter09/varying_intercepts.png&quot; alt=&quot;Varying Intercepts Model&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 9.2. Parallel group regression lines sharing slope \(\beta = 1.6\) with group-specific baselines \(\alpha_j\).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-pymc-implementation&quot;&gt;1. PyMC Implementation&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;varying_intercept_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mu_a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mu_a&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma_a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma_a&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma_a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_groups&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;group_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_accept&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute ICC:&lt;/strong&gt; Given posterior estimates \(\sigma_\alpha = 1.5\) and \(\sigma = 2.0\), compute the ICC and interpret it.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Predicting an unseen group:&lt;/strong&gt; How do you draw posterior predictive values for a brand-new classroom #31 with zero observations?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Comparison with dummy variables:&lt;/strong&gt; Explain why varying intercepts outperform unregularized one-hot group indicators out of sample.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 9.1: Pooling, No-Pooling & Shrinkage (Partial Pooling)</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter09/09_01_partial_pooling_shrinkage/"/>
   <updated>2025-01-09T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter09/09_01_partial_pooling_shrinkage</id>
   <content type="html">&lt;p&gt;Suppose you evaluate heart-surgery recovery rates across 8 hospitals. Hospital G1 performed only 5 surgeries and succeeded in 4 (raw rate \(80\%\)), while Hospital G8 performed 120 surgeries with 59 successes (\(49.2\%\)). Is G1 truly nearly twice as skilled as G8, or is 80% mostly small-sample noise? &lt;strong&gt;Hierarchical (Multilevel) Bayesian models&lt;/strong&gt; resolve this gracefully through &lt;strong&gt;partial pooling&lt;/strong&gt; and &lt;strong&gt;shrinkage&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;short-video-shrinkage-in-hierarchical-models&quot;&gt;Short Video: Shrinkage in Hierarchical Models&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/hierarchical-shrinkage.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Motion-first visualization showing 8 groups shrinking toward the population mean \(\mu\) as between-group spread \(\tau\) varies—with smaller-sample groups pulled much more strongly than large-sample groups (Vietnamese narration).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Contrast &lt;strong&gt;Complete Pooling&lt;/strong&gt;, &lt;strong&gt;No Pooling&lt;/strong&gt;, and &lt;strong&gt;Partial Pooling&lt;/strong&gt; for grouped data.&lt;/li&gt;
  &lt;li&gt;Understand &lt;strong&gt;hyperpriors&lt;/strong&gt; and &lt;strong&gt;shrinkage&lt;/strong&gt;: why small or extreme groups shrink harder toward the population mean.&lt;/li&gt;
  &lt;li&gt;Recognize how partial pooling improves out-of-sample predictive accuracy.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-two-level-generative-structure&quot;&gt;Key Ideas: Two-Level Generative Structure&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Observation level:&lt;/strong&gt; \(y_j \sim \operatorname{Binomial}(n_j, \theta_j)\) for group \(j = 1, \dots, J\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Population level (adaptive prior):&lt;/strong&gt; \(\operatorname{logit}(\theta_j) \sim \mathcal{N}(\mu, \tau^2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hyperpriors:&lt;/strong&gt; \(\mu \sim \mathcal{N}(0, 1.5),\ \tau \sim \operatorname{HalfNormal}(1)\). As \(\tau \to 0\) we recover complete pooling; as \(\tau \to \infty\) we recover no pooling. All groups jointly inform \(\tau\)!&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1-worked-example-shrinkage-across-8-hospitals&quot;&gt;1. Worked Example: Shrinkage Across 8 Hospitals&lt;/h2&gt;

&lt;p&gt;In a Beta–Binomial hierarchy (Kruschke, Ch. 9) with population mean \(\mu = 0.50\) and estimated concentration \(\kappa = 12\), each group’s posterior mean is a precision-weighted average:&lt;/p&gt;

\[\hat{\theta}_j = \frac{k_j + \kappa \mu}{n_j + \kappa} = \frac{n_j}{n_j + \kappa}\cdot \frac{k_j}{n_j} + \frac{\kappa}{n_j + \kappa}\cdot \mu.\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hospital G1 (\(n_1 = 5, k_1 = 4 \implies 80\%\)):&lt;/strong&gt; \(\hat{\theta}_1 = \frac{4 + 6}{5 + 12} \approx 58.8\%\)—shrunk by &lt;strong&gt;21.2 percentage points&lt;/strong&gt; toward \(50\%\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hospital G8 (\(n_8 = 120, k_8 = 59 \implies 49.2\%\)):&lt;/strong&gt; \(\hat{\theta}_8 = \frac{59 + 6}{120 + 12} \approx 49.24\%\)—barely moved because its own data dominate.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter09/partial_pooling_shrinkage.png&quot; alt=&quot;Hierarchical Shrinkage across 8 groups&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 9.1. Arrows show shrinkage from raw group rates (red circles) to partial-pooling estimates (blue squares). Smaller groups shrink far more strongly.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;interactive-explore-partial-pooling--shrinkage&quot;&gt;Interactive: Explore Partial Pooling &amp;amp; Shrinkage&lt;/h3&gt;

&lt;div data-demo=&quot;pooling-explainer&quot; data-data=&quot;schools&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hand calculation:&lt;/strong&gt; With \(\mu = 0.50, \kappa = 12\), compute the partial-pooling estimate for G2 (\(n_2 = 8, k_2 = 2\)) and compare it to \(\kappa = 40\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Limiting cases:&lt;/strong&gt; Explain mathematically what happens to \(\hat{\theta}_j\) as \(\tau \to 0\) and as \(\tau \to \infty\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Simulation study:&lt;/strong&gt; Simulate 20 groups with true \(\theta_j \sim \operatorname{Beta}(10, 10)\) and \(n_j = 8\) trials each; compare total MSE for no-pooling, complete-pooling, and partial-pooling estimators.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 8.4: Bayesian Decision Analysis - From Inference to Action</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter08/08_04_decision_analysis/"/>
   <updated>2025-01-05T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter08/08_04_decision_analysis</id>
   <content type="html">&lt;p&gt;Một mô hình Bayes xuất sắc cho bạn biết: &lt;em&gt;“Xác suất khách hàng rời bỏ dịch vụ là 35%”&lt;/em&gt;, hoặc &lt;em&gt;“Xác suất phương án B tốt hơn phương án A là 72%”&lt;/em&gt;. Nhưng đến đây công việc vẫn chưa xong — người quản lý vẫn phải chọn &lt;strong&gt;một hành động cụ thể&lt;/strong&gt;: có gửi ưu đãi giữ chân hay không, có triển khai tính năng B cho toàn bộ người dùng hay không? Khi chi phí của sai lầm dương tính giả và âm tính giả chênh lệch nhau 10 lần, ngưỡng mặc định 50% trở thành sai lầm đắt giá.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phân tích quyết định Bayes (Bayesian Decision Analysis)&lt;/strong&gt; — nền tảng từ Abraham Wald và Leonard Savage — khép lại toàn bộ vòng tròn suy luận: kết hợp trực tiếp phân phối hậu nghiệm \(p(\theta \mid y)\) với &lt;strong&gt;hàm tổn thất (loss function)&lt;/strong&gt; \(L(a, \theta)\) để tìm hành động tối ưu \(a^*\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài học này, bạn sẽ biết cách chuyển kết quả suy luận Bayes thành hành động cụ thể dưới độ bất định thông qua hàm mất mát (loss function), mất mát kỳ vọng (expected loss) và giá trị thông tin (value of information). Trọng tâm của bài là phân biệt hai câu hỏi khác nhau: phân phối hậu nghiệm trả lời “ta tin điều gì?”, còn lý thuyết quyết định trả lời “ta nên làm gì?” khi mỗi lựa chọn đi kèm chi phí sai lầm không đối xứng.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hàm-tổn-thất-tổn-thất-hậu-nghiệm-kỳ-vọng-và-giá-trị-thông-tin&quot;&gt;Kiến thức cần nhớ: Hàm tổn thất, Tổn thất hậu nghiệm kỳ vọng và Giá trị thông tin&lt;/h2&gt;

&lt;p&gt;Chuyển từ suy luận sang hành động dựa trên ba trụ cột toán học:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Nguyên tắc tối thiểu hóa tổn thất hậu nghiệm kỳ vọng (Bayes Optimal Action):&lt;/strong&gt; Với mỗi hành động ứng viên \(a\), ta tính kỳ vọng tổn thất trên toàn bộ phân phối hậu nghiệm: \(\mathbb{E}_{\theta \mid y}[L(a, \theta)] = \int L(a, \theta) p(\theta \mid y)\,d\theta\) và chọn \(a^* = \arg\min_a \mathbb{E}_{\theta \mid y}[L(a, \theta)]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ngưỡng quyết định từ chi phí bất đối xứng:&lt;/strong&gt; Trong bài toán quyết định nhị phân (hành động hay không hành động), nếu chi phí báo động giả là \(C_{\text{FP}}\) và chi phí bỏ sót ca thật là \(C_{\text{FN}}\), ngưỡng xác suất hậu nghiệm tối ưu không phải \(0.50\) mà chính xác là \(p^* = \frac{C_{\text{FP}}}{C_{\text{FP}} + C_{\text{FN}}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giá trị kỳ vọng của thông tin (EVPI / EVSI):&lt;/strong&gt; Cho phép định lượng bằng tiền xem việc thu thập thêm dữ liệu (chạy thí nghiệm A/B lâu hơn, làm thêm xét nghiệm y khoa) có thực sự đáng chi phí hay không.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-suy-luận-không-đồng-nghĩa-với-quyết-định&quot;&gt;1. Suy luận không đồng nghĩa với quyết định&lt;/h2&gt;

&lt;p&gt;Một phân phối hậu nghiệm rất sắc nét vẫn chưa tự động xác định được hành động đúng, vì quyết định còn phụ thuộc vào hệ quả của từng loại sai lầm. Cùng một xác suất hậu nghiệm có thể dẫn tới hai hành động khác nhau khi cấu trúc thiệt hại thay đổi. Vì vậy, phân tích quyết định (decision analysis) là bước cuối cùng không thể thiếu của quy trình Bayes.&lt;/p&gt;

&lt;p&gt;Khung chuẩn gồm bốn thành phần: tập hành động \(a\in\mathcal A\), trạng thái thế giới \(\theta\), phân phối hậu nghiệm \(p(\theta\mid y)\) và hàm mất mát \(L(a,\theta)\). Quy tắc hành động Bayes (Bayes action) chọn hành động tối thiểu hóa mất mát kỳ vọng hậu nghiệm:&lt;/p&gt;

\[a^*(y)=\arg\min_{a\in\mathcal A} \mathbb E[L(a,\theta)\mid y]
=\arg\min_{a\in\mathcal A}\int L(a,\theta)p(\theta\mid y)\,d\theta.\]

&lt;h2 id=&quot;2-quy-tắc-ngưỡng-từ-chi-phí-bất-đối-xứng&quot;&gt;2. Quy tắc ngưỡng từ chi phí bất đối xứng&lt;/h2&gt;

&lt;p&gt;Xét bài toán cảnh báo rủi ro với hai hành động: phát cảnh báo (\(a_1\)) và không cảnh báo (\(a_0\)). Gọi \(q=P(H_1\mid y)\) là xác suất hậu nghiệm xảy ra sự cố, \(L_{FP}\) là chi phí báo động giả và \(L_{FN}\) là chi phí bỏ sót sự cố. Khi đó, rủi ro kỳ vọng của mỗi hành động là:&lt;/p&gt;

\[R(a_1\mid y)=L_{FP}(1-q),\qquad R(a_0\mid y)=L_{FN}q.\]

&lt;p&gt;Ta chọn phát cảnh báo khi \(R(a_1\mid y)&amp;lt;R(a_0\mid y)\), tương đương:&lt;/p&gt;

\[q&amp;gt;\frac{L_{FP}}{L_{FP}+L_{FN}}.\]

&lt;p&gt;Với \(L_{FP}=5\) và \(L_{FN}=40\), ngưỡng quyết định chỉ là \(q^*=5/45\approx 0.111\). Điều này cho thấy quyết định tối ưu rất nhạy với cấu trúc chi phí, ngay cả khi phân phối hậu nghiệm không hề thay đổi.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/chapter08_expected_loss_threshold.png&quot; alt=&quot;Expected loss threshold rule&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;21-ý-nghĩa-nghiệp-vụ&quot;&gt;2.1. Ý nghĩa nghiệp vụ&lt;/h3&gt;

&lt;p&gt;Nếu tổn thất của việc bỏ sót sự cố lớn hơn nhiều lần so với báo động giả, tổ chức nên cảnh báo sớm hơn — tức sử dụng ngưỡng xác suất hậu nghiệm thấp hơn. Ngược lại, nếu báo động giả gây tốn kém lớn, ngưỡng hậu nghiệm cần được nâng cao để tránh can thiệp quá mức. Vì vậy, ngưỡng quyết định tối ưu không phải một hằng số phổ quát mà là hàm của cấu trúc mất mát trong từng bối cảnh cụ thể.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-ngưỡng-quyết-định-trong-thử-nghiệm-ab&quot;&gt;Thử nghiệm: Ngưỡng quyết định trong thử nghiệm A/B&lt;/h3&gt;

&lt;p&gt;Thêm từng lô 150 người dùng, theo dõi \(\pi = P(p &amp;gt; p_0)\) và so sánh với ngưỡng \(c_{fp}/(c_{fp} + c_{fn})\).&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;decision-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;threshold&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-hàm-mất-mát-và-điểm-tóm-tắt-hậu-nghiệm&quot;&gt;3. Hàm mất mát và điểm tóm tắt hậu nghiệm&lt;/h2&gt;

&lt;p&gt;Trong bài toán ước lượng điểm, việc chọn trung bình (mean), trung vị (median) hay mốt (mode) không phải là sở thích trình bày, mà xuất phát trực tiếp từ hàm mất mát được giả định:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Mất mát bình phương \(L(\hat\theta,\theta)=(\hat\theta-\theta)^2\) → tối ưu là trung bình hậu nghiệm (posterior mean),&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Mất mát trị tuyệt đối $$L(\hat\theta,\theta)=&lt;/td&gt;
          &lt;td&gt;\hat\theta-\theta&lt;/td&gt;
          &lt;td&gt;$$ → tối ưu là trung vị hậu nghiệm (posterior median),&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;Mất mát 0–1 (rời rạc) → tối ưu là mốt hậu nghiệm (posterior mode).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Như vậy, mọi báo cáo dưới dạng một “ước lượng điểm đại diện” đều ngầm mang theo một giả định về chi phí sai số, dù người phân tích có nêu rõ hay không.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-mỗi-hàm-mất-mát-cho-một-điểm-tóm-tắt-tối-ưu-khác-nhau&quot;&gt;Thử nghiệm: Mỗi hàm mất mát cho một điểm tóm tắt tối ưu khác nhau&lt;/h3&gt;

&lt;p&gt;Mất mát bình phương → trung bình, trị tuyệt đối → trung vị, 0–1 → mốt, bất đối xứng → phân vị.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;decision-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;loss&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;video-ngắn-lý-thuyết-quyết-định-bayes-ngưỡng-tối-ưu-khi-chi-phí-bất-đối-xứng&quot;&gt;Video ngắn: Lý thuyết Quyết định Bayes: Ngưỡng Tối ưu khi Chi phí Bất đối xứng&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch08-04a-decision-asymmetric-loss.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): trượt xác suất hỏng máy chủ p để thấy ngưỡng bảo trì tối ưu nằm ngay tại p* = 10% khi chi phí sập máy gấp 10 lần sửa trước.&lt;/p&gt;

&lt;h2 id=&quot;4-từ-bằng-chứng-đến-hành-động-vai-trò-của-hệ-số-bayes&quot;&gt;4. Từ bằng chứng đến hành động: Vai trò của hệ số Bayes&lt;/h2&gt;

&lt;p&gt;Với hai giả thuyết \(H_0,H_1\), hệ số Bayes (Bayes factor) được định nghĩa:&lt;/p&gt;

\[BF_{10}=\frac{p(D\mid H_1)}{p(D\mid H_0)}.\]

&lt;p&gt;Hệ số này cập nhật tỷ số odds qua biểu thức:&lt;/p&gt;

\[\frac{P(H_1\mid D)}{P(H_0\mid D)}=BF_{10}\times\frac{P(H_1)}{P(H_0)}.\]

&lt;p&gt;Tuy nhiên, ngay cả khi \(BF_{10}\) ủng hộ mạnh \(H_1\), hành động cuối cùng vẫn phải đi qua mất mát kỳ vọng. Hệ số Bayes trả lời câu hỏi “dữ liệu ủng hộ giả thuyết nào hơn?”, còn phân tích quyết định trả lời câu hỏi “trong cấu trúc chi phí hiện tại, hành động nào là tối ưu?”.&lt;/p&gt;

&lt;h2 id=&quot;5-giá-trị-thông-tin-value-of-information-khi-nào-nên-thu-thập-thêm-dữ-liệu&quot;&gt;5. Giá trị thông tin (Value of Information): Khi nào nên thu thập thêm dữ liệu&lt;/h2&gt;

&lt;p&gt;Không phải lúc nào thu thập thêm dữ liệu cũng mang lại lợi ích ròng. Giá trị thông tin được đo bằng mức giảm của mất mát kỳ vọng:&lt;/p&gt;

\[\text{VOI}=\mathbb E[L\mid \text{quyết định ngay}] - \mathbb E[L\mid \text{có thêm thông tin}].\]

&lt;p&gt;Quy tắc hành động tương ứng là:&lt;/p&gt;

\[\text{Thu thập thêm dữ liệu nếu } \text{VOI} &amp;gt; \text{chi phí thu thập}.\]

&lt;p&gt;Ví dụ, nếu mất mát kỳ vọng hiện tại là 12 và có thể giảm xuống 5 sau khi bổ sung thông tin, ta có \(\text{VOI} = 7\). Nếu chi phí thu thập là 4, lợi ích ròng dương nên đáng thu thập thêm; nếu chi phí là 10, lợi ích ròng âm nên hợp lý hơn là quyết định ngay với thông tin sẵn có.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/chapter08_voi_decision_curve.png&quot; alt=&quot;Value of information decision curve&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-evsi-và-cỡ-mẫu-tối-ưu&quot;&gt;Thử nghiệm: EVSI và cỡ mẫu tối ưu&lt;/h3&gt;

&lt;p&gt;So sánh giá trị kỳ vọng của thông tin mẫu bổ sung (EVSI) với chi phí thu thập để lựa chọn cỡ mẫu hợp lý.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;decision-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;voi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;6-ví-dụ-tổng-hợp-quyết-định-trong-ab-testing&quot;&gt;6. Ví dụ tổng hợp: Quyết định trong A/B testing&lt;/h2&gt;

&lt;p&gt;Giả sử hai phiên bản sản phẩm A và B có phân phối hậu nghiệm cho tỷ lệ chuyển đổi lần lượt là \(p_A\) và \(p_B\). Bước suy luận cung cấp xác suất \(P(p_B&amp;gt;p_A\mid D)\), nhưng quyết định triển khai không nên chỉ dựa cơ học vào con số này. Ta cần mô hình hóa hàm lợi ích hoặc mất mát kinh doanh: giá trị mỗi lượt chuyển đổi, chi phí triển khai, tổn thất nếu chọn sai và thời gian phản ứng. Hành động tối ưu là hành động tối đa hóa lợi ích kỳ vọng (hoặc tối thiểu hóa mất mát kỳ vọng), chứ không nhất thiết là hành động vượt qua một ngưỡng xác suất cố định.&lt;/p&gt;

&lt;p&gt;Đây là điểm giao nhau trực tiếp giữa thống kê và quản trị: cùng một phân phối hậu nghiệm, hai doanh nghiệp có cấu trúc chi phí khác nhau hoàn toàn có thể đi đến hai quyết định tối ưu khác nhau.&lt;/p&gt;

&lt;h2 id=&quot;7-quy-trình-thực-hành-phân-tích-quyết-định&quot;&gt;7. Quy trình thực hành phân tích quyết định&lt;/h2&gt;

&lt;p&gt;Một quy trình chặt chẽ thường gồm bốn bước: (i) xác định tập hành động khả thi, (ii) xây dựng hàm mất mát hoặc lợi ích rõ ràng và hợp lý về mặt nghiệp vụ, (iii) tính mất mát kỳ vọng dựa trên phân phối hậu nghiệm hoặc dự báo hậu nghiệm, và (iv) kiểm tra độ nhạy của quyết định khi thay đổi giả định về chi phí. Bước thứ tư đặc biệt quan trọng vì nhiều quyết định có thể đảo chiều khi ước lượng chi phí thay đổi.&lt;/p&gt;

&lt;p&gt;Dưới góc nhìn khoa học, một quyết định Bayes tốt không phải là quyết định chắc chắn đúng tuyệt đối, mà là quyết định tối ưu dựa trên thông tin hiện có và cấu trúc mất mát được khai báo minh bạch.&lt;/p&gt;

&lt;h2 id=&quot;8-kết-luận-bài-84&quot;&gt;8. Kết luận bài 8.4&lt;/h2&gt;

&lt;p&gt;Phân tích quyết định Bayes khép lại chu trình của Chương 08: PPC giúp phát hiện sai lệch của mô hình, WAIC/LOO giúp so sánh năng lực dự báo, các chiến lược so sánh mô hình giúp xử lý độ bất định mô hình, và lý thuyết quyết định chuyển toàn bộ kết quả suy luận thành hành động cụ thể. Nếu suy luận là khoa học cập nhật niềm tin dưới bất định, thì phân tích quyết định là kỷ luật biến niềm tin đó thành lựa chọn có cơ sở.&lt;/p&gt;

&lt;p&gt;Kết thúc Chương 08: phê bình mô hình → so sánh mô hình → ra quyết định.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tính-ngưỡng-quyết-định-tối-ưu-và-ra-quyết-định-bằng-bảng-tổn-thất&quot;&gt;Giải thích: Tính ngưỡng quyết định tối ưu và ra quyết định bằng bảng tổn thất&lt;/h2&gt;

&lt;p&gt;Thay vì dùng ngưỡng cảm tính 50% hay 95%, hãy đi chậm qua 4 bước quyết định Bayes:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lập ma trận tổn thất \(L(a, \theta)\)&lt;/strong&gt; theo đúng đơn vị tiền tệ hoặc hậu quả thực tế.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lấy xác suất hậu nghiệm \(p = P(\theta = 1 \mid y)\)&lt;/strong&gt; từ mô hình Bayes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính tổn thất kỳ vọng của từng hành động&lt;/strong&gt; bằng phép nhân xác suất với từng cột chi phí.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chọn hành động có tổn thất kỳ vọng nhỏ nhất&lt;/strong&gt; (hoặc kiểm tra \(p &amp;gt; p^* = \frac{C_{\text{FP}}}{C_{\text{FP}} + C_{\text{FN}}}\)).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-quyết-định-bảo-trì-phòng-ngừa-cho-một-máy-chủ-quan-trọng&quot;&gt;Ví dụ tính toán làm từng bước: Quyết định bảo trì phòng ngừa cho một máy chủ quan trọng&lt;/h3&gt;

&lt;p&gt;Giả sử mô hình Bayes ước lượng xác suất một máy chủ bị hỏng trong tuần tới là \(p = 0.15\) (chỉ 15%!). Tuy nhiên, chi phí bất đối xứng rất mạnh:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nếu &lt;strong&gt;bảo trì ngay (\(a_1\))&lt;/strong&gt; khi máy thực ra không hỏng: tốn chi phí bảo trì \(C_{\text{FP}} = 2\text{ triệu VNĐ}\).&lt;/li&gt;
  &lt;li&gt;Nếu &lt;strong&gt;không bảo trì (\(a_0\))&lt;/strong&gt; mà máy hỏng thật: thiệt hại gián đoạn dịch vụ \(C_{\text{FN}} = 38\text{ triệu VNĐ}\).&lt;/li&gt;
  &lt;li&gt;(Giả sử nếu bảo trì khi máy sắp hỏng thì ngăn được sự cố, chỉ tốn \(2\text{ triệu}\) bảo trì; không bảo trì khi máy tốt tốn \(0\).)&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Hành động&lt;/th&gt;
      &lt;th&gt;Máy tốt (\(1 - p = 0.85\))&lt;/th&gt;
      &lt;th&gt;Máy hỏng (\(p = 0.15\))&lt;/th&gt;
      &lt;th&gt;Tổn thất hậu nghiệm kỳ vọng&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(a_1\): Bảo trì ngay&lt;/td&gt;
      &lt;td&gt;\(2\text{ triệu}\)&lt;/td&gt;
      &lt;td&gt;\(2\text{ triệu}\)&lt;/td&gt;
      &lt;td&gt;\(0.85(2) + 0.15(2) = \mathbf{2.0\text{ triệu}}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(a_0\): Không bảo trì&lt;/td&gt;
      &lt;td&gt;\(0\text{ triệu}\)&lt;/td&gt;
      &lt;td&gt;\(38\text{ triệu}\)&lt;/td&gt;
      &lt;td&gt;\(0.85(0) + 0.15(38) = 5.7\text{ triệu}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Ngưỡng xác suất tối ưu để hành động là \(p^* = \frac{2}{38} \approx 0.0526\) (chỉ \(5.26\%\)!). Dù xác suất hỏng mới ở mức \(15\%\) (nhỏ hơn nhiều so với 50%), hành động tối ưu theo Bayes vẫn là &lt;strong&gt;bảo trì ngay&lt;/strong&gt;, giúp tiết kiệm kỳ vọng \(5.7 - 2.0 = 3.7\text{ triệu VNĐ}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Dùng ngưỡng phân loại mặc định \(p &amp;gt; 0.50\) hoặc ngưỡng ý nghĩa thống kê \(p &amp;gt; 0.95\) cho mọi bài toán kinh doanh/y tế mà không đưa hàm chi phí vào tính toán.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu chi phí gián đoạn chỉ còn \(10\text{ triệu VNĐ}\) (giữ nguyên chi phí bảo trì \(2\text{ triệu}\)), tổn thất kỳ vọng của “không bảo trì” là \(0.15 \times 10 = 1.5\text{ triệu} &amp;lt; 2.0\text{ triệu}\), nên lúc này hành động tối ưu đổi sang &lt;strong&gt;chưa cần bảo trì&lt;/strong&gt; (ngưỡng \(p^* = 2/10 = 20\%\)).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=b1GxZdFN6cY&quot;&gt;(ML 11.3) Frequentist risk, Bayesian expected loss, and Bayes risk&lt;/a&gt; — mathematicalmonk, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Trình bày mất mát kỳ vọng và rủi ro Bayes, nối trực tiếp từ phân phối hậu nghiệm sang hành động tối ưu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=tbv9E9D2BRQ&quot;&gt;Decision Analysis 2: EMV &amp;amp; EVPI - Expected Value &amp;amp; Perfect Information&lt;/a&gt; — Joshua Emmanuel, English. Giải thích giá trị kỳ vọng của thông tin hoàn hảo, hỗ trợ phần giá trị thông tin (VOI).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=c7_L0-0Bvs8&quot;&gt;Decision Theory: Loss Functions &amp;amp; Bayes Criterion (Worked Example 3)&lt;/a&gt; — StatsResource, English. Minh họa một bài toán quyết định với hàm mất mát cụ thể để thấy cùng một xác suất có thể dẫn tới các hành động khác nhau.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao hai tổ chức có cùng phân phối hậu nghiệm về rủi ro lại có thể đưa ra hai hành động tối ưu khác nhau?&lt;/li&gt;
  &lt;li&gt;Nếu chi phí báo động giả tăng gấp đôi, ngưỡng quyết định \(q^*\) sẽ thay đổi theo chiều hướng nào?&lt;/li&gt;
  &lt;li&gt;Khi giá trị thông tin (VOI) dương nhưng rất sát chi phí thu thập, bạn cần kiểm tra thêm điều gì trước khi quyết định thu thập dữ liệu?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Berger, J. O. (1985). &lt;em&gt;Statistical Decision Theory and Bayesian Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition), Chapter 9.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Chương tiếp theo: &lt;a href=&quot;/vi/chapter12/&quot;&gt;Chapter 12: Labs Thực Hành Bayesian&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Giới thiệu Khóa học: Phân tích Dữ liệu Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_00_course_introduction/"/>
   <updated>2025-01-05T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_00_course_introduction</id>
   <content type="html">&lt;p&gt;Hầu hết chúng ta học thống kê lần đầu qua một danh sách dài các kiểm định rời rạc: kiểm định \(t\), kiểm định \(\chi^2\), ANOVA, từng công thức riêng cho từng bảng số liệu. Thống kê Bayes mở ra một con đường hoàn toàn khác: thay vì ghi nhớ hàng chục công thức chắp vá, bạn chỉ cần nắm vững &lt;strong&gt;một nguyên lý duy nhất&lt;/strong&gt; — xây dựng mô hình sinh dữ liệu và cập nhật niềm tin theo định lý Bayes — rồi áp dụng nhất quán từ bài toán tung đồng xu đến hồi quy phân cấp và mô hình dự báo phức tạp.&lt;/p&gt;

&lt;p&gt;Trang giới thiệu này là tấm bản đồ toàn khóa, giúp bạn hình dung rõ lộ trình học từ nền tảng xác suất, cập nhật liên hợp, MCMC cho tới đánh giá mô hình và ra quyết định thực tế.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;chào-mừng-đến-với-thống-kê-bayes&quot;&gt;Chào mừng đến với Thống kê Bayes&lt;/h2&gt;

&lt;p&gt;Khóa học này được xây dựng với một mục tiêu rõ ràng: giúp bạn &lt;strong&gt;tư duy bằng xác suất&lt;/strong&gt;, thay vì chỉ ghi nhớ các công thức thống kê một cách rời rạc. Trong thực tế, chúng ta liên tục đối diện với những câu hỏi như: một giả thuyết có đáng tin hay không, dữ liệu mới có làm thay đổi niềm tin ban đầu hay không, và nếu phải ra quyết định ngay lúc này thì rủi ro sai sót lớn đến mức nào. Thống kê Bayes (Bayesian statistics) đặc biệt phù hợp với những bài toán như vậy, bởi phương pháp này không dừng ở một “kết quả kiểm định” đơn lẻ mà cung cấp một khung tư duy nhất quán kết nối &lt;strong&gt;niềm tin, dữ liệu, độ bất định và quyết định&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ mini.&lt;/strong&gt; Khi nghe dự báo “70% khả năng mưa”, bạn không cần tưởng tượng ngày mai được lặp lại vô hạn lần để hiểu con số đó. Bạn chỉ cần xem đó là mức độ tin cậy hiện tại để quyết định có mang ô hay không.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Theo bạn, vì sao cách suy nghĩ “cập nhật niềm tin khi có thêm thông tin” lại gần với thực tế đời sống hơn nhiều công thức kiểm định rời rạc?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-lộ-trình-4-tầng-của-tư-duy-thống-kê-bayes&quot;&gt;Kiến thức cần nhớ: Lộ trình 4 tầng của Tư duy Thống kê Bayes&lt;/h2&gt;

&lt;p&gt;Toàn bộ khóa học này được thiết kế như một hành trình gồm ba trụ cột liên kết chặt chẽ với nhau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tầng 1 — Nền tảng xác suất &amp;amp; Tư duy Bayes (Chương 0–2):&lt;/strong&gt; Xây dựng ngôn ngữ xác suất, trực giác prior–likelihood–posterior, họ liên hợp và xấp xỉ lưới để bạn nhìn thấy tường tận cơ chế cập nhật niềm tin bằng tay trước khi dùng phần mềm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng 2 — Tính toán hậu nghiệm &amp;amp; Mô hình hóa (Chương 3–7):&lt;/strong&gt; Vượt qua rào cản tích phân nhiều chiều bằng MCMC (Metropolis–Hastings, HMC/NUTS trong PyMC), sau đó xây dựng hồi quy tuyến tính, mô hình tuyến tính tổng quát (GLM), điều chuẩn bằng prior và mô hình phân cấp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng 3 — Phản biện mô hình &amp;amp; Ra quyết định (Chương 8–12):&lt;/strong&gt; Hoàn thiện chu trình khoa học bằng kiểm tra dự báo hậu nghiệm (PPC), tiêu chí thông tin (WAIC/PSIS-LOO), phân tích quyết định theo hàm chi phí và hệ thống bài lab thực hành xuyên suốt.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;khóa-học-này-sẽ-giúp-bạn-học-điều-gì&quot;&gt;Khóa học này sẽ giúp bạn học điều gì?&lt;/h2&gt;

&lt;p&gt;Khi hoàn thành khóa học này, bạn sẽ không chỉ nắm được định lý Bayes mà còn biết cách vận dụng tư duy Bayes vào các bài toán thực tế.&lt;/p&gt;

&lt;h3 id=&quot;1-hiểu-xác-suất-như-ngôn-ngữ-của-mức-độ-tin-cậy&quot;&gt;1. Hiểu xác suất như ngôn ngữ của mức độ tin cậy&lt;/h3&gt;

&lt;p&gt;Bạn sẽ thấy vì sao trong thống kê Bayes, xác suất không chỉ được hiểu là tần suất dài hạn mà còn là ngôn ngữ định lượng mức độ hợp lý của một giả thuyết, đặc biệt trong những tình huống mà độ bất định là điều không thể tránh khỏi.&lt;/p&gt;

&lt;h3 id=&quot;2-xây-dựng-mô-hình-sinh-dữ-liệu&quot;&gt;2. Xây dựng mô hình sinh dữ liệu&lt;/h3&gt;

&lt;p&gt;Một mô hình Bayes tốt không bắt đầu từ việc viết mã, mà bắt đầu từ việc phân tích xem dữ liệu được sinh ra theo cơ chế nào, tham số nào chưa biết, và phân phối tiền nghiệm (prior) nào phản ánh hợp lý kiến thức sẵn có.&lt;/p&gt;

&lt;h3 id=&quot;3-cập-nhật-niềm-tin-bằng-dữ-liệu&quot;&gt;3. Cập nhật niềm tin bằng dữ liệu&lt;/h3&gt;

&lt;p&gt;Đây là trọng tâm của cả khóa học: &lt;strong&gt;prior&lt;/strong&gt; biểu diễn niềm tin ban đầu, &lt;strong&gt;likelihood&lt;/strong&gt; cho biết dữ liệu ủng hộ từng giả thuyết hay giá trị tham số đến mức nào, còn &lt;strong&gt;posterior&lt;/strong&gt; là niềm tin đã được cập nhật sau khi kết hợp hai nguồn thông tin đó.&lt;/p&gt;

&lt;h4 id=&quot;video-ngắn-cỗ-máy-bayes-prior--likelihood--posterior--cập-nhật-tuần-tự&quot;&gt;Video ngắn: Cỗ máy Bayes: Prior × Likelihood → Posterior &amp;amp; Cập nhật tuần tự&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-00a-bayesian-engine-life.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 28 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): trực quan hóa Prior Beta(2,2) nhân với Likelihood (7/10 Ngửa) thành Posterior Beta(9,5), rồi tiếp tục cập nhật mượt mà khi thêm dữ liệu mới.&lt;/p&gt;

&lt;h3 id=&quot;4-sử-dụng-công-cụ-hiện-đại-cho-suy-luận-bayes&quot;&gt;4. Sử dụng công cụ hiện đại cho suy luận Bayes&lt;/h3&gt;

&lt;p&gt;Sau phần nền tảng, khóa học sẽ giới thiệu các phương pháp tính toán như &lt;strong&gt;xấp xỉ lưới (grid approximation)&lt;/strong&gt;, Monte Carlo và MCMC, tiếp đó là thư viện PyMC để triển khai các mô hình thực tế cùng các kỹ thuật chẩn đoán mô hình và kiểm tra dự báo.&lt;/p&gt;

&lt;h3 id=&quot;5-diễn-giải-kết-quả-một-cách-trung-thực&quot;&gt;5. Diễn giải kết quả một cách trung thực&lt;/h3&gt;

&lt;p&gt;Bạn sẽ học cách trả lời những câu hỏi mà người làm nghiên cứu, kinh doanh hay kỹ thuật thực sự quan tâm: xác suất một tham số lớn hơn 0 là bao nhiêu, vùng giá trị nào có khả năng cao, dự báo tương lai còn mức bất định ra sao, và mô hình có đang bỏ sót cấu trúc quan trọng nào không.&lt;/p&gt;

&lt;h2 id=&quot;vì-sao-nên-học-thống-kê-bayes-ngay-từ-đầu&quot;&gt;Vì sao nên học thống kê Bayes ngay từ đầu?&lt;/h2&gt;

&lt;p&gt;Nhiều người tìm đến thống kê Bayes sau khi đã học thống kê tần suất (frequentist) và cảm thấy khó diễn giải các khái niệm như p-value, khoảng tin cậy (confidence interval) hay kiểm định giả thuyết. Cách tiếp cận Bayes trở nên hấp dẫn vì ba lý do chính.&lt;/p&gt;

&lt;h3 id=&quot;1-gần-với-trực-giác-học-từ-thông-tin-mới&quot;&gt;1. Gần với trực giác học từ thông tin mới&lt;/h3&gt;

&lt;p&gt;Trong đời sống hằng ngày, chúng ta vốn suy nghĩ theo tinh thần Bayes: nghe dự báo thời tiết rồi điều chỉnh kế hoạch, xem kết quả xét nghiệm y khoa rồi cập nhật chẩn đoán, hay quan sát vài lượt mua hàng đầu tiên rồi điều chỉnh nhận định về nhu cầu thị trường. Ít ai suy nghĩ theo kiểu “bác bỏ giả thuyết ở mức ý nghĩa 5%”, bởi ngôn ngữ đời thực gắn với việc cập nhật niềm tin hơn là các quy tắc kiểm định hình thức.&lt;/p&gt;

&lt;h3 id=&quot;2-trung-thực-hơn-về-độ-bất-định&quot;&gt;2. Trung thực hơn về độ bất định&lt;/h3&gt;

&lt;p&gt;Thống kê Bayes không chỉ trả lời “ước lượng bằng bao nhiêu”, mà còn cho biết mức độ chắc chắn của ước lượng đó, những giá trị nào vẫn còn khả dĩ, và vùng rủi ro cần cân nhắc khi dự báo tương lai.&lt;/p&gt;

&lt;h3 id=&quot;3-phù-hợp-với-khoa-học-dữ-liệu-hiện-đại&quot;&gt;3. Phù hợp với khoa học dữ liệu hiện đại&lt;/h3&gt;

&lt;p&gt;Cách tiếp cận Bayes phát huy hiệu quả rõ rệt trong các bài toán có dữ liệu ít nhưng cần quyết định sớm, mô hình phân cấp, dự báo và hệ gợi ý (recommendation), phân tích y khoa, thử nghiệm A/B, cũng như học máy có &lt;strong&gt;định lượng bất định (quantification of uncertainty)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo-trong-suốt-khóa-học&quot;&gt;Tài liệu tham khảo trong suốt khóa học&lt;/h2&gt;

&lt;h3 id=&quot;tài-liệu-chính&quot;&gt;Tài liệu chính&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Richard McElreath (2020)&lt;/strong&gt; - &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition)&lt;/p&gt;

&lt;p&gt;Điểm mạnh của cuốn sách là trực giác mô hình hóa rõ ràng, cách giải thích dễ tiếp cận với người mới học và khả năng kết nối chặt chẽ giữa lý thuyết với thực hành mô hình.&lt;/p&gt;

&lt;h3 id=&quot;tài-liệu-bổ-sung&quot;&gt;Tài liệu bổ sung&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Andrew Gelman et al. (2013)&lt;/strong&gt; - &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition)&lt;/p&gt;

&lt;p&gt;Cuốn sách cung cấp nền tảng toán học vững chắc, độ bao quát rộng và rất phù hợp khi bạn muốn đi sâu hơn sau khi đã có trực giác cơ bản.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;John K. Kruschke (2014)&lt;/strong&gt; - &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Tài liệu có tính sư phạm cao, nhiều ví dụ minh họa và kết nối rõ ràng giữa khái niệm toán học với cách diễn giải kết quả.&lt;/p&gt;

&lt;h2 id=&quot;thông-tin-môn-học-và-đánh-giá&quot;&gt;Thông tin môn học và đánh giá&lt;/h2&gt;

&lt;h3 id=&quot;tài-liệu-tham-khảo-cốt-lõi&quot;&gt;Tài liệu tham khảo cốt lõi&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Congdon, P. &lt;em&gt;Bayesian Statistical Modelling&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Lee, P. M. &lt;em&gt;Bayesian Statistics: An Introduction&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;cấu-phần-đánh-giá&quot;&gt;Cấu phần đánh giá&lt;/h3&gt;

&lt;p&gt;Cấu phần đánh giá hiện tại gồm 20% thường kỳ, 30% giữa kỳ theo hướng thực hành và 50% cuối kỳ theo hướng thực hành.&lt;/p&gt;

&lt;h2 id=&quot;bạn-không-cần-giỏi-toán-mới-học-được-bayes&quot;&gt;Bạn không cần giỏi toán mới học được Bayes&lt;/h2&gt;

&lt;p&gt;Bạn chỉ cần sự kiên nhẫn để chấp nhận ba nguyên tắc: độ bất định cần được mô hình hóa tường minh, dữ liệu không tự mang ý nghĩa nếu thiếu mô hình, và cập nhật niềm tin nhất quán là cốt lõi của suy luận. Khi nắm vững tinh thần đó, thống kê Bayes sẽ không còn là một chủ đề khó tiếp cận mà trở thành một cách tư duy tự nhiên.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Khóa học này không chỉ dạy công thức Bayes mà dạy cả một cách tư duy học từ dữ liệu; thống kê Bayes mạnh ở chỗ kết nối mô hình, độ bất định và ra quyết định trong cùng một quy trình; và để học tốt, bạn nên ưu tiên trực giác mô hình hóa trước rồi mới đến kỹ thuật tính toán.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;đi-tiếp-từ-đây&quot;&gt;Đi tiếp từ đây&lt;/h2&gt;

&lt;p&gt;Bài tiếp theo là &lt;a href=&quot;/contents/vi/chapter01/01_01_replication_crisis_pvalues/&quot;&gt;1.1 Replication Crisis &amp;amp; P-values&lt;/a&gt;, nơi Chương 1 bắt đầu đặt câu hỏi: khi cách suy luận thống kê truyền thống bộc lộ nhiều giới hạn, ta có lựa chọn nào phù hợp hơn không? Nếu cần ôn lại nền tảng trước khi vào chương, bạn có thể xem &lt;a href=&quot;/vi/chapter00/&quot;&gt;Chapter 00: Prerequisites&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-chu-trình-làm-việc-bayes-5-bước-bayesian-workflow&quot;&gt;Giải thích: Chu trình làm việc Bayes 5 bước (Bayesian Workflow)&lt;/h2&gt;

&lt;p&gt;Suốt khóa học, dù bài toán đơn giản hay phức tạp, bạn sẽ luôn đi theo cùng một vòng lặp 5 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kể câu chuyện sinh dữ liệu (Generative Story):&lt;/strong&gt; Viết rõ phân phối prior cho tham số và likelihood cho dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra dự báo tiền nghiệm (Prior Predictive Check):&lt;/strong&gt; Sinh dữ liệu giả lập từ prior để đảm bảo mô hình chưa tạo ra kết quả phi lý.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật hậu nghiệm (Inference):&lt;/strong&gt; Tính hậu nghiệm bằng công thức liên hợp, lưới, hoặc MCMC (PyMC) và kiểm tra hội tụ (\(\hat R\), ESS).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra dự báo hậu nghiệm (Posterior Predictive Check):&lt;/strong&gt; So sánh dữ liệu mô phỏng từ hậu nghiệm với dữ liệu thật để tìm điểm yếu của mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh và ra quyết định:&lt;/strong&gt; Dùng WAIC/LOO để so sánh mô hình và tối thiểu hóa kỳ vọng tổn thất để đưa ra hành động cụ thể.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-bản-thu-nhỏ-cả-khóa-học-trong-3-dòng-số&quot;&gt;Ví dụ tính toán làm từng bước: Bản thu nhỏ cả khóa học trong 3 dòng số&lt;/h3&gt;

&lt;p&gt;Giả sử bạn tung một đồng xu mới \(n = 5\) lần và thấy \(4\) mặt Ngửa. Với niềm tin ban đầu trung lập \(\text{Beta}(1, 1)\) (kỳ vọng \(0.50\)), toàn bộ quy trình Bayes cho ra:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Giai đoạn trong khóa học&lt;/th&gt;
      &lt;th&gt;Đại lượng tương ứng&lt;/th&gt;
      &lt;th&gt;Giá trị cụ thể&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Niềm tin ban đầu (Chương 1–2)&lt;/td&gt;
      &lt;td&gt;Prior \(\text{Beta}(1, 1)\)&lt;/td&gt;
      &lt;td&gt;Kỳ vọng \(1/(1+1) = 0.500\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Bằng chứng dữ liệu (Chương 2)&lt;/td&gt;
      &lt;td&gt;Likelihood \(\text{Binomial}(5, p)\) với \(k=4\)&lt;/td&gt;
      &lt;td&gt;Tỷ lệ quan sát \(4/5 = 0.800\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Niềm tin cập nhật (Chương 2–3)&lt;/td&gt;
      &lt;td&gt;Posterior \(\text{Beta}(1+4, 1+1) = \text{Beta}(5, 2)\)&lt;/td&gt;
      &lt;td&gt;Kỳ vọng \(5/(5+2) \approx 0.714\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Dự báo lần tung thứ 6 (Chương 8)&lt;/td&gt;
      &lt;td&gt;Posterior Predictive \(P(X_6 = 1 \mid y)\)&lt;/td&gt;
      &lt;td&gt;Đúng bằng kỳ vọng hậu nghiệm \(5/7 \approx 0.714\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Mọi mô hình lớn hơn ở các chương sau — từ hồi quy logistic đến mô hình phân cấp — đều vận hành theo đúng bốn dòng logic này, chỉ thay phân phối đơn giản bằng cấu trúc giàu thông tin hơn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nghĩ rằng phải thuộc lòng giải tích phức tạp mới bắt đầu học Bayes được. Trong khóa học này, trực giác xác suất và khả năng đọc phân phối luôn đi trước, còn phần tính tích phân nặng nhọc sẽ có mô phỏng và PyMC đảm nhiệm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu bạn quan sát thêm 5 lần nữa và thấy toàn mặt Sấp (tổng cộng 4 Ngửa, 6 Sấp trong 10 lần), hậu nghiệm tự động cập nhật thành \(\text{Beta}(5, 7)\) với kỳ vọng \(5/12 \approx 0.417\) — không cần bắt đầu lại từ đầu.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R13BD8qKeTg&quot;&gt;The Bayesian Trap&lt;/a&gt; — Veritasium, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Minh họa cái bẫy của tỷ lệ nền khi cập nhật niềm tin, gắn trực tiếp với mục tiêu tư duy bằng xác suất thay vì thuộc công thức.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Giải thích định lý Bayes bằng trực giác hình học, hỗ trợ lộ trình đi từ prior, likelihood đến posterior.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=FdnMWdICdRs&quot;&gt;Statistical Rethinking 2023 - 01 - The Golem of Prague&lt;/a&gt; — Richard McElreath, English. Bài giảng mở đầu của &lt;em&gt;Statistical Rethinking&lt;/em&gt; về việc xem mô hình như công cụ cần được giám sát, cùng tinh thần với khóa học này.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 8.4: Bayesian Decision Analysis - From Inference to Action</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter08/08_04_decision_analysis/"/>
   <updated>2025-01-05T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter08/08_04_decision_analysis</id>
   <content type="html">&lt;p&gt;Your Bayesian posterior tells you there is a &lt;strong&gt;20% chance of heavy rain&lt;/strong&gt; tomorrow—should you carry an umbrella? That question cannot be answered by probability alone! Carrying an umbrella unnecessarily costs tiny annoyance (loss = 1), whereas getting soaked in a suit costs misery (loss = 10). Multiply posterior probabilities by &lt;strong&gt;asymmetric loss&lt;/strong&gt;, and carrying the umbrella wins easily even at just 20% rain probability!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bayesian Decision Theory&lt;/strong&gt; is the final bridge from &lt;em&gt;inference&lt;/em&gt; (\(p(\theta\mid y)\)) to &lt;em&gt;optimal action&lt;/em&gt; (\(a^* = \arg\min_a \mathbb{E}_{\theta\mid y}[L(a, \theta)]\))—explaining why optimal decisions under asymmetric costs almost never use a naive &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.50&lt;/code&gt; probability cutoff.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-from-posterior-beliefs-to-optimal-decisions&quot;&gt;Key ideas: From Posterior Beliefs to Optimal Decisions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Loss / Utility Function \(L(a, \theta)\):&lt;/strong&gt; Quantifies the real-world cost of taking action \(a\) when the true state of the world is \(\theta\) (medical false negative vs. false positive; stockout vs. overstock).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayes-Optimal Action (Expected Posterior Loss):&lt;/strong&gt; Integrate the loss over your full posterior distribution: \(a^* = \arg\min_a \int L(a, \theta)\,p(\theta\mid y)\,d\theta\)—approximated effortlessly from MCMC draws via \(\frac{1}{S}\sum_s L(a, \theta^{(s)})\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Classic Point Estimators Are Just Special Loss Functions:&lt;/strong&gt; Squared error \((a-\theta)^2 \implies\) &lt;strong&gt;posterior mean&lt;/strong&gt;; absolute error \(\lvert a-\theta\rvert \implies\) &lt;strong&gt;posterior median&lt;/strong&gt;; asymmetric pinball loss (cost of under-predicting is \(9\times\) over-predicting) \(\implies\) &lt;strong&gt;90th posterior quantile&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Value of Information (EVPI):&lt;/strong&gt; Quantifies the maximum dollars worth paying to collect &lt;em&gt;more data&lt;/em&gt; before committing to an irreversible action.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you should be able to turn Bayesian inference results into concrete actions under uncertainty, through loss functions, expected loss, and the value of information. The focus of the lesson is to understand that the posterior answers the question “what do we believe”, while decision theory answers a completely different question: “what should we do” when each choice carries asymmetric costs.&lt;/p&gt;

&lt;h2 id=&quot;1-inference-is-not-the-same-as-decision&quot;&gt;1. Inference is not the same as decision&lt;/h2&gt;

&lt;p&gt;A very sharp posterior does not automatically produce the right decision, because a decision always also depends on the consequences of mistakes. The same posterior probability can lead to two different actions if the damage structure changes. This is why decision analysis is the mandatory final stage of the Bayesian workflow, not a decorative add-on after inference.&lt;/p&gt;

&lt;p&gt;The standard framework has four components: the action set \(a\in\mathcal A\), the state of the world \(\theta\), the posterior \(p(\theta\mid y)\) and the loss \(L(a,\theta)\). The Bayes action rule is to choose&lt;/p&gt;

\[a^*(y)=\arg\min_{a\in\mathcal A} \mathbb E[L(a,\theta)\mid y]
=\arg\min_{a\in\mathcal A}\int L(a,\theta)p(\theta\mid y)\,d\theta.\]

&lt;h2 id=&quot;2-a-threshold-rule-from-asymmetric-costs&quot;&gt;2. A threshold rule from asymmetric costs&lt;/h2&gt;

&lt;p&gt;Consider a risk-alert problem with two actions: alert (\(a_1\)) and no alert (\(a_0\)). Let \(q=P(H_1\mid y)\) be the posterior probability of an incident, \(L_{FP}\) the cost of a false alarm, and \(L_{FN}\) the cost of missing an incident. Then&lt;/p&gt;

\[R(a_1\mid y)=L_{FP}(1-q),\qquad R(a_0\mid y)=L_{FN}q.\]

&lt;p&gt;We choose to alert if \(R(a_1\mid y)&amp;lt;R(a_0\mid y)\), which is equivalent to&lt;/p&gt;

\[q&amp;gt;\frac{L_{FP}}{L_{FP}+L_{FN}}.\]

&lt;p&gt;With \(L_{FP}=5\) and \(L_{FN}=40\), the decision threshold is only \(q^*=5/45\approx 0.111\). This shows an important methodological point: the optimal decision can be very “sensitive” to costs, even when the posterior does not change.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/chapter08_expected_loss_threshold.png&quot; alt=&quot;Expected loss threshold rule&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;21-a-business-meaning-example&quot;&gt;2.1. A business-meaning example&lt;/h3&gt;

&lt;p&gt;If missing an incident causes losses many times larger than a false alert, a reasonable organization will alert earlier, that is, use a lower posterior threshold. Conversely, if a false alert is very expensive, the posterior threshold needs to be higher to avoid over-acting. The optimal rule is therefore never a “universal” number; it is a function of the loss structure in the specific context.&lt;/p&gt;

&lt;h3 id=&quot;experiment-the-decision-threshold-in-an-ab-test&quot;&gt;Experiment: the decision threshold in an A/B test&lt;/h3&gt;

&lt;p&gt;Add batches of 150 users one at a time, track π = P(p &amp;gt; p₀) and compare it with the threshold c_fp/(c_fp + c_fn).&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;decision-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;threshold&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-loss-functions-and-posterior-summaries&quot;&gt;3. Loss functions and posterior summaries&lt;/h2&gt;

&lt;p&gt;In point estimation, the choice of mean, median, or mode is not a presentation preference but is determined by the loss:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;squared loss \(L(\hat\theta,\theta)=(\hat\theta-\theta)^2\) -&amp;gt; the optimum is the posterior mean,&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;absolute loss $$L(\hat\theta,\theta)=&lt;/td&gt;
          &lt;td&gt;\hat\theta-\theta&lt;/td&gt;
          &lt;td&gt;$$ -&amp;gt; the optimum is the posterior median,&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;0-1 loss (discrete) -&amp;gt; the optimum is the posterior mode.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The methodological conclusion here is: any report of a “representative point estimate” implicitly contains a view about the cost of error, whether or not we are aware of it.&lt;/p&gt;

&lt;h3 id=&quot;experiment-each-loss-function-gives-a-different-optimal-summary&quot;&gt;Experiment: each loss function gives a different optimal summary&lt;/h3&gt;

&lt;p&gt;Squared → mean, absolute value → median, 0–1 → mode, asymmetric → quantile.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;decision-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;loss&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;4-from-evidence-to-action-the-role-of-the-bayes-factor&quot;&gt;4. From evidence to action: the role of the Bayes factor&lt;/h2&gt;

&lt;p&gt;For two hypotheses \(H_0,H_1\), the Bayes factor is defined as:&lt;/p&gt;

\[BF_{10}=\frac{p(D\mid H_1)}{p(D\mid H_0)}.\]

&lt;p&gt;It updates the odds through&lt;/p&gt;

\[\frac{P(H_1\mid D)}{P(H_0\mid D)}=BF_{10}\times\frac{P(H_1)}{P(H_0)}.\]

&lt;p&gt;However, even when \(BF_{10}\) leans strongly toward \(H_1\), the final action must still pass through the expected loss. The Bayes factor answers the question “which hypothesis does the data support”; decision analysis answers a different one: “under the current cost structure, which action is optimal”.&lt;/p&gt;

&lt;h2 id=&quot;5-value-of-information-when-to-collect-more-data&quot;&gt;5. Value of Information: when to collect more data&lt;/h2&gt;

&lt;p&gt;Adding data is not always worth it. The value of information is measured by the reduction in expected loss:&lt;/p&gt;

\[\text{VOI}=\mathbb E[L\mid \text{decide now}] - \mathbb E[L\mid \text{with extra information}].\]

&lt;p&gt;The action rule is very clear:&lt;/p&gt;

\[\text{Collect more data if } \text{VOI} &amp;gt; \text{collection cost}.\]

&lt;p&gt;For example, if the current expected loss is 12 and after adding information it could drop to 5, then VOI = 7. If the cost of obtaining the information is 4, the net benefit is positive and we should collect it; if the cost is 10, the net benefit is negative and we should decide now with the information we have.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/chapter08_voi_decision_curve.png&quot; alt=&quot;Value of information decision curve&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;experiment-evsi-and-the-optimal-sample-size&quot;&gt;Experiment: EVSI and the optimal sample size&lt;/h3&gt;

&lt;p&gt;Compare the expected value of an extra sample with its collection cost to choose the sample size.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;decision-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;voi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;6-a-combined-example-an-ab-testing-decision&quot;&gt;6. A combined example: an A/B testing decision&lt;/h2&gt;

&lt;p&gt;Suppose two product versions A and B have posterior conversion rates \(p_A\) and \(p_B\). The inference part gives us the probability \(P(p_B&amp;gt;p_A\mid D)\), but the rollout decision should not rest mechanically on this probability. We need to model the business utility/loss: the value of each conversion, the rollout cost, the risk of loss if we choose wrongly, and the time available to react. The optimal action is then the one with the highest expected utility (or the lowest expected loss), not necessarily the one with the highest posterior probability under a fixed threshold.&lt;/p&gt;

&lt;p&gt;This is an important intersection between statistics and management: with the same posterior, businesses with different cost structures will have different optimal decisions.&lt;/p&gt;

&lt;h2 id=&quot;7-a-workflow-template-for-decision-analysis&quot;&gt;7. A workflow template for decision analysis&lt;/h2&gt;

&lt;p&gt;A rigorous practical procedure usually goes through four steps: (i) identify the set of actions that can be executed, (ii) define a clear loss/utility that can be defended on business grounds, (iii) compute the expected loss based on the posterior/predictive, and (iv) check the sensitivity of the decision when the loss assumptions change. Step (iv) is especially important because many decisions can flip when costs are re-evaluated.&lt;/p&gt;

&lt;p&gt;From a scientific viewpoint, a good Bayesian decision is not one that is “certainly right”, but one that is optimal given the current information and a transparently declared loss structure.&lt;/p&gt;

&lt;h2 id=&quot;8-conclusion-of-lesson-84&quot;&gt;8. Conclusion of Lesson 8.4&lt;/h2&gt;

&lt;p&gt;Bayesian decision analysis completes the cycle of Chapter 08: PPC helps detect where the model is wrong, WAIC/LOO helps compare predictive ability, model comparison strategies help handle model uncertainty, and decision theory turns all of that information into concrete action. If inference is the science of belief under uncertainty, then decision analysis is the discipline that turns that belief into a responsible choice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Chapter 08 Complete&lt;/strong&gt;: model criticism -&amp;gt; model comparison -&amp;gt; decision.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-optimal-medical--umbrella-decision-under-asymmetric-loss&quot;&gt;Worked Numerical Example: Optimal Medical / Umbrella Decision Under Asymmetric Loss&lt;/h3&gt;

&lt;p&gt;Suppose your posterior probability of a severe defect (\(D=1\)) is only &lt;strong&gt;\(p = 0.20\)&lt;/strong&gt; (and \(P(D=0) = 0.80\)). Compare two actions with asymmetric costs:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Action &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Inspect&lt;/code&gt;:&lt;/strong&gt; Fixed cost = &lt;strong&gt;$$100$&lt;/strong&gt; whether defective or not.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Action &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Ship Without Inspecting&lt;/code&gt;:&lt;/strong&gt; Cost = &lt;strong&gt;$$0$&lt;/strong&gt; if clean, but &lt;strong&gt;$$1{,}000$&lt;/strong&gt; recall disaster if defective!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Compute exact expected posterior loss for both actions:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[\mathbb{E}[L(\text{Inspect})] = 0.20(100) + 0.80(100) = \mathbf{\$100}.\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathbb{E}[L(\text{Ship})] = 0.20(1000) + 0.80(0) = \mathbf{\$200}.\]
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Optimal threshold:&lt;/strong&gt; Inspect whenever \(1000\,p &amp;gt; 100 \iff \mathbf{p &amp;gt; 0.10}\)! Even though “no defect” is 4× more likely (80%), &lt;strong&gt;Inspect&lt;/strong&gt; cuts expected loss in half!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-rules-for-bayesian-decision-analysis&quot;&gt;Explanation: Four Rules for Bayesian Decision Analysis&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always separate &lt;em&gt;inference&lt;/em&gt; (posterior \(p(\theta\mid y)\)) from &lt;em&gt;decision&lt;/em&gt; (loss \(L(a,\theta)\)):&lt;/strong&gt; Never distort your prior to mimic a conservative loss function—keep beliefs honest and put conservatism explicitly into the loss matrix!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Integrate loss over the &lt;em&gt;entire&lt;/em&gt; posterior, not just the posterior mean:&lt;/strong&gt; Under nonlinear or asymmetric loss, \(L(a, \mathbb{E}[\theta]) \neq \mathbb{E}[L(a, \theta)]\) (Jensen’s inequality!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use the 0.50 threshold only when false positives and false negatives cost the exact same amount:&lt;/strong&gt; In fraud, medicine, and SRE alerting, optimal thresholds are often &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.05&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.15&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Expected Value of Sample Information before running expensive experiments:&lt;/strong&gt; If even a 10× larger sample wouldn’t change your optimal action \(a^*\), act now instead of delaying!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the defect-inspection example above, if the recall disaster cost drops from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;\$1,000&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;\$400&lt;/code&gt; (still with inspection cost &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;\$100&lt;/code&gt;), what is the new posterior probability threshold \(p^*\) above which you should choose &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Inspect&lt;/code&gt;?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=b1GxZdFN6cY&quot;&gt;(ML 11.3) Frequentist risk, Bayesian expected loss, and Bayes risk&lt;/a&gt; — mathematicalmonk, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch expected loss and Bayes risk, exactly the step where the lesson goes from the posterior to an action under a loss.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=tbv9E9D2BRQ&quot;&gt;Decision Analysis 2: EMV &amp;amp; EVPI - Expected Value &amp;amp; Perfect Information&lt;/a&gt; — Joshua Emmanuel, English. Watch the expected value of perfect information, supporting the value-of-information part.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=c7_L0-0Bvs8&quot;&gt;Decision Theory: Loss Functions &amp;amp; Bayes Criterion (Worked Example 3)&lt;/a&gt; — StatsResource, English. Watch a decision problem with a concrete loss function, used to see how the same probability can lead to two different actions.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why can two organizations with the same posterior about a risk arrive at two different optimal actions?&lt;/li&gt;
  &lt;li&gt;If the cost of a false alarm doubles, in which direction does the threshold \(q^*\) change?&lt;/li&gt;
  &lt;li&gt;When VOI is positive but very close to the collection cost, what should you check before deciding to collect more data?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Berger, J. O. (1985). &lt;em&gt;Statistical Decision Theory and Bayesian Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition), Chapter 9.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next chapter: &lt;a href=&quot;/en/chapter12/&quot;&gt;Chapter 12: Bayesian Hands-on Labs&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Course Introduction: Bayesian Data Analysis</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_00_course_introduction/"/>
   <updated>2025-01-05T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_00_course_introduction</id>
   <content type="html">&lt;p&gt;Most statistics courses hand you a confusing flowchart of 25 disconnected tests—pick a \(z\)-test here, a Mann–Whitney there, a chi-squared somewhere else—and leave you memorizing edge cases. &lt;strong&gt;Bayesian Data Analysis&lt;/strong&gt; replaces that entire zoo with &lt;strong&gt;one unified, generative engine&lt;/strong&gt;: write a probability story for how your data arose, condition on the data you actually observed, and inspect the resulting posterior distribution!&lt;/p&gt;

&lt;p&gt;Welcome to the course roadmap: this introduction shows you how all twelve chapters connect—from Chapter 0’s probability foundations through conjugate algebra, MCMC/HMC sampling, hierarchical partial pooling, and real-world Bayesian decision analysis.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-four-stage-journey-of-bayesian-data-analysis&quot;&gt;Key ideas: The Four-Stage Journey of Bayesian Data Analysis&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Stage 1 — Foundations &amp;amp; Updating (Chapters 0–2):&lt;/strong&gt; Probability as plausibility, Bayes’ rule, likelihoods, priors, posteriors, and exact conjugate families (Beta–Binomial, Normal–Normal, Gamma–Poisson).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stage 2 — Computation Beyond Conjugacy (Chapters 3–4):&lt;/strong&gt; Grid approximation, Quadratic/Laplace approximation, and &lt;strong&gt;Markov Chain Monte Carlo (MCMC / Metropolis / HMC-NUTS)&lt;/strong&gt; so you can fit &lt;em&gt;any&lt;/em&gt; model you can write down.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stage 3 — Regression, GLMs, Causality &amp;amp; Regularization (Chapters 5–7):&lt;/strong&gt; Multiple predictors, DAGs &amp;amp; confounding, Logistic/Poisson GLMs, and shrinkage priors that prevent overfitting.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stage 4 — Criticism, Decisions &amp;amp; Hierarchical Models (Chapters 8–12):&lt;/strong&gt; Posterior Predictive Checks (PPC), WAIC/LOO model comparison, Bayesian decision theory, and hands-on coding labs.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;welcome-to-bayesian-statistics&quot;&gt;Welcome to Bayesian Statistics&lt;/h2&gt;

&lt;p&gt;This course is built for one very clear goal: to help you learn to &lt;strong&gt;think in probabilities&lt;/strong&gt;, instead of just memorizing statistical formulas as disconnected pieces. In practice, we constantly face questions such as whether a hypothesis is credible, whether new data changes an old belief, and, if we must decide today, how large the risk of being wrong is. Bayesian statistics is especially strong at exactly these questions, because it does not just give a “test result”, but provides a unified way of thinking about &lt;strong&gt;belief, data, uncertainty and decisions&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; When you hear a forecast of “70% chance of rain”, you do not need to repeat tomorrow infinitely many times to understand what it means. You only need to know the current level of confidence to decide whether to bring an umbrella.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In your opinion, why is the way of thinking “update beliefs when more information arrives” closer to real life than many disconnected statistical formulas?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/bayesian_daily_life_small.png&quot; alt=&quot;Bayesian reasoning in everyday life&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;what-will-this-course-help-you-learn&quot;&gt;What will this course help you learn?&lt;/h2&gt;

&lt;p&gt;If you study this course well, you will not only know “what Bayes’ theorem is”, but also how to use Bayesian thinking on real problems.&lt;/p&gt;

&lt;h3 id=&quot;1-understand-probability-as-a-language-of-degrees-of-belief&quot;&gt;1. Understand probability as a language of degrees of belief&lt;/h3&gt;

&lt;p&gt;You will see why in Bayes, probability is understood not only as long-run frequency but also as a language describing the plausibility of a hypothesis, especially in situations where uncertainty is unavoidable.&lt;/p&gt;

&lt;h3 id=&quot;2-understand-how-to-build-a-data-generating-model&quot;&gt;2. Understand how to build a data-generating model&lt;/h3&gt;

&lt;p&gt;A good Bayesian model does not start from code. It starts from the question of how the data was generated, which parameters are still unknown, and which prior reasonably reflects what we already know.&lt;/p&gt;

&lt;h3 id=&quot;3-understand-how-to-update-beliefs-with-data&quot;&gt;3. Understand how to update beliefs with data&lt;/h3&gt;

&lt;p&gt;This is the heart of the whole course: the &lt;strong&gt;prior&lt;/strong&gt; is what we initially believe, the &lt;strong&gt;likelihood&lt;/strong&gt; is how the data speaks under each hypothesis or parameter value, and the &lt;strong&gt;posterior&lt;/strong&gt; is the belief updated after those two parts meet.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/bayes_machine_small.png&quot; alt=&quot;The Bayes machine: from prior to posterior&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;4-know-how-to-use-modern-tools-for-bayesian-inference&quot;&gt;4. Know how to use modern tools for Bayesian inference&lt;/h3&gt;

&lt;p&gt;After the foundations, the course moves into tools such as &lt;strong&gt;grid approximation&lt;/strong&gt;, Monte Carlo and MCMC, then PyMC to implement real models, as well as model diagnostic techniques and predictive checks.&lt;/p&gt;

&lt;h3 id=&quot;5-know-how-to-interpret-results-honestly&quot;&gt;5. Know how to interpret results honestly&lt;/h3&gt;

&lt;p&gt;You will learn how to answer the questions that researchers, business people and engineers really care about, such as what the probability is that a parameter is greater than 0, which range of values is still plausible, how uncertain the future forecast is, and whether the model is missing an important structure.&lt;/p&gt;

&lt;h2 id=&quot;why-learn-bayes-from-the-very-beginning&quot;&gt;Why learn Bayes from the very beginning?&lt;/h2&gt;

&lt;p&gt;Many people come to Bayes after learning frequentist statistics and feeling that something is “hard to swallow” about p-values, confidence intervals or hypothesis testing. That is perfectly normal.&lt;/p&gt;

&lt;p&gt;Bayes is attractive for three big reasons.&lt;/p&gt;

&lt;h3 id=&quot;1-it-is-close-to-the-intuition-of-learning-from-new-information&quot;&gt;1. It is close to the intuition of learning from new information&lt;/h3&gt;

&lt;p&gt;In life, we already think in a very Bayesian way: hearing a weather forecast and then updating plans, seeing a medical test and then updating a diagnosis, or watching the first few purchases and then adjusting beliefs about market demand. We hardly ever think in the style of “I reject the hypothesis at the 5% significance level”, because everyday language is closer to updating beliefs than to formal testing rituals.&lt;/p&gt;

&lt;h3 id=&quot;2-it-is-more-honest-about-uncertainty&quot;&gt;2. It is more honest about uncertainty&lt;/h3&gt;

&lt;p&gt;Bayes does not only answer “what is the estimate”, but also tells us how sure we are, which values remain possible, and, if we must forecast the future, how the risk region should be understood.&lt;/p&gt;

&lt;h3 id=&quot;3-it-fits-modern-data-science-very-well&quot;&gt;3. It fits modern data science very well&lt;/h3&gt;

&lt;p&gt;Bayes is especially strong in contexts such as little data but a need for quick decisions, hierarchical models, forecasting and recommendation, medical analysis, A/B testing, or machine learning with &lt;strong&gt;quantification of uncertainty&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;resources-to-consult-throughout-the-course&quot;&gt;Resources to consult throughout the course&lt;/h2&gt;

&lt;h3 id=&quot;main-resource&quot;&gt;Main resource&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Richard McElreath (2020)&lt;/strong&gt; - &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition)&lt;/p&gt;

&lt;p&gt;The strength of this resource is its very good modeling intuition, an explanation style close to beginners, and a tight connection between theory and practical models.&lt;/p&gt;

&lt;h3 id=&quot;supplementary-resources&quot;&gt;Supplementary resources&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Andrew Gelman et al. (2013)&lt;/strong&gt; - &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition)&lt;/p&gt;

&lt;p&gt;The strength of this resource is its very solid foundation, broad coverage, and high suitability when you want to go deeper after having built initial intuition.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;John K. Kruschke (2014)&lt;/strong&gt; - &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The strength of this resource is its very high pedagogy, many illustrative examples, and a very good connection between concepts and interpretation.&lt;/p&gt;

&lt;h2 id=&quot;course-information-and-assessment&quot;&gt;Course information and assessment&lt;/h2&gt;

&lt;h3 id=&quot;core-reference-materials&quot;&gt;Core reference materials&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Congdon, P. &lt;em&gt;Bayesian Statistical Modelling&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Lee, P. M. &lt;em&gt;Bayesian Statistics: An Introduction&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;assessment-components&quot;&gt;Assessment components&lt;/h3&gt;

&lt;p&gt;The current assessment consists of 20% regular work, 30% mid-term in a practical format, and 50% final in a practical format as well.&lt;/p&gt;

&lt;h2 id=&quot;you-do-not-need-to-be-good-at-math-to-learn-bayes&quot;&gt;You do not need to be good at math to learn Bayes&lt;/h2&gt;

&lt;p&gt;You only need enough patience to accept that uncertainty is something that must be modeled, that data does not speak for itself without a model, and that updating beliefs consistently is the core of inference. If you keep that spirit, Bayes will no longer be a hard chapter of statistics, but a very natural way of thinking.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; This course does not only teach the Bayes formula but also a whole way of thinking about learning from data; Bayesian statistics is strong in connecting models, uncertainty and decision-making in the same workflow; and to study this course well, you should always prioritize modeling intuition first and only then computational technique.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;moving-on-from-here&quot;&gt;Moving on from here&lt;/h2&gt;

&lt;p&gt;The next lesson is &lt;a href=&quot;/en/chapter01/replication-crisis-pvalues/&quot;&gt;1.1 Replication Crisis &amp;amp; P-values&lt;/a&gt;. This is where Chapter 1 begins to ask: if traditional statistical inference has too many limitations, do we have a better option?&lt;/p&gt;

&lt;p&gt;If you need to review the foundations before entering the chapter, you can see &lt;a href=&quot;/en/chapter00/&quot;&gt;Chapter 00: Prerequisites&lt;/a&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-one-complete-mini-bayesian-cycle-in-3-lines-of-arithmetic&quot;&gt;Worked Numerical Example: One Complete Mini Bayesian Cycle in 3 Lines of Arithmetic&lt;/h3&gt;

&lt;p&gt;Before writing a single line of Stan or PyMC, see the entire Bayesian workflow on a 3-flip coin experiment (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;H, H, T&lt;/code&gt; — 2 heads, 1 tail) starting from a flat \(\mathrm{Beta}(1,1)\) prior:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Update:&lt;/strong&gt; \(\mathrm{Beta}(1 + 2,\; 1 + 1) = \mathrm{Beta}(3, 2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Summarize:&lt;/strong&gt; Posterior mean \(\mathbb{E}[p\mid D] = \frac{3}{3+2} = \mathbf{0.60}\), mode \(\frac{3-1}{3+2-2} = \mathbf{0.667}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Predict next flip (Posterior Predictive):&lt;/strong&gt; Probability Flip 4 is Heads equals the posterior mean &lt;strong&gt;\(60\%\)&lt;/strong&gt;—automatically hedging between the raw sample rate (66.7%) and prior ignorance (50%)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-study-habits-that-make-this-course-stick&quot;&gt;Explanation: Four Study Habits That Make This Course Stick&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always sketch the generative story first:&lt;/strong&gt; Every model in Chapters 1–12 can be drawn as a 3-line prior \(\to\) likelihood diagram.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Run and break every Python lab:&lt;/strong&gt; Change the prior strength, cut \(n\) in half, or inject an outlier to &lt;em&gt;see&lt;/em&gt; how the posterior reacts.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never separate inference from checking:&lt;/strong&gt; Fitting a posterior is only step 1; Posterior Predictive Checks tell you whether your model actually resembles reality.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Think in distributions, not single numbers:&lt;/strong&gt; Train yourself to ask &lt;em&gt;“how wide is my uncertainty?”&lt;/em&gt; every time you see a point estimate.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the 3-flip example above (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Beta(3, 2)&lt;/code&gt; posterior), if you observe 100 more flips (60 Heads, 40 Tails), what is the updated posterior Beta distribution?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R13BD8qKeTg&quot;&gt;The Bayesian Trap&lt;/a&gt; — Veritasium, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the base-rate trap when updating beliefs, exactly the lesson’s invitation to think in probabilities instead of memorizing formulas.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Watch the geometry of Bayes’ theorem, supporting the roadmap the lesson promises from prior and likelihood to posterior.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=FdnMWdICdRs&quot;&gt;Statistical Rethinking 2023 - 01 - The Golem of Prague&lt;/a&gt; — Richard McElreath, English. Watch the opening lecture of Statistical Rethinking on models as tools that need to be supervised, in the same spirit as this course.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 8.3: Model Comparison Strategies</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter08/08_03_model_comparison/"/>
   <updated>2025-01-04T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter08/08_03_model_comparison</id>
   <content type="html">&lt;p&gt;Sau khi có bảng điểm LOO/WAIC trong tay, phản xạ quen thuộc của hầu hết người làm dữ liệu là chọn lấy mô hình đứng hạng nhất và xóa sạch mọi mô hình còn lại. Nhưng điều gì xảy ra nếu Mô hình A và Mô hình B gần như ngang điểm nhau, mỗi mô hình lại nắm bắt một góc khác nhau của thực tế? Vứt bỏ Mô hình B đồng nghĩa với việc tự xóa đi phần &lt;strong&gt;bất định về cấu trúc mô hình (model uncertainty)&lt;/strong&gt; và làm khoảng dự báo bị hẹp giả tạo.&lt;/p&gt;

&lt;p&gt;Bài học này mở rộng tư duy từ “chọn một người thắng cuộc” sang ba chiến lược chiến lược chuẩn của thống kê Bayes hiện đại: &lt;strong&gt;Chọn mô hình (Selection)&lt;/strong&gt;, &lt;strong&gt;Kết hợp mô hình (Averaging / Stacking)&lt;/strong&gt; và &lt;strong&gt;Mở rộng mô hình (Continuous Model Expansion)&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài học này, bạn sẽ phân biệt rõ ba chiến lược so sánh mô hình trong thống kê Bayes: chọn một mô hình (selection), kết hợp nhiều mô hình (averaging) và mở rộng thành mô hình bao trùm (expansion). Trọng tâm là không xem so sánh mô hình như một thủ tục xếp hạng cơ học, mà như một bài toán ra quyết định dưới độ bất định về cấu trúc mô hình, trong đó chiến lược lựa chọn phụ thuộc vào mức độ tách biệt về hiệu năng dự báo và mục tiêu ứng dụng.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-chọn-lọc-kết-hợp-bmastacking-và-mở-rộng-mô-hình&quot;&gt;Kiến thức cần nhớ: Chọn lọc, Kết hợp (BMA/Stacking) và Mở rộng Mô hình&lt;/h2&gt;

&lt;p&gt;Ba chiến lược xử lý đa mô hình tương ứng với ba bối cảnh thực tiễn rõ rệt:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Chọn mô hình (Model Selection):&lt;/strong&gt; Phù hợp khi một mô hình vượt trội rõ rệt (\(\Delta\text{elpd} \gg 2\,\mathrm{SE}\)) hoặc khi hệ thống vận hành đòi hỏi một mô hình đơn giản, gọn nhẹ duy nhất để triển khai và giải thích.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kết hợp mô hình (BMA &amp;amp; Bayesian Stacking):&lt;/strong&gt; Thay vì chọn 1, ta trộn phân phối dự báo hậu nghiệm: \(p(\tilde y \mid y) = \sum_{k=1}^K w_k\, p(\tilde y \mid y, M_k)\). Khác với BMA cổ điển (dễ nhạy với prior và giả định một trong các mô hình là mô hình thật — thế giới \(\mathcal{M}\)-closed), &lt;strong&gt;Bayesian Stacking&lt;/strong&gt; (Yao et al., 2018) tối ưu hóa trực tiếp trọng số \(w_k\) trên điểm LOO để tối đa hóa khả năng dự báo trong thế giới thực (\(\mathcal{M}\)-open).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mở rộng mô hình (Model Expansion):&lt;/strong&gt; Thay vì coi hai mô hình rời rạc như hai đối thủ loại trừ nhau, ta nhúng cả hai vào một mô hình liên tục tổng quát hơn (ví dụ dùng phân phối Student-\(t\) với bậc tự do \(\nu\) học được thay vì chọn cứng giữa Gaussian và Cauchy).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-so-sánh-mô-hình-không-phải-lúc-nào-cũng-là-chọn-một-mô-hình-thắng-cuộc&quot;&gt;1. So sánh mô hình không phải lúc nào cũng là chọn một mô hình thắng cuộc&lt;/h2&gt;

&lt;p&gt;Khi nhiều mô hình ứng viên có năng lực dự báo rất sát nhau, việc ép buộc phải chọn duy nhất một mô hình dễ tạo cảm giác chắc chắn giả tạo. Ngược lại, khi một mô hình vượt trội rõ rệt và ổn định qua các bước kiểm tra, duy trì nhiều mô hình chỉ làm tăng độ phức tạp mà không mang lại thêm giá trị dự báo. Do đó, câu hỏi đúng không phải là “mô hình nào đứng hạng nhất?”, mà là “chiến lược nào tạo ra dự báo hữu ích nhất với mức độ bất định trung thực nhất?”.&lt;/p&gt;

&lt;h2 id=&quot;2-chiến-lược-a--chọn-mô-hình-model-selection&quot;&gt;2. Chiến lược A — Chọn mô hình (Model Selection)&lt;/h2&gt;

&lt;p&gt;Chọn mô hình phù hợp khi khoảng cách về năng lực dự báo ngoài mẫu giữa mô hình tốt nhất và các mô hình còn lại đủ lớn so với độ bất định ước lượng. Khi đó, chi phí duy trì nhiều mô hình thường vượt quá lợi ích mang lại, còn một mô hình duy nhất giúp việc diễn giải, truyền đạt và triển khai trở nên gọn nhẹ hơn.&lt;/p&gt;

&lt;p&gt;Tuy nhiên, điều kiện ngầm của chiến lược này là sự tách biệt phải đủ mạnh. Nếu chênh lệch giữa các chỉ số dự báo nhỏ và thiếu ổn định, việc chọn cứng một mô hình có thể khiến toàn bộ quy trình phụ thuộc vào dao động ngẫu nhiên của mẫu thay vì tín hiệu cấu trúc thật.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-hệ-số-bayes-là-tỷ-số-hợp-lý-biên-marginal-likelihood&quot;&gt;Thử nghiệm: Hệ số Bayes là tỷ số hợp lý biên (marginal likelihood)&lt;/h3&gt;

&lt;p&gt;Tung đồng xu từng lần và quan sát \(BF_{10} = m_1(k)/m_0(k)\) tích lũy; hợp lý biên tự động phạt các mô hình dàn trải xác suất quá rộng (hiệu ứng Occam).&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;bf-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;seq&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-chiến-lược-b--kết-hợp-mô-hình-model-averaging&quot;&gt;3. Chiến lược B — Kết hợp mô hình (Model Averaging)&lt;/h2&gt;

&lt;p&gt;Kết hợp mô hình tuân theo nguyên tắc bảo toàn độ bất định giữa các mô hình bằng cách trộn các phân phối dự báo:&lt;/p&gt;

\[p(\tilde y\mid y)=\sum_{k=1}^{K} w_k\,p_k(\tilde y\mid y),\qquad \sum_k w_k=1,\; w_k\ge 0.\]

&lt;p&gt;Trong thực hành hiện đại, trọng số stacking thường được ưu tiên vì chúng tối ưu trực tiếp năng lực dự báo của phân phối kết hợp, thay vì cố gán xác suất “đúng” hay “sai” tuyệt đối cho từng mô hình riêng lẻ.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-trung-bình-mô-hình-theo-trọng-số-pseudo-bma&quot;&gt;Thử nghiệm: Trung bình mô hình theo trọng số pseudo-BMA&lt;/h3&gt;

&lt;p&gt;Thêm từng mô hình vào tập ứng viên và quan sát sự thay đổi của trọng số \(w \propto \exp(\text{elpd}_{\text{loo}})\) cùng dự báo trung bình.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;ic-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;avg&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;31-ví-dụ-định-lượng-ngắn&quot;&gt;3.1. Ví dụ định lượng ngắn&lt;/h3&gt;

&lt;p&gt;Giả sử tại một điểm dự báo mới, mô hình A cho trung bình 52, mô hình B cho trung bình 56, và trọng số stacking lần lượt là 0.58 và 0.42. Khi đó, dự báo trung bình của mô hình kết hợp là:&lt;/p&gt;

\[0.58\times 52 + 0.42\times 56 = 53.68.\]

&lt;p&gt;Giá trị này phản ánh đồng thời tín hiệu từ cả hai mô hình lẫn độ bất định cấu trúc giữa chúng, thay vì cưỡng ép chọn 52 hoặc 56 như hai kịch bản loại trừ nhau.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/chapter08_selection_vs_stacking.png&quot; alt=&quot;Selection vs Stacking predictive distributions&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-hệ-số-bayes-phụ-thuộc-vào-độ-rộng-tiên-nghiệm&quot;&gt;Thử nghiệm: Hệ số Bayes phụ thuộc vào độ rộng tiên nghiệm&lt;/h3&gt;

&lt;p&gt;Thay đổi tiên nghiệm \(\text{Beta}(c, c)\) của \(M_1\) và quan sát \(BF_{10}\) biến thiên — lý do cần thực hiện phân tích độ nhạy.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;bf-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;prior&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;video-ngắn-chọn-1-mô-hình-vs-trộn-mô-hình-stacking--bma&quot;&gt;Video ngắn: Chọn 1 Mô hình vs Trộn Mô hình (Stacking / BMA)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch08-03a-stacking-vs-selection.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): biến đổi phân phối dự báo từ chọn cứng 100% Mô hình 1 sang trộn 65% M₁ + 35% M₂ để bao trọn cả hai kịch bản hợp lý.&lt;/p&gt;

&lt;h2 id=&quot;4-chiến-lược-c--mở-rộng-mô-hình-model-expansion&quot;&gt;4. Chiến lược C — Mở rộng mô hình (Model Expansion)&lt;/h2&gt;

&lt;p&gt;Mở rộng mô hình phù hợp khi các mô hình ứng viên phản ánh những mảnh ghép khác nhau của cùng một cơ chế sinh dữ liệu và có thể hợp nhất vào một mô hình lớn hơn — chẳng hạn bổ sung thành phần phi tuyến, hiệu ứng nhóm phân cấp hoặc các số hạng tương tác có điều chuẩn. Ưu điểm của hướng này là tạo ra một khung suy luận thống nhất thay vì duy trì nhiều mô hình rời rạc; rủi ro là tăng độ phức tạp tính toán và đòi hỏi kiểm tra chặt chẽ hơn để tránh quá khớp.&lt;/p&gt;

&lt;p&gt;Có thể tóm tắt ngắn gọn: chọn mô hình xử lý sự cạnh tranh giữa các mô hình; kết hợp mô hình xử lý độ bất định giữa các mô hình; còn mở rộng mô hình xử lý sự thiếu hụt về cấu trúc của tập mô hình hiện có.&lt;/p&gt;

&lt;h2 id=&quot;5-quy-tắc-lựa-chọn-chiến-lược-trong-thực-hành&quot;&gt;5. Quy tắc lựa chọn chiến lược trong thực hành&lt;/h2&gt;

&lt;p&gt;Ta có thể tóm lược một quy tắc thực hành như sau: nếu chênh lệch hiệu năng dự báo đủ lớn và ổn định, ưu tiên chọn mô hình (selection); nếu nhiều mô hình gần ngang sức, ưu tiên kết hợp mô hình (averaging) để bảo toàn độ bất định; nếu mọi mô hình đều bộc lộ sai lệch cơ chế trong PPC, ưu tiên mở rộng mô hình (expansion) thay vì tranh luận xem mô hình nào “ít sai nhất”.&lt;/p&gt;

&lt;p&gt;Quy tắc này cần luôn đi kèm bước kiểm tra chẩn đoán (chẳng hạn Pareto \(k\) trong LOO) và kết quả phê bình mô hình. Một bảng xếp hạng gọn gàng không thể thay thế bằng chứng cho thấy mô hình vẫn đang bỏ sót cấu trúc quan trọng của dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;6-ví-dụ-tổng-hợp-cùng-dữ-liệu-ba-quyết-định-khác-nhau&quot;&gt;6. Ví dụ tổng hợp: Cùng dữ liệu, ba quyết định khác nhau&lt;/h2&gt;

&lt;p&gt;Giả sử ta có ba mô hình M1, M2, M3 và kết quả LOO cho thấy M1 và M2 sát nhau trong phạm vi sai số chuẩn, còn M3 kém hơn rõ rệt. Khi mục tiêu là dự báo ngắn hạn ổn định, kết hợp giữa M1 và M2 thường hợp lý hơn chọn một mô hình. Nếu mục tiêu là giải thích cơ chế và M1 đơn giản hơn đáng kể, ta vẫn có thể chọn M1 với điều kiện báo cáo rõ độ bất định mô hình còn lại. Ngược lại, nếu PPC cho thấy cả M1 lẫn M2 đều sai lệch ở phần đuôi, quyết định đúng nhất không phải chọn hay trộn, mà là mở rộng mô hình để sửa trực tiếp cơ chế sinh dữ liệu.&lt;/p&gt;

&lt;p&gt;Ví dụ này cho thấy so sánh mô hình là bài toán ra quyết định đa mục tiêu: cân bằng giữa dự báo, khả năng diễn giải, chi phí triển khai và tính trung thực với độ bất định.&lt;/p&gt;

&lt;h2 id=&quot;7-kết-luận-bài-83&quot;&gt;7. Kết luận bài 8.3&lt;/h2&gt;

&lt;p&gt;Không tồn tại một chiến lược so sánh mô hình duy nhất đúng cho mọi tình huống. Selection, averaging và expansion là ba công cụ bổ sung lẫn nhau trong cùng một quy trình Bayes. Năng lực của người phân tích nằm ở việc nhận biết đúng lúc nào nên thu gọn bằng chọn mô hình, lúc nào nên bảo toàn độ bất định bằng kết hợp mô hình, và lúc nào cần tái thiết kế mô hình để khắc phục sai lệch cơ chế.&lt;/p&gt;

&lt;p&gt;Bài tiếp theo: &lt;strong&gt;Phân tích quyết định Bayes (Bayesian Decision Analysis)&lt;/strong&gt;, chuyển kết quả suy luận thành hành động tối ưu dưới một hàm mất mát cụ thể.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tính-dự-báo-và-phương-sai-khi-kết-hợp-mô-hình-stacking--bma&quot;&gt;Giải thích: Tính dự báo và phương sai khi Kết hợp mô hình (Stacking / BMA)&lt;/h2&gt;

&lt;p&gt;Khi hai mô hình ngang sức nhau (ví dụ \(\Delta\text{elpd} &amp;lt; 2\,\mathrm{SE}\)), hãy đi chậm qua 3 bước để kết hợp dự báo thay vì chọn cứng:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Xác định trọng số \(w_1, \dots, w_K\)&lt;/strong&gt; (\(\sum w_k = 1, w_k \ge 0\)) từ Bayesian Stacking hoặc trọng số Akaike/Pseudo-BMA.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính trung bình dự báo kết hợp:&lt;/strong&gt; \(\mu_{\text{comb}} = \sum_{k=1}^K w_k \mu_k\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính phương sai dự báo kết hợp (cộng cả độ bất đồng giữa các mô hình!):&lt;/strong&gt;
\(\sigma_{\text{comb}}^2 = \sum_{k=1}^K w_k \sigma_k^2 + \sum_{k=1}^K w_k (\mu_k - \mu_{\text{comb}})^2.\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-trộn-dự-báo-doanh-số-từ-2-mô-hình-theo-trọng-số-stacking&quot;&gt;Ví dụ tính toán làm từng bước: Trộn dự báo doanh số từ 2 mô hình theo trọng số Stacking&lt;/h3&gt;

&lt;p&gt;Giả sử hai mô hình dự báo doanh số quý tới (tỷ VNĐ) có điểm LOO rất sát nhau, với trọng số Stacking là \(w_1 = 0.60\) và \(w_2 = 0.40\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mô hình 1 (tuyến tính): \(\mu_1 = 100\), \(\sigma_1 = 5\) (\(\sigma_1^2 = 25\)).&lt;/li&gt;
  &lt;li&gt;Mô hình 2 (phi tuyến): \(\mu_2 = 110\), \(\sigma_2 = 5\) (\(\sigma_2^2 = 25\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Thành phần&lt;/th&gt;
      &lt;th&gt;Công thức&lt;/th&gt;
      &lt;th&gt;Giá trị tính tay&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Trung bình kết hợp \(\mu_{\text{comb}}\)&lt;/td&gt;
      &lt;td&gt;\(0.6(100) + 0.4(110)\)&lt;/td&gt;
      &lt;td&gt;\(60 + 44 = 104.0\text{ tỷ}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Phương sai nội mô hình&lt;/td&gt;
      &lt;td&gt;\(0.6(25) + 0.4(25)\)&lt;/td&gt;
      &lt;td&gt;\(25.0\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Phương sai bất đồng giữa 2 mô hình&lt;/td&gt;
      &lt;td&gt;\(0.6(100 - 104)^2 + 0.4(110 - 104)^2\)&lt;/td&gt;
      &lt;td&gt;\(0.6(16) + 0.4(36) = 9.6 + 14.4 = 24.0\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Tổng phương sai &amp;amp; Độ lệch chuẩn&lt;/td&gt;
      &lt;td&gt;\(\sigma_{\text{comb}}^2 = 25 + 24 = 49\)&lt;/td&gt;
      &lt;td&gt;\(\sigma_{\text{comb}} = \sqrt{49} = 7.0\text{ tỷ}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Nhìn vào con số \(7.0\text{ tỷ}\) so với \(5.0\text{ tỷ}\): nếu chỉ chọn Mô hình 1, bạn sẽ báo cáo độ bất định \(\pm 5\text{ tỷ}\) (quá tự tin). Kết hợp mô hình tự động mở rộng độ lệch chuẩn lên \(\pm 7\text{ tỷ}\) để phản ánh trung thực sự bất đồng giữa hai giả định cấu trúc!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhầm rằng Stacking hay Model Averaging luôn cho ra dự báo có phương sai &lt;em&gt;nhỏ hơn&lt;/em&gt; từng mô hình đơn lẻ. Khi các mô hình bất đồng mạnh về tâm dự báo, phương sai tổng có thể &lt;em&gt;lớn hơn&lt;/em&gt; — và đó chính là dấu hiệu trung thực, giúp tránh bất ngờ ngoài mẫu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu hai mô hình hoàn toàn đồng ý về tâm dự báo (\(\mu_1 = \mu_2 = 104\)), số hạng bất đồng bằng \(0\) và \(\sigma_{\text{comb}} = 5.0\text{ tỷ}\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qwF-st2NGTU&quot;&gt;Statistical Rethinking 2023 - 20 - Horoscopes&lt;/a&gt; — Richard McElreath, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giải thích vì sao bảng xếp hạng mô hình không phải lời tiên tri, củng cố lập luận không chọn kẻ thắng bằng mọi giá.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=707hT6qYghw&quot;&gt;16a Prediction and Model Averaging&lt;/a&gt; — Philip Ramsey, English. Minh họa phương pháp kết hợp dự báo giữa nhiều mô hình thay vì chỉ chọn một mô hình duy nhất.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Nv2rm1s9q6I&quot;&gt;Statistical Rethinking 2026 - Lecture B02 - Multilevel Model Expansion&lt;/a&gt; — Richard McElreath, English. Trình bày chiến lược mở rộng mô hình nhiều tầng, đặt cạnh hai hướng selection và averaging.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Khi hai mô hình có chênh lệch LOO rất nhỏ so với sai số chuẩn, vì sao việc chọn cứng một mô hình có thể kém trung thực hơn kết hợp mô hình?&lt;/li&gt;
  &lt;li&gt;Trong tình huống nào chiến lược mở rộng mô hình (expansion) tốt hơn cả selection lẫn averaging?&lt;/li&gt;
  &lt;li&gt;Nếu mục tiêu chính là diễn giải nhân quả, thứ tự ưu tiên giữa các chiến lược sẽ thay đổi ra sao so với mục tiêu dự báo thuần túy?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Yao, Y., et al. (2018). “Using stacking to average Bayesian predictive distributions.” &lt;em&gt;Bayesian Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter08/08_04_decision_analysis/&quot;&gt;8.4 Bayesian Decision Analysis&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 8.2: Information Criteria - WAIC và LOO</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter08/08_02_information_criteria/"/>
   <updated>2025-01-04T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter08/08_02_information_criteria</id>
   <content type="html">&lt;p&gt;Thêm tham số vào mô hình hầu như lúc nào cũng làm tăng độ khớp trên tập dữ liệu hiện có, nhưng lại có thể phá hỏng khả năng dự báo trên dữ liệu mới. Làm sao ước lượng được &lt;strong&gt;độ chính xác dự báo ngoài mẫu (out-of-sample predictive accuracy)&lt;/strong&gt; mà không phải chạy lại MCMC hàng trăm lần như kiểm định chéo &lt;em&gt;leave-one-out&lt;/em&gt; thủ công?&lt;/p&gt;

&lt;p&gt;Công trình đột phá của Sumio Watanabe (2010, WAIC) và Aki Vehtari, Andrew Gelman, Jonah Gabry (2017, PSIS-LOO) đã giải quyết trọn vẹn bài toán này: chỉ từ &lt;strong&gt;một&lt;/strong&gt; lần chạy MCMC duy nhất, ta có thể ước lượng chính xác hiệu năng dự báo ngoài mẫu kèm cả sai số chuẩn và tín hiệu cảnh báo chẩn đoán (chỉ số Pareto \(k\)).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài học này, bạn sẽ hiểu WAIC và LOO như những công cụ xấp xỉ năng lực dự báo ngoài mẫu của mô hình Bayes, đồng thời biết đọc kết quả kèm theo độ bất định ước lượng thay vì xếp hạng một cách cứng nhắc. Trọng tâm của bài là lập luận phương pháp: vì sao cần ưu tiên tiêu chí dự báo ngoài mẫu, khi nào chênh lệch giữa các mô hình đủ lớn để đưa ra kết luận, và khi nào nên chuyển từ chọn một mô hình sang kết hợp nhiều mô hình (model averaging).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-elpd-waic-psis-loo-và-chẩn-đoán-pareto-k&quot;&gt;Kiến thức cần nhớ: ELPD, WAIC, PSIS-LOO và Chẩn đoán Pareto \(k\)&lt;/h2&gt;

&lt;p&gt;So sánh mô hình Bayes hiện đại xoay quanh ba trụ cột toán học cốt lõi:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mật độ dự báo log kỳ vọng (ELPD — Expected Log Pointwise Predictive Density):&lt;/strong&gt; Thước đo mục tiêu cho khả năng dự báo ngoài mẫu: \(\text{elpd} = \sum_{i=1}^n \mathbb{E}_{\tilde y_i}[\log p(\tilde y_i \mid y)]\). Điểm ELPD càng &lt;strong&gt;cao&lt;/strong&gt; (càng ít âm) thì mô hình dự báo càng tốt (khác với thang deviance/AIC càng thấp càng tốt).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;WAIC (Widely Applicable Information Criterion):&lt;/strong&gt; Tách ELPD thành độ khớp trong mẫu (&lt;strong&gt;lppd&lt;/strong&gt;) trừ đi số tham số hiệu dụng (&lt;strong&gt;\(p_{\text{WAIC}}\)&lt;/strong&gt; — tính bằng tổng phương sai của log-likelihood hậu nghiệm từng điểm). Khác với AIC hay DIC, WAIC tận dụng toàn bộ phân phối hậu nghiệm thay vì chỉ một ước lượng điểm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;PSIS-LOO &amp;amp; Chỉ số Pareto \(k\):&lt;/strong&gt; Xấp xỉ kiểm định chéo bỏ-từng-điểm (&lt;em&gt;leave-one-out&lt;/em&gt;) bằng lấy mẫu quan trọng làm mượt theo phân phối Pareto tổng quát (&lt;em&gt;Pareto Smoothed Importance Sampling&lt;/em&gt;). Chỉ số \(\hat k_i\) là công cụ chẩn đoán cực kỳ quý giá: \(\hat k_i &amp;lt; 0.5\) là rất tin cậy, \(0.5 \le \hat k_i \le 0.7\) chấp nhận được, còn \(\hat k_i &amp;gt; 0.7\) cảnh báo điểm dữ liệu \(i\) có ảnh hưởng quá lớn — cần tính LOO trực tiếp hoặc xem lại mô hình.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-từ-độ-khớp-trong-mẫu-sang-dự-báo-ngoài-mẫu&quot;&gt;1. Từ độ khớp trong mẫu sang dự báo ngoài mẫu&lt;/h2&gt;

&lt;p&gt;Vấn đề kinh điển của so sánh mô hình là mô hình càng linh hoạt càng dễ đạt độ khớp tốt trên tập huấn luyện, nhưng chính sự linh hoạt đó có thể làm suy giảm khả năng dự báo trên dữ liệu mới. Do đó, đại lượng đáng quan tâm không phải sai số trong mẫu mà là mật độ dự báo dạng log ngoài mẫu (expected log predictive density). Ở dạng từng điểm quan sát (pointwise), ta xét tổng:&lt;/p&gt;

\[\text{elpd} = \sum_{i=1}^n \log p(y_i\mid y_{-i}),\]

&lt;p&gt;trong đó mỗi quan sát \(y_i\) được đánh giá như một điểm dữ liệu mới khi mô hình đã học từ toàn bộ phần dữ liệu còn lại \(y_{-i}\).&lt;/p&gt;

&lt;p&gt;Ý tưởng này chặt chẽ về mặt lý thuyết nhưng rất tốn kém nếu phải khớp lại mô hình nhiều lần; WAIC và PSIS-LOO ra đời như hai phương pháp thực dụng để xấp xỉ cùng mục tiêu đó.&lt;/p&gt;

&lt;h2 id=&quot;2-waic-xấp-xỉ-hoàn-toàn-theo-hướng-bayes-cho-độ-chính-xác-dự-báo&quot;&gt;2. WAIC: Xấp xỉ hoàn toàn theo hướng Bayes cho độ chính xác dự báo&lt;/h2&gt;

&lt;p&gt;WAIC được viết dưới dạng:&lt;/p&gt;

\[\text{WAIC}=-2\,(\text{lppd}-p_{\text{WAIC}}),\]

&lt;p&gt;trong đó \(\text{lppd}\) đo độ khớp dự báo trên từng điểm dữ liệu, còn \(p_{\text{WAIC}}\) là số tham số hiệu dụng đóng vai trò phạt độ phức tạp để hạn chế quá khớp. Khi so sánh các mô hình trên cùng tập dữ liệu, giá trị WAIC thấp hơn tương ứng với năng lực dự báo tốt hơn (tương đương với \(\text{elpd}\) lớn hơn).&lt;/p&gt;

&lt;p&gt;Cần lưu ý rằng WAIC không phải một thang điểm tuyệt đối: nó chỉ có ý nghĩa khi đặt trong tương quan giữa các mô hình cạnh tranh và phải đi kèm sai số chuẩn của độ chênh lệch.&lt;/p&gt;

&lt;h2 id=&quot;3-psis-loo-chuẩn-tham-chiếu-gần-thực-tế-hơn&quot;&gt;3. PSIS-LOO: Chuẩn tham chiếu gần thực tế hơn&lt;/h2&gt;

&lt;p&gt;Kiểm định chéo loại từng phần tử (LOO-CV) lý tưởng đòi hỏi bỏ lần lượt từng quan sát và khớp lại mô hình, trong khi PSIS-LOO dùng kỹ thuật lấy mẫu trọng số có làm mượt Pareto (Pareto-smoothed importance sampling) để xấp xỉ quy trình đó mà không cần khớp lại toàn bộ. Vì bám sát định nghĩa dự báo ngoài mẫu hơn, PSIS-LOO thường được ưu tiên trong quy trình Bayes hiện đại, với điều kiện chỉ số chẩn đoán Pareto \(k\) cho thấy phép xấp xỉ đủ tin cậy.&lt;/p&gt;

&lt;p&gt;Tóm lại: WAIC nhanh và thuận tiện; PSIS-LOO thường đáng tin cậy hơn; và cả hai đều phải được diễn giải cùng độ bất định ước lượng.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/chapter08_waic_loo_comparison.png&quot; alt=&quot;WAIC and LOO comparison with uncertainty&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-waic-và-loo-ước-lượng-chất-lượng-dự-báo-ngoài-mẫu&quot;&gt;Thử nghiệm: WAIC và LOO ước lượng chất lượng dự báo ngoài mẫu&lt;/h3&gt;

&lt;p&gt;Tăng bậc đa thức từng bước để quan sát \(\text{lppd}\) trong mẫu luôn tăng, còn \(\text{elpd}\) theo WAIC và LOO (bám sát \(\text{elpd}\) trên dữ liệu mới) đạt đỉnh rồi giảm. Bảng kết quả hiển thị \(p_{\text{waic}}\), \(\Delta\text{elpd}\) và sai số chuẩn.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;ic-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;waic&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-đọc-bảng-so-sánh-mô-hình-chênh-lệch-và-độ-bất-định&quot;&gt;4. Đọc bảng so sánh mô hình: Chênh lệch và độ bất định&lt;/h2&gt;

&lt;p&gt;Giả sử ba mô hình cho kết quả theo thang \(\text{elpd}\) như sau (giá trị càng cao càng tốt):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Mô hình A: \(\text{elpd} = -221\), \(\text{SE} = 5\)&lt;/li&gt;
  &lt;li&gt;Mô hình B: \(\text{elpd} = -220\), \(\text{SE} = 5.5\)&lt;/li&gt;
  &lt;li&gt;Mô hình C: \(\text{elpd} = -229\), \(\text{SE} = 6\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Kết luận hợp lý là C kém hơn rõ rệt so với A và B, còn A và B gần như tương đương vì chênh lệch 1 điểm nhỏ hơn nhiều so với độ bất định đi kèm. Trong trường hợp này, tuyên bố “B thắng” là kết luận quá mức; cách xử lý hợp lý hơn là xem A và B như nhóm mô hình ngang sức, sau đó cân nhắc kết hợp mô hình (averaging) hoặc ưu tiên mô hình dễ diễn giải hơn nếu mục tiêu truyền đạt là quan trọng.&lt;/p&gt;

&lt;h2 id=&quot;5-chỉ-số-pareto-k-điều-kiện-tin-cậy-của-psis-loo&quot;&gt;5. Chỉ số Pareto \(k\): Điều kiện tin cậy của PSIS-LOO&lt;/h2&gt;

&lt;p&gt;Với PSIS-LOO, chỉ số Pareto \(k\) cho biết các trọng số lấy mẫu quan trọng có ổn định hay không. Ngưỡng thực hành thường dùng gồm:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(k&amp;lt;0.5\): phép xấp xỉ ổn định,&lt;/li&gt;
  &lt;li&gt;\(0.5\le k\le 0.7\): có thể sử dụng nhưng cần thận trọng,&lt;/li&gt;
  &lt;li&gt;\(k&amp;gt;0.7\): phép xấp xỉ có thể kém tin cậy, cần kiểm tra lại các điểm ảnh hưởng lớn và cân nhắc phương án thay thế.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Pareto \(k\) không phải chi tiết phụ: nếu bước chẩn đoán này không đạt, bảng xếp hạng LOO dù trông gọn gàng vẫn không đủ cơ sở vững chắc để ra quyết định.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-waic--psis-loo-so-sánh-δelpd-và-chẩn-đoán-điểm-ảnh-hưởng-pareto-k&quot;&gt;Video ngắn: WAIC &amp;amp; PSIS-LOO: So sánh ΔELPD và Chẩn đoán Điểm ảnh hưởng Pareto k&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch08-02a-waic-loo-pareto-k.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 13 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): đối chiếu ΔELPD với sai số chuẩn SE để quyết định chọn mô hình, đồng thời soi điểm ngoại lai vượt ngưỡng k &amp;gt; 0.7.&lt;/p&gt;

&lt;h2 id=&quot;6-ví-dụ-phương-pháp-luận-khi-nào-đủ-bằng-chứng-để-chọn-mô-hình&quot;&gt;6. Ví dụ phương pháp luận: Khi nào đủ bằng chứng để chọn mô hình&lt;/h2&gt;

&lt;p&gt;Giả sử mô hình đứng đầu có \(\text{elpd}\) cao hơn mô hình thứ hai 6 điểm, với sai số chuẩn của chênh lệch khoảng 2. Khi đó ta có khoảng cách đủ thuyết phục để chọn mô hình đứng đầu cho mục tiêu dự báo. Ngược lại, nếu chênh lệch chỉ là 1.5 trong khi sai số chuẩn là 2.2, kết luận hợp lý nên là “chưa đủ bằng chứng phân biệt rõ”, và nên cân nhắc kết hợp dự báo hoặc giữ nhiều mô hình cho các mục tiêu khác nhau.&lt;/p&gt;

&lt;p&gt;Nói cách khác, so sánh mô hình trong thống kê Bayes là bài toán suy luận dưới bất định, không phải cuộc thi chấm điểm dựa trên một con số duy nhất.&lt;/p&gt;

&lt;h2 id=&quot;7-thực-hành-tốt-khi-dùng-waic-và-loo&quot;&gt;7. Thực hành tốt khi dùng WAIC và LOO&lt;/h2&gt;

&lt;p&gt;Có ba nguyên tắc thực hành cốt lõi. Thứ nhất, luôn so sánh các mô hình trên cùng một tập dữ liệu và cùng biến mục tiêu để chênh lệch có ý nghĩa. Thứ hai, luôn đọc đồng thời giá trị ước lượng và sai số chuẩn thay vì chỉ nhìn thứ hạng. Thứ ba, khi nhiều mô hình đạt hiệu năng sát nhau, hãy chuyển từ tư duy “chọn duy nhất mô hình đứng đầu” sang tư duy kết hợp dự báo.&lt;/p&gt;

&lt;p&gt;Trong tổng thể quy trình Bayes, WAIC và LOO không thay thế PPC: một mô hình có điểm dự báo tốt hơn vẫn có thể sai lệch cơ chế ở những vùng quan trọng của bài toán. Vì vậy, phê bình mô hình (PPC) và so sánh mô hình (WAIC/LOO) cần được sử dụng bổ trợ cho nhau.&lt;/p&gt;

&lt;h2 id=&quot;8-kết-luận-bài-82&quot;&gt;8. Kết luận bài 8.2&lt;/h2&gt;

&lt;p&gt;WAIC và LOO cung cấp thước đo định lượng để so sánh năng lực dự báo ngoài mẫu giữa các mô hình, nhưng giá trị lớn nhất của chúng nằm ở kỷ luật diễn giải: luôn đọc chênh lệch kèm độ bất định, luôn kiểm tra chẩn đoán của phép xấp xỉ, và luôn gắn lựa chọn mô hình với mục tiêu dự báo thay vì chọn máy móc theo thứ hạng.&lt;/p&gt;

&lt;p&gt;Bài tiếp theo: &lt;strong&gt;Các chiến lược so sánh mô hình (Model Comparison Strategies)&lt;/strong&gt;, đi sâu vào lựa chọn giữa chọn mô hình (selection), kết hợp mô hình (averaging) và mở rộng mô hình (expansion).&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tự-tính-waic-bằng-tay-và-đọc-bảng-chênh-lệch-elpd-có-sai-số-chuẩn&quot;&gt;Giải thích: Tự tính WAIC bằng tay và đọc bảng chênh lệch ELPD có sai số chuẩn&lt;/h2&gt;

&lt;p&gt;Để thực sự hiểu WAIC và LOO đang tính gì bên dưới hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;az.compare()&lt;/code&gt;, hãy đi chậm qua 4 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lập ma trận log-likelihood&lt;/strong&gt; cỡ \(S \times n\) (hàng là mẫu hậu nghiệm \(s\), cột là điểm dữ liệu \(i\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính \(\text{lppd}_i = \log\!\left(\frac{1}{S}\sum_{s=1}^S p(y_i \mid \theta^{(s)})\right)\)&lt;/strong&gt; cho từng điểm rồi cộng lại.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính phạt độ phức tạp \(p_{\text{WAIC}} = \sum_{i=1}^n \mathrm{Var}_{s}(\log p(y_i \mid \theta^{(s)}))\):&lt;/strong&gt; Điểm nào có log-likelihood dao động mạnh qua các mẫu hậu nghiệm thì đóng góp phạt lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính \(\widehat{\text{elpd}}_{\text{WAIC}} = \text{lppd} - p_{\text{WAIC}}\)&lt;/strong&gt; và khi so hai mô hình, luôn đối chiếu \(\Delta\text{elpd}\) với sai số chuẩn \(\mathrm{SE}(\Delta\text{elpd})\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-tính-textlppd_i-và-p_textwaici-cho-1-điểm-dữ-liệu-với-s--2-mẫu-hậu-nghiệm&quot;&gt;Ví dụ tính toán làm từng bước: Tính \(\text{lppd}_i\) và \(p_{\text{WAIC},i}\) cho 1 điểm dữ liệu với \(S = 2\) mẫu hậu nghiệm&lt;/h3&gt;

&lt;p&gt;Giả sử tại điểm dữ liệu \(i\), hai mẫu hậu nghiệm \(\theta^{(1)}, \theta^{(2)}\) cho xác suất hợp lý là \(p_1 = 0.20\) và \(p_2 = 0.40\) (tương ứng \(\log p_1 \approx -1.6094\) và \(\log p_2 \approx -0.9163\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Bước tính&lt;/th&gt;
      &lt;th&gt;Công thức&lt;/th&gt;
      &lt;th&gt;Giá trị tính tay&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Độ khớp điểm \(\text{lppd}_i\)&lt;/td&gt;
      &lt;td&gt;\(\ln\!\left(\frac{0.20 + 0.40}{2}\right) = \ln(0.30)\)&lt;/td&gt;
      &lt;td&gt;\(-1.2040\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Trung bình log-likelihood&lt;/td&gt;
      &lt;td&gt;\(\frac{-1.6094 + (-0.9163)}{2}\)&lt;/td&gt;
      &lt;td&gt;\(-1.2629\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Phạt độ phức tạp \(p_{\text{WAIC}, i}\) (phương sai mẫu \(S-1=1\))&lt;/td&gt;
      &lt;td&gt;\(\frac{(-1.6094+1.2629)^2 + (-0.9163+1.2629)^2}{2-1}\)&lt;/td&gt;
      &lt;td&gt;\(0.2402\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Đóng góp ELPD của điểm \(i\)&lt;/td&gt;
      &lt;td&gt;\(\text{lppd}_i - p_{\text{WAIC}, i}\)&lt;/td&gt;
      &lt;td&gt;\(-1.2040 - 0.2402 = -1.4442\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Khi so sánh hai mô hình trên cả tập dữ liệu: giả sử Mô hình A có \(\text{elpd}_{\text{LOO}} = -120.5\) và Mô hình B có \(\text{elpd}_{\text{LOO}} = -124.0\) (chênh lệch \(\Delta\text{elpd} = 3.5\)) với \(\mathrm{SE}(\Delta\text{elpd}) = 4.2\). Vì \(\Delta\text{elpd} &amp;lt; 2\,\mathrm{SE}\), sự chênh lệch này &lt;strong&gt;chưa đủ bằng chứng mạnh&lt;/strong&gt; để loại bỏ Mô hình B!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhìn thấy Mô hình A có ELPD cao hơn Mô hình B dù chỉ \(0.8\) điểm (trong khi \(\mathrm{SE} = 3.0\)) rồi vội tuyên bố “Mô hình A thắng tuyệt đối”. Chênh lệch nhỏ hơn \(2\,\mathrm{SE}\) thường nằm trong vùng nhiễu lấy mẫu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu \(\Delta\text{elpd} = 18.0\) và \(\mathrm{SE}(\Delta\text{elpd}) = 4.5\), tỷ số \(z = 18.0 / 4.5 = 4.0\) — đây là bằng chứng rất rõ ràng cho thấy mô hình đứng đầu vượt trội về dự báo ngoài mẫu.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=xS4jDHQfP2o&quot;&gt;Evaluating model fit through AIC, DIC, WAIC and LOO-CV&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Đặt AIC, DIC, WAIC và LOO-CV cạnh nhau để so sánh các cách ước lượng năng lực dự báo ngoài mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=D0kVMie93Yk&quot;&gt;BDA 2019 Lecture 9.1 PSIS-LOO and K-fold cross-validation&lt;/a&gt; — Aki Vehtari, English. Trình bày PSIS-LOO và kiểm định chéo K-fold, củng cố lý do ưu tiên LOO hơn độ khớp trong mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=h4g5KUWRzyg&quot;&gt;31- Pareto k diagnostics in R&lt;/a&gt; — Horizon 2 Reach, English. Giải thích chẩn đoán Pareto \(k\) — điều kiện cần kiểm tra trước khi tin tưởng ước lượng PSIS-LOO.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao chênh lệch WAIC/LOO nhỏ hơn sai số chuẩn của chênh lệch không đủ cơ sở để khẳng định một mô hình vượt trội hơn?&lt;/li&gt;
  &lt;li&gt;Nếu một mô hình đứng hạng nhất nhưng có nhiều điểm dữ liệu mang chỉ số Pareto \(k&amp;gt;0.7\), bạn sẽ xử lý kết quả đó như thế nào?&lt;/li&gt;
  &lt;li&gt;Trong những tình huống nào bạn nên ưu tiên kết hợp mô hình (model averaging) thay vì chọn một mô hình duy nhất?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Vehtari, A., Gelman, A., &amp;amp; Gabry, J. (2017). “Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC.” &lt;em&gt;Statistics and Computing&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition), Chapter 7.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter08/08_03_model_comparison/&quot;&gt;8.3 Model Comparison Strategies&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 8.1: Posterior Predictive Checks - Model Criticism</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter08/08_01_ppc/"/>
   <updated>2025-01-04T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter08/08_01_ppc</id>
   <content type="html">&lt;p&gt;Một cạm bẫy cực kỳ nguy hiểm trong thực hành Bayes là sự an tâm giả tạo: chuỗi MCMC hội tụ hoàn hảo (\(\hat R = 1.00\)), ESS lên đến hàng nghìn, biểu đồ trace mượt như dải lụa — nhưng toàn bộ mô hình lại mô tả sai hoàn toàn thực tế! Hội tụ MCMC chỉ chứng minh thuật toán đã &lt;em&gt;tính đúng&lt;/em&gt; hậu nghiệm của mô hình bạn viết ra, hoàn toàn không chứng minh mô hình đó &lt;em&gt;phù hợp&lt;/em&gt; với dữ liệu thật.&lt;/p&gt;

&lt;p&gt;Đó là lý do &lt;strong&gt;Kiểm tra dự báo hậu nghiệm (Posterior Predictive Checks — PPC)&lt;/strong&gt; — do Donald Rubin và Andrew Gelman hệ thống hóa — trở thành bước phản biện không thể thiếu: nếu mô hình của bạn thực sự nắm bắt được cơ chế sinh dữ liệu, thì dữ liệu mô phỏng từ hậu nghiệm phải có hình dáng và đặc trưng thống kê tương đồng với dữ liệu quan sát thật.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài học này, bạn sẽ hiểu &lt;strong&gt;kiểm tra dự báo hậu nghiệm (Posterior Predictive Checks — PPC)&lt;/strong&gt; như trục trung tâm của bước phê bình mô hình (model criticism) trong quy trình Bayes: ta không chỉ đánh giá mô hình dựa trên mức độ khớp dữ liệu cũ, mà dựa trên việc nó có tái tạo được những đặc điểm quan trọng của dữ liệu quan sát hay không. Bạn cũng sẽ nắm cách chuyển một nghi ngờ về mô hình (chẳng hạn đuôi quá mỏng, phương sai thay đổi, hay quan hệ phi tuyến) thành phép kiểm tra định lượng tương ứng để không phải dựa vào cảm tính trực quan.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-phản-biện-mô-hình-thống-kê-kiểm-định-và-trị-số-p-bayes&quot;&gt;Kiến thức cần nhớ: Phản biện Mô hình, Thống kê kiểm định và Trị số p Bayes&lt;/h2&gt;

&lt;p&gt;PPC nối chặt lý thuyết xác suất hậu nghiệm với khoa học thực nghiệm qua ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối dự báo hậu nghiệm (Posterior Predictive Distribution):&lt;/strong&gt; Định nghĩa bởi tích phân \(p(y^{\text{rep}} \mid y) = \int p(y^{\text{rep}} \mid \theta) p(\theta \mid y)\,d\theta\). Trong thực tế với \(S\) mẫu hậu nghiệm \(\theta^{(1)}, \dots, \theta^{(S)}\), ta chỉ cần sinh từng bộ dữ liệu giả lập \(y^{\text{rep}(s)} \sim p(\cdot \mid \theta^{(s)})\) rồi đối chiếu với dữ liệu thật \(y\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chọn thống kê kiểm định \(T(y)\) có mục tiêu:&lt;/strong&gt; Đừng kiểm tra PPC bằng đúng đại lượng mà mô hình tự động khớp (ví dụ trung bình trong mô hình Gaussian có hệ số chặn — luôn khớp gần hoàn hảo!). Hãy chọn các thống kê nhạy với điểm yếu tiềm ẩn: phương sai, độ lệch, tỷ lệ số 0, giá trị cực đại/cực tiểu, hoặc tự tương quan.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trị số p Bayes (Bayesian p-value):&lt;/strong&gt; Định nghĩa \(p_B = P(T(y^{\text{rep}}) \ge T(y) \mid y) \approx \frac{1}{S}\sum_{s=1}^S \mathbb{I}(T(y^{\text{rep}(s)}) \ge T(y))\). Khác với \(p\)-value tần suất, ta muốn \(p_B\) nằm vùng giữa (ví dụ \(0.10 \text{–} 0.90\)); giá trị cực đoan gần \(0\) hoặc \(1\) báo hiệu mô hình bỏ sót một đặc trưng quan trọng của dữ liệu.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-vì-sao-hậu-nghiệm-đẹp-vẫn-chưa-đủ&quot;&gt;1. Vì sao hậu nghiệm đẹp vẫn chưa đủ&lt;/h2&gt;

&lt;p&gt;Trong thực hành, một phân phối hậu nghiệm ổn định chỉ cho biết thuật toán lấy mẫu đang khám phá tốt phân phối hậu nghiệm của tham số &lt;em&gt;dưới mô hình đã giả định&lt;/em&gt;; nó không chứng minh rằng mô hình đó mô tả đúng cơ chế sinh dữ liệu. Nói ngắn gọn, hội tụ MCMC là điều kiện về tính toán, còn mức độ phù hợp của mô hình là điều kiện về khoa học dữ liệu. PPC ra đời để kết nối hai lớp điều kiện này.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“All models are wrong, but some are useful.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Câu nói nổi tiếng của George Box có thể hiểu theo ngôn ngữ PPC như sau: một mô hình hữu ích là mô hình có khả năng sinh ra dữ liệu giống với dữ liệu thật trên đúng những khía cạnh liên quan đến câu hỏi quyết định.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học-của-ppc&quot;&gt;2. Nền tảng toán học của PPC&lt;/h2&gt;

&lt;p&gt;Phân phối dự báo hậu nghiệm được định nghĩa bởi:&lt;/p&gt;

\[p(\tilde y\mid y)=\int p(\tilde y\mid\theta)\,p(\theta\mid y)\,d\theta.\]

&lt;p&gt;Trong đó, \(p(\theta\mid y)\) biểu diễn độ bất định của tham số sau khi đã quan sát dữ liệu, còn \(p(\tilde y\mid\theta)\) mô tả cách dữ liệu mới được sinh ra ứng với tham số \(\theta\). Về bản chất, PPC so sánh dữ liệu quan sát \(y\) với một tập lớn các bản sao mô phỏng \(\tilde y^{(s)}\) rút ra từ phân phối này. Nếu mô hình phản ánh hợp lý cơ chế sinh dữ liệu, dữ liệu thật không nên trông như một ngoại lệ bất thường dưới chính mô hình đó.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_process_workflow.png&quot; alt=&quot;PPC Process Workflow&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-logic-kiểm-tra-có-cấu-trúc&quot;&gt;3. Logic kiểm tra có cấu trúc&lt;/h2&gt;

&lt;p&gt;Thực hiện PPC hiệu quả không phải là vẽ thật nhiều biểu đồ, mà là đặt đúng câu hỏi kiểm tra theo trình tự hợp lý. Ta bắt đầu từ hình dạng tổng thể của phân phối, tiếp tục kiểm tra các đặc trưng trung tâm và độ phân tán, sau đó đi sâu vào phần đuôi, rồi mới chuyển sang kiểm tra có điều kiện theo biến dự báo hoặc theo nhóm. Trình tự này giúp tránh kết luận vội rằng mô hình đã ổn chỉ vì trung bình khớp tốt, trong khi phần đuôi và phần dư lại cho thấy sai lệch hệ thống.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_workflow_diagram.png&quot; alt=&quot;PPC Workflow&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;31-kiểm-tra-phân-phối-tổng-thể&quot;&gt;3.1. Kiểm tra phân phối tổng thể&lt;/h3&gt;

&lt;p&gt;So sánh hàm mật độ (density) hoặc hàm phân phối tích lũy thực nghiệm (ECDF) giữa dữ liệu quan sát và dữ liệu dự báo hậu nghiệm là bước sàng lọc đầu tiên để phát hiện sai lệch lớn về vị trí, độ rộng và độ bất đối xứng. Nếu mô hình không vượt qua bước này, các phân tích tinh hơn phía sau thường mất ý nghĩa vì giả định nền đã sai.&lt;/p&gt;

&lt;h3 id=&quot;32-kiểm-tra-bằng-các-thống-kê-kiểm-định-mục-tiêu&quot;&gt;3.2. Kiểm tra bằng các thống kê kiểm định mục tiêu&lt;/h3&gt;

&lt;p&gt;Thay vì chỉ nhìn một chỉ số duy nhất, ta thường sử dụng một bộ thống kê kiểm định (test statistics):&lt;/p&gt;

\[T(y)\in\{\bar y,\operatorname{Var}(y),Q_{0.95}(y),\max(y),\operatorname{IQR}(y)\}.\]

&lt;p&gt;Mỗi thống kê trả lời một câu hỏi khác nhau: trung bình phản ánh vị trí trung tâm, phương sai phản ánh độ phân tán, còn phân vị cao và giá trị cực đại phản ánh hành vi phần đuôi. Một mô hình có thể vượt qua kiểm tra ở trung tâm nhưng thất bại hoàn toàn ở phần đuôi; do đó, với các bài toán liên quan đến rủi ro cực trị, kiểm tra phần đuôi là yêu cầu bắt buộc.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_multiple_test_statistics.png&quot; alt=&quot;Multiple Test Statistics&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;33-ví-dụ-định-lượng-trung-bình-đúng-nhưng-phần-đuôi-sai&quot;&gt;3.3. Ví dụ định lượng: Trung bình đúng nhưng phần đuôi sai&lt;/h3&gt;

&lt;p&gt;Giả sử dữ liệu thực tế có trung bình khoảng 20 và mô hình cũng tái tạo tốt mức trung bình này. Tuy nhiên, giá trị cực đại quan sát được là 61, trong khi các bản sao dự báo hậu nghiệm hiếm khi vượt quá 45. Kết luận khoa học chính xác không phải là “mô hình tốt”, mà là “mô hình phù hợp cho mức trung bình nhưng không phù hợp cho các biến cố cực trị”. Cùng một mô hình có thể chấp nhận được cho dự báo vận hành thường ngày nhưng không đủ tin cậy cho quản trị rủi ro đuôi.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-kiểm-tra-dự-báo-hậu-nghiệm&quot;&gt;Thử nghiệm: Kiểm tra dự báo hậu nghiệm&lt;/h3&gt;

&lt;p&gt;Mô phỏng các bản sao dữ liệu từ phân phối hậu nghiệm và đối chiếu với dữ liệu thực qua các thống kê kiểm tra.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;ppc-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-diễn-giải-trị-số-p-bayes-bayesian-p-value-đúng-ngữ-cảnh&quot;&gt;4. Diễn giải trị số p Bayes (Bayesian p-value) đúng ngữ cảnh&lt;/h2&gt;

&lt;p&gt;Với một thống kê kiểm định \(T(\cdot)\), trị số p Bayes (Bayesian p-value) được định nghĩa là:&lt;/p&gt;

\[p_B = P\big(T(\tilde y)\ge T(y)\mid y\big).\]

&lt;p&gt;Giá trị quanh 0.5 cho thấy dữ liệu quan sát nằm ở vùng điển hình của mô hình theo thống kê đang xét; giá trị quá gần 0 hoặc 1 gợi ý dữ liệu quan sát rơi vào vùng hiếm của thế giới mà mô hình sinh ra. Điểm cần lưu ý là \(p_B\) không phải phán quyết cuối cùng cho toàn bộ mô hình: nó chỉ phản ánh một khía cạnh kiểm tra cụ thể, nên luôn phải đọc kết hợp với biểu đồ và các thống kê khác.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-kiểm-tra-dự-báo-hậu-nghiệm-ppc--bayesian-p-value&quot;&gt;Video ngắn: Kiểm tra Dự báo Hậu nghiệm (PPC) &amp;amp; Bayesian p-value&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch08-01a-ppc-bayesian-pvalue.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 13 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): rút 500 bộ dữ liệu giả y_rep từ mô hình Poisson (phương sai quanh 3.2) đối chiếu với dữ liệu thật Var = 9.8 để bắt lỗi quá phân tán.&lt;/p&gt;

&lt;h2 id=&quot;5-dùng-ppc-để-chẩn-đoán-loại-sai-lệch-của-mô-hình&quot;&gt;5. Dùng PPC để chẩn đoán loại sai lệch của mô hình&lt;/h2&gt;

&lt;p&gt;Giá trị lớn nhất của PPC là giúp nhận diện mô hình đang sai &lt;em&gt;theo kiểu nào&lt;/em&gt;, chứ không chỉ sai nhiều hay ít. Trong hồi quy, ba sai lệch điển hình là phương sai thay đổi theo biến dự báo (heteroskedasticity), quan hệ phi tuyến bị ép thành tuyến tính, và hàm hợp lý có đuôi quá mỏng nên không sinh được giá trị ngoại lai (outliers). Ba lỗi này để lại những dấu hiệu trực quan rất khác nhau trên biểu đồ phần dư và biểu đồ Q-Q.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_model_inadequacy_detection.png&quot; alt=&quot;Model Inadequacy Detection&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_graphical_methods.png&quot; alt=&quot;Graphical PPC Methods&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;51-ví-dụ-mô-hình-chọn-sai-hàm-hợp-lý&quot;&gt;5.1. Ví dụ mô hình chọn sai hàm hợp lý&lt;/h3&gt;

&lt;p&gt;Nếu dữ liệu có các giá trị ngoại lai đáng kể nhưng mô hình lại dùng hàm hợp lý chuẩn (Normal), phân phối dự báo hậu nghiệm thường tái tạo kém phần đuôi và làm khoảng dự báo quá hẹp quanh trung tâm. Trong tình huống này, thay phân phối chuẩn bằng phân phối Student-t là điều chỉnh trực tiếp vào cơ chế sinh dữ liệu, cho phép mô hình tạo ra các quan sát ngoại lai với xác suất hợp lý hơn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_good_vs_bad_models.png&quot; alt=&quot;Good vs Bad PPC Models&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-nguyên-tắc-thực-hành-để-tránh-ppc-hình-thức&quot;&gt;6. Nguyên tắc thực hành để tránh PPC hình thức&lt;/h2&gt;

&lt;p&gt;Thực hành PPC hiệu quả có thể tóm gọn trong ba nguyên tắc. Thứ nhất, các thống kê kiểm tra phải gắn trực tiếp với câu hỏi quyết định — chẳng hạn bài toán rủi ro cần kiểm tra phần đuôi chứ không dừng ở trung bình. Thứ hai, luôn kết hợp kiểm tra toàn cục và kiểm tra có điều kiện, vì mô hình có thể khớp tốt ở mức tổng thể nhưng sai lệch nặng trên một vùng biến dự báo quan trọng. Thứ ba, PPC không dừng ở bước chẩn đoán mà phải dẫn đến chỉnh sửa mô hình: thay đổi hàm hợp lý, bổ sung thành phần phi tuyến, mô hình hóa phương sai thay đổi hoặc thêm cấu trúc phân nhóm khi còn dấu vết cấu trúc bị bỏ sót.&lt;/p&gt;

&lt;h2 id=&quot;7-kết-luận-bài-81&quot;&gt;7. Kết luận bài 8.1&lt;/h2&gt;

&lt;p&gt;PPC là cầu nối giữa suy luận tham số và phê bình mô hình: nó buộc ta kiểm chứng xem dữ liệu thật có thực sự phù hợp với thế giới mà mô hình giả định hay không. Một quy trình Bayes hoàn chỉnh không dừng lại ở phân phối hậu nghiệm của tham số, mà chỉ khép lại khi mô hình vượt qua các phép kiểm tra dự báo hậu nghiệm gắn với mục tiêu ứng dụng.&lt;/p&gt;

&lt;p&gt;Bài tiếp theo: &lt;strong&gt;Các tiêu chí thông tin (Information Criteria: WAIC, LOO)&lt;/strong&gt; để so sánh mô hình theo năng lực dự báo ngoài mẫu.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-thực-hiện-một-phép-kiểm-tra-ppc-đúng-kỹ-thuật-trong-4-bước&quot;&gt;Giải thích: Thực hiện một phép kiểm tra PPC đúng kỹ thuật trong 4 bước&lt;/h2&gt;

&lt;p&gt;Để tránh làm PPC mang tính hình thức, hãy đi chậm qua 4 bước sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Rút \(S\) mẫu tham số từ hậu nghiệm&lt;/strong&gt; \(\theta^{(1)}, \dots, \theta^{(S)}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Với mỗi \(\theta^{(s)}\), mô phỏng một bộ dữ liệu mới cùng cỡ mẫu&lt;/strong&gt; \(y^{\text{rep}(s)}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính thống kê chẩn đoán \(T(y^{\text{rep}(s)})\)&lt;/strong&gt; trên từng bộ mô phỏng (ví dụ: phương sai, giá trị lớn nhất, hay số lượng giá trị 0) và so với giá trị thật \(T(y_{\text{obs}})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính \(p_B\) và đọc hướng cải tiến mô hình:&lt;/strong&gt; Nếu \(p_B &amp;lt; 0.02\) hoặc \(p_B &amp;gt; 0.98\), chính thống kê \(T\) bị lệch sẽ chỉ thẳng chỗ cần nâng cấp mô hình.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-chẩn-đoán-quá-phân-tán-của-mô-hình-poisson-bằng-ppc&quot;&gt;Ví dụ tính toán làm từng bước: Chẩn đoán quá phân tán của mô hình Poisson bằng PPC&lt;/h3&gt;

&lt;p&gt;Giả sử ta khớp mô hình Poisson vào dữ liệu đếm có trung bình quan sát \(\bar y = 4.0\) nhưng phương sai quan sát là \(T(y_{\text{obs}}) = s_{\text{obs}}^2 = 12.5\). Ta rút \(S = 10\) tập dữ liệu giả lập \(y^{\text{rep}(s)}\) từ hậu nghiệm Poisson và tính phương sai \(T(y^{\text{rep}(s)})\) của từng tập:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Tập mô phỏng \(s\)&lt;/th&gt;
      &lt;th&gt;1&lt;/th&gt;
      &lt;th&gt;2&lt;/th&gt;
      &lt;th&gt;3&lt;/th&gt;
      &lt;th&gt;4&lt;/th&gt;
      &lt;th&gt;5&lt;/th&gt;
      &lt;th&gt;6&lt;/th&gt;
      &lt;th&gt;7&lt;/th&gt;
      &lt;th&gt;8&lt;/th&gt;
      &lt;th&gt;9&lt;/th&gt;
      &lt;th&gt;10&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Phương sai \(T(y^{\text{rep}(s)})\)&lt;/td&gt;
      &lt;td&gt;\(3.6\)&lt;/td&gt;
      &lt;td&gt;\(4.8\)&lt;/td&gt;
      &lt;td&gt;\(3.9\)&lt;/td&gt;
      &lt;td&gt;\(5.1\)&lt;/td&gt;
      &lt;td&gt;\(4.2\)&lt;/td&gt;
      &lt;td&gt;\(3.3\)&lt;/td&gt;
      &lt;td&gt;\(4.5\)&lt;/td&gt;
      &lt;td&gt;\(5.4\)&lt;/td&gt;
      &lt;td&gt;\(3.8\)&lt;/td&gt;
      &lt;td&gt;\(4.4\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(T(y^{\text{rep}(s)}) \ge 12.5\)?&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Kết quả: \(0/10\) tập mô phỏng đạt nổi phương sai \(12.5\), nên trị số \(p\) Bayes là \(p_B = 0 / 10 = 0.00\)! Trong khi đó, nếu kiểm tra trung bình \(\bar y\), \(p_B\) lại đẹp quanh \(0.50\). Phép PPC trên phương sai lập tức chứng minh mô hình Poisson thiếu cơ chế cho độ phân tán và chỉ thẳng hướng nâng cấp sang Negative Binomial.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Diễn giải \(p_B = 0.45\) là “xác suất mô hình đúng bằng 45%”. Trị số \(p_B\) chỉ đo mức độ cực đoan của dữ liệu thật so với dự báo của mô hình theo &lt;em&gt;riêng thống kê \(T\) đó&lt;/em&gt; — một mô hình sai vẫn có thể có \(p_B \approx 0.50\) nếu ta chọn thống kê \(T\) quá dễ tính.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu sau khi chuyển sang Negative Binomial, có \(420\) trong \(1000\) tập mô phỏng cho phương sai \(\ge 12.5\), thì \(p_B = 420 / 1000 = 0.42\) — cho thấy mô hình mới đã tái tạo tốt độ phân tán của dữ liệu thật.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yDPJnV9vcHs&quot;&gt;What is a posterior predictive check and why is it useful?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giới thiệu kiểm tra dự báo hậu nghiệm như bước phê bình mô hình, tách bạch giữa hội tụ MCMC và độ phù hợp của câu chuyện sinh dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R9NQY2Hyl14&quot;&gt;26 - Prior and posterior predictive distributions - an introduction&lt;/a&gt; — Ox educ, English. Phân biệt phân phối dự báo tiên nghiệm và hậu nghiệm, hỗ trợ phần tái tạo đặc điểm dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=IhTfuO8wSDA&quot;&gt;Posterior Predictive Sampling in PyMC by (Luciano Paz)&lt;/a&gt; — PyMC Developers, English. Hướng dẫn lấy mẫu dự báo hậu nghiệm trong PyMC để chuyển từ lý thuyết sang thực hành.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao một mô hình tái tạo tốt giá trị trung bình nhưng sai lệch rõ ở phân vị \(Q_{0.95}\) vẫn có thể gây rủi ro trong bài toán vận hành?&lt;/li&gt;
  &lt;li&gt;Khi trị số p Bayes của thống kê phương sai rất gần 1, bạn nghi ngờ dạng sai lệch nào trước tiên?&lt;/li&gt;
  &lt;li&gt;Trong bài toán có rủi ro đuôi cao, bạn sẽ ưu tiên bổ sung thống kê nào vào bộ PPC và vì sao?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition), Chapter 6.&lt;/li&gt;
  &lt;li&gt;Gabry, J., et al. (2019). “Visualization in Bayesian workflow.” &lt;em&gt;JRSS A&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter08/08_02_information_criteria/&quot;&gt;8.2 Information Criteria (WAIC, LOO)&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 8.3: Model Comparison Strategies</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter08/08_03_model_comparison/"/>
   <updated>2025-01-04T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter08/08_03_model_comparison</id>
   <content type="html">&lt;p&gt;You run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;az.compare({&quot;M1&quot;: idata1, &quot;M2&quot;: idata2})&lt;/code&gt; and see &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;M2&lt;/code&gt; beat &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;M1&lt;/code&gt; by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elpd_diff = 1.8&lt;/code&gt;. Should you throw &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;M1&lt;/code&gt; in the trash and declare &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;M2&lt;/code&gt; the winner? Look one column to the right: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dse = 2.9&lt;/code&gt;! The difference is &lt;em&gt;smaller than its own standard error&lt;/em&gt;—picking one “winner” here is pure coin-flipping!&lt;/p&gt;

&lt;p&gt;This lesson teaches mature &lt;strong&gt;Bayesian Model Comparison&lt;/strong&gt;: reading &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elpd_diff&lt;/code&gt; alongside its paired standard error &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dse&lt;/code&gt;, understanding &lt;strong&gt;Bayes Factors&lt;/strong&gt; (and why they depend strongly on prior width!), and combining competing models cleanly via &lt;strong&gt;Bayesian Stacking / Model Averaging&lt;/strong&gt; instead of forcing a brittle winner-take-all choice.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-three-complementary-lenses-for-model-comparison&quot;&gt;Key ideas: Three Complementary Lenses for Model Comparison&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Predictive Comparison (LOO-CV &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elpd_diff&lt;/code&gt; vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dse&lt;/code&gt;):&lt;/strong&gt; Compares &lt;em&gt;pointwise&lt;/em&gt; predictive differences \(d_i = \mathrm{elpd}_{i, M_2} - \mathrm{elpd}_{i, M_1}\). Because both models are evaluated on the exact same observations, pairing cancels out shared noise—giving a clean paired SE (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dse&lt;/code&gt;). Rule of thumb: \(\lvert\Delta\mathrm{elpd}\rvert &amp;gt; 2\text{–}4 \times \mathrm{dse}\) signals a clear predictive win!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Marginal Likelihood &amp;amp; Bayes Factors (\(\mathrm{BF}_{12} = \frac{p(y\mid M_1)}{p(y\mid M_2)}\)):&lt;/strong&gt; Measures relative evidence under prior predictive distributions. Powerful for nested scientific hypotheses, yet &lt;strong&gt;highly sensitive to prior width&lt;/strong&gt; (making a prior 10× wider penalizes that model’s Bayes Factor by 10×!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Model Averaging &amp;amp; Stacking (Yao et al.):&lt;/strong&gt; When two models are neck-and-neck (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elpd_diff &amp;lt; 2 * dse&lt;/code&gt;), don’t discard one! &lt;strong&gt;Stacking&lt;/strong&gt; finds optimal non-negative weights \(w_1 + w_2 = 1\) maximizing combined LOO predictive density—preserving model uncertainty in predictions!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Causal Goal ≠ Predictive Goal:&lt;/strong&gt; Use DAGs to choose causal models; use LOO/Stacking to optimize predictive accuracy.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you should clearly distinguish three model comparison strategies in Bayesian statistics: choosing one model (selection), combining several models (averaging), and expanding the model to encompass the others (expansion). The central point is not to treat model comparison as a mechanical ranking procedure, but as a decision problem under model uncertainty, where the choice of strategy depends on how well separated the predictive performance is and on the application goal.&lt;/p&gt;

&lt;h2 id=&quot;1-comparing-models-is-not-always-about-picking-a-winner&quot;&gt;1. Comparing models is not always about picking a winner&lt;/h2&gt;

&lt;p&gt;When several competing models have very similar predictive ability, being forced to choose exactly one model easily creates a false sense of certainty. Conversely, when one model is clearly superior and stable across checks, keeping several models only adds complexity without adding predictive value. So the right question is not “which model ranks first”, but “which strategy produces the most useful forecasts with the most honest uncertainty”.&lt;/p&gt;

&lt;h2 id=&quot;2-strategy-a---model-selection&quot;&gt;2. Strategy A - Model selection&lt;/h2&gt;

&lt;p&gt;Model selection is appropriate when the out-of-sample predictive gap between the best model and the rest is large relative to the estimation uncertainty. In that case, the cognitive cost of maintaining several models usually outweighs the benefit, and a single model allows simpler interpretation, communication, and deployment.&lt;/p&gt;

&lt;p&gt;However, the hidden condition of selection is sufficiently strong separation. If the difference in predictive metrics is small and unstable, selection can make the whole pipeline depend on random sampling fluctuation rather than on real structural signal.&lt;/p&gt;

&lt;h3 id=&quot;experiment-the-bayes-factor-is-a-ratio-of-marginal-likelihoods&quot;&gt;Experiment: the Bayes factor is a ratio of marginal likelihoods&lt;/h3&gt;

&lt;p&gt;Flip one at a time and watch the cumulative BF₁₀ = m₁(k)/m₀(k); the marginal likelihood penalizes a model that spreads its probability thinly (the Occam effect).&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;bf-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;seq&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-strategy-b---model-averaging&quot;&gt;3. Strategy B - Model averaging&lt;/h2&gt;

&lt;p&gt;Model averaging follows the principle of “preserving model uncertainty” by combining predictive distributions:&lt;/p&gt;

\[p(\tilde y\mid y)=\sum_{k=1}^{K} w_k\,p_k(\tilde y\mid y),\qquad \sum_k w_k=1,\; w_k\ge 0.\]

&lt;p&gt;In modern practice, stacking weights are usually preferred because they directly optimize the predictive ability of the combined distribution, instead of trying to assign an absolute “right/wrong” probability to each model.&lt;/p&gt;

&lt;h3 id=&quot;experiment-model-averaging-with-pseudo-bma-weights&quot;&gt;Experiment: model averaging with pseudo-BMA weights&lt;/h3&gt;

&lt;p&gt;Add models to the group one at a time and watch the weights w ∝ exp(elpd_loo) and the averaged prediction change.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;ic-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;avg&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;31-a-short-quantitative-example&quot;&gt;3.1. A short quantitative example&lt;/h3&gt;

&lt;p&gt;Suppose that at a new prediction point, model A gives a mean of 52, model B gives 56, and the stacking weights are 0.58 and 0.42 respectively. The mean prediction of the combined model is then&lt;/p&gt;

\[0.58\times 52 + 0.42\times 56 = 53.68.\]

&lt;p&gt;This value reflects both the signals of the two models and the structural uncertainty that exists between them, instead of forcing a choice of 52 or 56 as two mutually exclusive scenarios.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/chapter08_selection_vs_stacking.png&quot; alt=&quot;Selection vs Stacking predictive distributions&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;experiment-the-bf-depends-on-the-prior-width&quot;&gt;Experiment: the BF depends on the prior width&lt;/h3&gt;

&lt;p&gt;Change the Beta(c, c) prior of M₁ and watch BF₁₀ change — the reason a sensitivity analysis is needed.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;bf-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;prior&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;4-strategy-c---model-expansion&quot;&gt;4. Strategy C - Model expansion&lt;/h2&gt;

&lt;p&gt;Model expansion is appropriate when the candidate models represent different pieces of the same data-generating mechanism and can be merged into one larger model, for example by adding a nonlinear component, hierarchical group effects, or regularized interactions. The advantage of expansion is a single consistent inference framework instead of maintaining several disconnected models; the risk is higher computational complexity and the need for stronger checks to avoid overfitting.&lt;/p&gt;

&lt;p&gt;A useful way to read it: selection resolves competition between models; averaging resolves uncertainty between models; expansion resolves the structural deficiency of the existing set of models.&lt;/p&gt;

&lt;h2 id=&quot;5-rules-for-choosing-a-strategy-in-practice&quot;&gt;5. Rules for choosing a strategy in practice&lt;/h2&gt;

&lt;p&gt;A working rule can be stated as follows. If the difference in predictive performance is large and stable, prefer selection. If several models are nearly tied, prefer averaging to preserve uncertainty. If all models reveal mechanism misfit in PPC, prefer expansion instead of continuing to argue about who is “least wrong”.&lt;/p&gt;

&lt;p&gt;The important point is that this rule must always go together with diagnostic checks (for example Pareto \(k\) in LOO) and the results of model criticism. A nice rank table cannot replace evidence that the model still misses important data structure.&lt;/p&gt;

&lt;h2 id=&quot;6-a-combined-example-same-data-three-different-decisions&quot;&gt;6. A combined example: same data, three different decisions&lt;/h2&gt;

&lt;p&gt;Suppose we have three models M1, M2, M3, and the LOO results show that M1 and M2 are close within the standard error, while M3 is clearly worse. When the goal is stable short-term forecasting, averaging between M1 and M2 is usually more sensible than selection. If the goal is to explain the mechanism and M1 is considerably simpler, selection may still be chosen provided the remaining model uncertainty is clearly reported. Conversely, if PPC shows that both M1 and M2 are wrong in the tail, the best decision is neither to choose nor to mix, but to expand in order to fix the data-generating mechanism properly.&lt;/p&gt;

&lt;p&gt;This example shows that model comparison is a multi-objective decision: prediction, interpretation, deployment cost, and honesty about uncertainty.&lt;/p&gt;

&lt;h2 id=&quot;7-conclusion-of-lesson-83&quot;&gt;7. Conclusion of Lesson 8.3&lt;/h2&gt;

&lt;p&gt;There is no single correct model comparison strategy for every context. Selection, averaging, and expansion are three complementary tools in the same Bayesian workflow. An analyst’s ability lies not in remembering the names of the tools, but in knowing when to reduce uncertainty by choosing a model, when to keep uncertainty by combining models, and when to redesign the model to fix mechanism misfit.&lt;/p&gt;

&lt;p&gt;Next lesson: &lt;strong&gt;Bayesian Decision Analysis&lt;/strong&gt;, where model results are turned into the optimal choice of action under a concrete loss.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-reading-two-real-azcompare-tables-side-by-side&quot;&gt;Worked Numerical Example: Reading Two Real &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;az.compare&lt;/code&gt; Tables Side by Side&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Scenario 1 — Clear Winner:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Model A (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Simple Linear&lt;/code&gt;): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elpd_loo = -142.0&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Model B (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Hierarchical Spline&lt;/code&gt;): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elpd_loo = -129.6&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Difference: \(\Delta\mathrm{elpd} = \mathbf{+12.4}\), paired \(\mathrm{dse} = \mathbf{3.1}\) \(\implies z = 12.4 / 3.1 = \mathbf{4.0}\) (decisive predictive superiority for Model B!).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Scenario 2 — Too Close to Call (Use Stacking!):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Model C (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Poisson&lt;/code&gt;): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elpd_loo = -210.4&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Model D (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NegBin&lt;/code&gt;): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elpd_loo = -208.6&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Difference: \(\Delta\mathrm{elpd} = \mathbf{+1.8}\), paired \(\mathrm{dse} = \mathbf{2.9}\) \(\implies z = 1.8 / 2.9 = \mathbf{0.62}\)!&lt;/li&gt;
  &lt;li&gt;Rather than betting 100% on one model, &lt;strong&gt;Stacking&lt;/strong&gt; might assign weights \(w_D = 0.65,\; w_C = 0.35\), combining their posterior predictive draws cleanly!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-rules-for-wise-bayesian-model-comparison&quot;&gt;Explanation: Four Rules for Wise Bayesian Model Comparison&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dse&lt;/code&gt; (difference SE), never the individual models’ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;se&lt;/code&gt;:&lt;/strong&gt; Individual &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;se&lt;/code&gt; includes observation-to-observation difficulty; paired &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dse&lt;/code&gt; measures the true uncertainty in &lt;em&gt;Model B minus Model A&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never use flat/uninformative priors when computing Bayes Factors:&lt;/strong&gt; Under improper or arbitrarily wide priors, Bayes Factors automatically favor the simpler model (Lindley’s Paradox) regardless of the data!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;When models tie on LOO, prefer the simpler, better-regularized, or causally grounded model—or stack them.&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always run PPCs on the winning model too:&lt;/strong&gt; Being the “best” of three bad models still leaves you with a bad model!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If Model 2 beats Model 1 by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elpd_diff = 3.0&lt;/code&gt; with a paired &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dse = 4.5&lt;/code&gt;, do you have strong evidence that Model 2 predicts better out of sample—and what should you do instead of discarding Model 1?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qwF-st2NGTU&quot;&gt;Statistical Rethinking 2023 - 20 - Horoscopes&lt;/a&gt; — Richard McElreath, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch why a model ranking table is not a prophecy, exactly the argument by which the lesson refuses to pick a winner at all costs.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=707hT6qYghw&quot;&gt;16a Prediction and Model Averaging&lt;/a&gt; — Philip Ramsey, English. Watch model averaging when the models all make predictions, supporting the strategy of combining instead of choosing one model.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Nv2rm1s9q6I&quot;&gt;Statistical Rethinking 2026 - Lecture B02 - Multilevel Model Expansion&lt;/a&gt; — Richard McElreath, English. Watch multilevel model expansion, used for the expansion strategy that the lesson places next to selection and averaging.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;When two models differ in LOO by very little relative to the SE, why can selection be less honest than averaging?&lt;/li&gt;
  &lt;li&gt;When is expansion better than both selection and averaging?&lt;/li&gt;
  &lt;li&gt;If the main goal is causal interpretation, how would you change your strategy priorities compared with a purely predictive goal?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Yao, Y., et al. (2018). “Using stacking to average Bayesian predictive distributions.” &lt;em&gt;Bayesian Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter08/08_04_decision_analysis/&quot;&gt;8.4 Bayesian Decision Analysis&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 8.2: Information Criteria - WAIC and LOO</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter08/08_02_information_criteria/"/>
   <updated>2025-01-04T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter08/08_02_information_criteria</id>
   <content type="html">&lt;p&gt;How do you compare two competing Bayesian models—say a simple linear model vs. a complex hierarchical spline—on out-of-sample predictive accuracy &lt;em&gt;without&lt;/em&gt; having to refit your expensive MCMC sampler 1,000 times for Leave-One-Out Cross-Validation? Enter &lt;strong&gt;WAIC (Watanabe–Akaike Information Criterion)&lt;/strong&gt; and &lt;strong&gt;PSIS-LOO (Pareto-Smoothed Importance Sampling Leave-One-Out)&lt;/strong&gt;—two breakthroughs that estimate true out-of-sample &lt;strong&gt;Expected Log Pointwise Predictive Density (ELPD)&lt;/strong&gt; directly from &lt;em&gt;one single&lt;/em&gt; MCMC run!&lt;/p&gt;

&lt;p&gt;This lesson builds crystal-clear intuition for &lt;strong&gt;lppd&lt;/strong&gt;, the &lt;strong&gt;effective number of parameters (\(p_{\text{WAIC}}\))&lt;/strong&gt;, and the &lt;strong&gt;Pareto-\(k\) diagnostic&lt;/strong&gt; that warns you when a single influential outlier needs exact refitting.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-estimating-out-of-sample-predictive-accuracy-from-one-mcmc-run&quot;&gt;Key ideas: Estimating Out-of-Sample Predictive Accuracy From One MCMC Run&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Log Pointwise Predictive Density (\(\mathrm{lppd}\)):&lt;/strong&gt; Averages likelihood across posterior draws &lt;em&gt;first&lt;/em&gt;, then takes the log: \(\mathrm{lppd} = \sum_{i=1}^n \ln\!\left(\frac{1}{S}\sum_{s=1}^S p(y_i \mid \theta^{(s)})\right)\). Measures in-sample predictive fit using the &lt;em&gt;entire&lt;/em&gt; posterior!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Effective Number of Parameters (\(p_{\text{WAIC}}\)):&lt;/strong&gt; Penalizes overfitting by summing the posterior &lt;em&gt;variance&lt;/em&gt; of log-likelihood at every data point: \(p_{\text{WAIC}} = \sum_{i=1}^n \mathrm{Var}_s\!\bigl(\ln p(y_i \mid \theta^{(s)})\bigr)\). Notice that hierarchical shrinkage can make \(p_{\text{WAIC}}\) &lt;em&gt;far smaller&lt;/em&gt; than the raw parameter count!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;WAIC &amp;amp; ELPD:&lt;/strong&gt; \(\widehat{\mathrm{elpd}}_{\text{WAIC}} = \mathrm{lppd} - p_{\text{WAIC}}\) (higher is better!), or on the deviance scale \(\mathrm{WAIC} = -2\,\widehat{\mathrm{elpd}}_{\text{WAIC}}\) (lower is better!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;PSIS-LOO &amp;amp; Pareto-\(k\) Diagnostic (Vehtari et al.):&lt;/strong&gt; Uses importance sampling to approximate exact Leave-One-Out CV—and automatically flags high-leverage observations where &lt;strong&gt;Pareto-\(k &amp;gt; 0.7\)&lt;/strong&gt; (a built-in reliability alarm that WAIC lacks!).&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you should understand WAIC and LOO as tools for approximating the out-of-sample predictive ability of Bayesian models, and know how to read results in terms of estimation uncertainty rather than with a “hard ranking” mindset. The focus of the lesson is methodological reasoning: why out-of-sample predictive criteria should be preferred, when the difference between models is large enough to conclude, and when to move from model selection to model averaging.&lt;/p&gt;

&lt;h2 id=&quot;1-from-training-fit-to-out-of-sample-prediction&quot;&gt;1. From training fit to out-of-sample prediction&lt;/h2&gt;

&lt;p&gt;The classic problem of model comparison is that the more flexible a model is, the more easily it achieves a good training fit, yet that same flexibility can reduce predictive ability on new data. Therefore, the quantity of interest is not the in-sample error but the out-of-sample log predictive density. In pointwise language, we care about the sum&lt;/p&gt;

\[\text{elpd} = \sum_{i=1}^n \log p(y_i\mid y_{-i}),\]

&lt;p&gt;where each observation is evaluated as a never-before-seen point, with the model having learned from the remaining data.&lt;/p&gt;

&lt;p&gt;This idea is very powerful conceptually but computationally expensive if the model must be refit many times; WAIC and PSIS-LOO appear as two practical routes to approximate the same target.&lt;/p&gt;

&lt;h2 id=&quot;2-waic-a-fully-bayesian-approximation-of-predictive-accuracy&quot;&gt;2. WAIC: a fully Bayesian approximation of predictive accuracy&lt;/h2&gt;

&lt;p&gt;WAIC can be written as&lt;/p&gt;

\[\text{WAIC}=-2\,(\text{lppd}-p_{\text{WAIC}}),\]

&lt;p&gt;where lppd reflects pointwise predictive fit, and \(p_{\text{WAIC}}\) plays the role of effective complexity that penalizes overfitting. When comparing several models on the same data, a lower WAIC corresponds to better predictive performance (or, equivalently, a larger elpd).&lt;/p&gt;

&lt;p&gt;It must be emphasized that WAIC is not an “absolute score” of a model; it only has meaning relative to competing models and must be accompanied by the standard error of the difference.&lt;/p&gt;

&lt;h2 id=&quot;3-psis-loo-closer-to-the-reference-standard-in-practice&quot;&gt;3. PSIS-LOO: closer to the reference standard in practice&lt;/h2&gt;

&lt;p&gt;Ideal LOO-CV requires leaving out each observation and refitting the model, while PSIS-LOO uses Pareto-smoothed importance sampling to approximate that procedure without refitting the whole model. Because it is closer to the direct out-of-sample definition, LOO is usually preferred in modern workflows, provided the Pareto \(k\) diagnostic shows that the approximation is reliable enough.&lt;/p&gt;

&lt;p&gt;A short reading that still captures the essence: WAIC is usually fast and convenient; PSIS-LOO is usually more trustworthy; both must be interpreted together with estimation uncertainty.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/chapter08_waic_loo_comparison.png&quot; alt=&quot;WAIC and LOO comparison with uncertainty&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;experiment-waic-and-loo-estimate-out-of-sample-predictive-quality&quot;&gt;Experiment: WAIC and LOO estimate out-of-sample predictive quality&lt;/h3&gt;

&lt;p&gt;Increase the polynomial degree step by step: the in-sample lppd always rises, while the elpd by WAIC and LOO (which tracks the elpd on new data closely) peaks and then falls. The table gives p_waic, Δelpd and the standard error.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;ic-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;waic&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-reading-the-model-comparison-table-differences-and-uncertainty&quot;&gt;4. Reading the model comparison table: differences and uncertainty&lt;/h2&gt;

&lt;p&gt;Suppose three models give the following results on the elpd scale (higher is better):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Model A: elpd = -221, SE = 5&lt;/li&gt;
  &lt;li&gt;Model B: elpd = -220, SE = 5.5&lt;/li&gt;
  &lt;li&gt;Model C: elpd = -229, SE = 6&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The reasonable conclusion is that C is clearly worse than A and B, but A and B are almost tied because a difference of 1 point is considerably smaller than the accompanying uncertainty. In this situation, declaring “B wins” is an over-reading; the more mature choice is to treat A and B as a set of nearly equally competitive models, then consider averaging or prefer the more interpretable model if communication goals matter.&lt;/p&gt;

&lt;h2 id=&quot;5-pareto-k-the-reliability-condition-of-psis-loo&quot;&gt;5. Pareto k: the reliability condition of PSIS-LOO&lt;/h2&gt;

&lt;p&gt;For PSIS-LOO, the Pareto \(k\) index answers the question: are the importance sampling weights stable? A commonly used practical threshold is:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(k&amp;lt;0.5\): very stable,&lt;/li&gt;
  &lt;li&gt;\(0.5\le k\le 0.7\): usable but needs care,&lt;/li&gt;
  &lt;li&gt;\(k&amp;gt;0.7\): the approximation may be unreliable; check carefully and consider alternative measures.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The important point is that Pareto \(k\) is not a minor detail. If the diagnostic fails, the LOO ranking table may look nice but no longer has a solid enough foundation for decisions.&lt;/p&gt;

&lt;h2 id=&quot;6-a-methodological-example-when-is-there-enough-evidence-to-choose-a-model&quot;&gt;6. A methodological example: when is there “enough evidence” to choose a model&lt;/h2&gt;

&lt;p&gt;Suppose the best model has an elpd 6 points higher than the second-best model, while the standard error of the difference is about 2. Then we can regard the gap as convincing enough to choose the best model for the predictive goal. Conversely, if the difference is only 1.5 with a standard error of 2.2, the scientific conclusion should be “not clearly distinguishable yet”, and the more sensible strategy is usually averaging or keeping several models for different goals.&lt;/p&gt;

&lt;p&gt;In other words, model comparison in Bayesian statistics is an inference problem under uncertainty, not a scoring contest with a single number.&lt;/p&gt;

&lt;h2 id=&quot;7-good-practice-when-using-waicloo&quot;&gt;7. Good practice when using WAIC/LOO&lt;/h2&gt;

&lt;p&gt;Good practice can be summarized in three principles. First, always compare on the same data and the same target variable so that the difference has meaning. Second, read the estimate and the SE together instead of looking only at the rank. Third, if several models are close, move from “winner-takes-all” logic to combining predictions.&lt;/p&gt;

&lt;p&gt;From the workflow perspective, WAIC/LOO does not replace PPC: a model with a better predictive score can still be wrong in mechanism in regions the problem cares about especially, so model criticism and model comparison must be used as complements, not substitutes.&lt;/p&gt;

&lt;h2 id=&quot;8-conclusion-of-lesson-82&quot;&gt;8. Conclusion of Lesson 8.2&lt;/h2&gt;

&lt;p&gt;WAIC and LOO provide a quantitative language for comparing models by out-of-sample predictive ability, but their greatest value lies in disciplined interpretation: always read differences together with uncertainty, always check the diagnostics of the approximation, and always tie the model-choice decision to a concrete predictive goal rather than to the habit of choosing the top rank.&lt;/p&gt;

&lt;p&gt;Next lesson: &lt;strong&gt;Model Comparison Strategies&lt;/strong&gt;, where we go deeper into the choice between selection, averaging, and expansion.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-hand-computing-mathrmlppd-p_textwaic-and-waic-on-2-data-points&quot;&gt;Worked Numerical Example: Hand-Computing \(\mathrm{lppd}\), \(p_{\text{WAIC}}\), and WAIC on 2 Data Points&lt;/h3&gt;

&lt;p&gt;Suppose we have \(n = 2\) observations and \(S = 2\) posterior draws \(\theta^{(1)}, \theta^{(2)}\) with pointwise likelihoods \(p(y_i\mid\theta^{(s)})\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Observation \(i\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(p(y_i\mid\theta^{(1)})\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(p(y_i\mid\theta^{(2)})\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Mean Lik \(\bar{p}_i\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(\ln \bar{p}_i\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(\ln p^{(1)}, \ln p^{(2)}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Sample Var \(v_i\) (\(ddof=1\))&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(i = 1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.50\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.50\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.50\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-0.693\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-0.693,\; -0.693\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.000\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(i = 2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.80\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.20\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.50\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-0.693\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-0.223,\; -1.609\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.961\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Sum across both data points:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;\(\mathrm{lppd} = -0.693 + (-0.693) = \mathbf{-1.386}\).&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Effective parameters \(p_{\text{WAIC}} = 0.000 + 0.961 = \mathbf{0.961}\).&lt;/strong&gt; &lt;em&gt;(Notice observation 2 varies wildly across draws, contributing the entire overfitting penalty!)&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;\(\widehat{\mathrm{elpd}}_{\text{WAIC}} = -1.386 - 0.961 = \mathbf{-2.347}\)&lt;/strong&gt; \(\implies \mathrm{WAIC} = -2(-2.347) = \mathbf{4.694}\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-using-waic--psis-loo-correctly&quot;&gt;Explanation: Four Rules for Using WAIC &amp;amp; PSIS-LOO Correctly&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Prefer &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;az.loo&lt;/code&gt; (PSIS-LOO) over WAIC as your default:&lt;/strong&gt; Both target exact LOO-CV, yet PSIS-LOO gives you the &lt;strong&gt;Pareto-\(k\)&lt;/strong&gt; diagnostic warning whenever an observation has extreme leverage (\(k &amp;gt; 0.7\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Only compare models fitted to the &lt;em&gt;exact same&lt;/em&gt; observed outcome vector \(y\):&lt;/strong&gt; You cannot compare WAIC/LOO between a model on \(y\) and a model on \(\log(y)\) without adding the Jacobian correction, nor between datasets with different dropped missing rows!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never confuse predictive ELPD with causal truth:&lt;/strong&gt; A confounded model (or one conditioning on a collider!) can easily achieve &lt;em&gt;better&lt;/em&gt; LOO-CV ELPD than the true causal model!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always inspect &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dse&lt;/code&gt; (the standard error of the difference):&lt;/strong&gt; Raw &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elpd_diff&lt;/code&gt; without &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dse&lt;/code&gt; is meaningless.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the 2-observation table above, why did observation \(i = 1\) contribute &lt;strong&gt;\(0.000\)&lt;/strong&gt; to the complexity penalty \(p_{\text{WAIC}}\), whereas observation \(i = 2\) contributed \(0.961\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=xS4jDHQfP2o&quot;&gt;Evaluating model fit through AIC, DIC, WAIC and LOO-CV&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch AIC, DIC, WAIC and LOO-CV placed side by side as ways of estimating out-of-sample predictive ability.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=D0kVMie93Yk&quot;&gt;BDA 2019 Lecture 9.1 PSIS-LOO and K-fold cross-validation&lt;/a&gt; — Aki Vehtari, English. Watch Aki Vehtari present PSIS-LOO and K-fold, supporting the part where the lesson prefers LOO over in-sample fit.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=h4g5KUWRzyg&quot;&gt;31- Pareto k diagnostics in R&lt;/a&gt; — Horizon 2 Reach, English. Watch the Pareto k diagnostic, exactly the condition the lesson requires before trusting a PSIS-LOO estimate.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why is a WAIC/LOO difference smaller than the standard error of the difference not enough to declare a model the winner?&lt;/li&gt;
  &lt;li&gt;If a model ranks first but has many points with Pareto \(k&amp;gt;0.7\), how would you handle that result?&lt;/li&gt;
  &lt;li&gt;When do you prefer model averaging over choosing a single model?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Vehtari, A., Gelman, A., &amp;amp; Gabry, J. (2017). “Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC.” &lt;em&gt;Statistics and Computing&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition), Chapter 7.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter08/08_03_model_comparison/&quot;&gt;8.3 Model Comparison Strategies&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 8.1: Posterior Predictive Checks - Model Criticism</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter08/08_01_ppc/"/>
   <updated>2025-01-04T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter08/08_01_ppc</id>
   <content type="html">&lt;p&gt;Fitting a Bayesian model and getting a smooth, converged MCMC posterior proves only one thing: &lt;em&gt;your sampler solved the math of the model you wrote.&lt;/em&gt; It does &lt;strong&gt;NOT&lt;/strong&gt; prove that your model actually resembles reality! If you fit a Normal distribution to bimodal data, or a Poisson distribution to zero-inflated counts, MCMC will happily converge with \(\hat{R} = 1.00\) while generating fake worlds that look nothing like your real dataset!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Posterior Predictive Checks (PPC)&lt;/strong&gt; are the Bayesian scientist’s reality check: &lt;em&gt;“If my fitted model were truly the machine that generated the world, would simulated datasets \(y^{\text{rep}}\) look like the real dataset \(y\) I actually observed?”&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-how-posterior-predictive-checks-expose-model-misfit&quot;&gt;Key ideas: How Posterior Predictive Checks Expose Model Misfit&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;The Posterior Predictive Distribution:&lt;/strong&gt; Draw parameter vectors \(\theta^{(s)} \sim p(\theta\mid y)\), then simulate a full synthetic dataset \(y^{\text{rep},(s)} \sim p(\tilde{y} \mid \theta^{(s)})\)—propagating &lt;em&gt;both&lt;/em&gt; parameter uncertainty and sampling noise!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Visual Density Overlay (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;az.plot_ppc&lt;/code&gt;):&lt;/strong&gt; Overlay 50–100 replicated density curves on top of the observed data curve—immediately exposing skewness, multimodality, boundary violations, or heavy tails!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Test Quantities \(T(y)\) &amp;amp; Bayesian p-values (\(p_B\)):&lt;/strong&gt; Choose targeted diagnostics &lt;em&gt;not&lt;/em&gt; trivially fixed by the model’s mean—such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max(y)&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;min(y)&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var(y)/mean(y)&lt;/code&gt;, or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fraction_of_zeros(y)&lt;/code&gt;—and compute \(p_B = P\bigl(T(y^{\text{rep}}) \ge T(y) \mid y\bigr)\). Values near &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.5&lt;/code&gt; look great; values near &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.00&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.00&lt;/code&gt; flag a serious model failure!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Iterative Model Expansion (Box’s Loop):&lt;/strong&gt; PPC doesn’t just say “reject”—it tells you &lt;em&gt;exactly what&lt;/em&gt; is missing (e.g., too many zeros \(\to\) Zero-Inflated Poisson; heavy tails \(\to\) Student-\(t\))!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you should understand Posterior Predictive Checks (PPC) as the central axis of model criticism in the Bayesian workflow: we do not judge a model by how well it explains the old data, but by whether it can reproduce the important features of the observed data. You should also know how to turn a suspicion about a model (for example: tails that are too thin, changing variance, a nonlinear relationship) into a corresponding quantitative check, so that conclusions do not rest on visual impression alone.&lt;/p&gt;

&lt;h2 id=&quot;1-why-a-nice-posterior-is-not-enough&quot;&gt;1. Why a nice posterior is not enough&lt;/h2&gt;

&lt;p&gt;In practice, a stable posterior only tells you that the sampler is exploring the posterior distribution of the parameters sensibly under the assumed model; it does not prove that the model is a good description of the data-generating mechanism. In short, MCMC convergence is a computational condition, while model quality is a data-science condition. PPC exists to connect these two layers of conditions.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“All models are wrong, but some are useful.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Box’s sentence can be read in PPC language: a useful model is one that can generate data that looks like the real data on exactly those aspects that matter for the decision question.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation-of-ppc&quot;&gt;2. Mathematical foundation of PPC&lt;/h2&gt;

&lt;p&gt;The posterior predictive distribution is defined by&lt;/p&gt;

\[p(\tilde y\mid y)=\int p(\tilde y\mid\theta)\,p(\theta\mid y)\,d\theta.\]

&lt;p&gt;Here, \(p(\theta\mid y)\) encodes parameter uncertainty after observing the data, while \(p(\tilde y\mid\theta)\) encodes how new data would be generated if the parameter equaled \(\theta\). PPC is essentially a comparison of the observed data \(y\) with a large set of replicates \(\tilde y^{(s)}\) drawn from this distribution. Intuitively, if the model is a reasonable data-generating story, the real data should not become an “outlier” under that very story.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_process_workflow.png&quot; alt=&quot;PPC Process Workflow&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-a-structured-checking-logic&quot;&gt;3. A structured checking logic&lt;/h2&gt;

&lt;p&gt;A good PPC is not about drawing many plots, but about asking the right checking questions in the right order. Start from the overall shape of the distribution, then check central features and dispersion, then go deeper into the tails, and only then move on to conditional checks by predictor or by group. This sequence helps avoid wrong conclusions of the “the model is fine” kind just because the mean is reproduced well while the tails and residuals show systematic deviation.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_workflow_diagram.png&quot; alt=&quot;PPC Workflow&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;31-checking-the-overall-distribution&quot;&gt;3.1. Checking the overall distribution&lt;/h3&gt;

&lt;p&gt;Comparing the density/ECDF of the observed data with the posterior predictive is the first screening step for detecting large deviations in location, width, and asymmetry. If the model fails at this step, finer conclusions usually no longer mean anything because the underlying assumption is already wrong.&lt;/p&gt;

&lt;h3 id=&quot;32-checking-with-targeted-test-statistics&quot;&gt;3.2. Checking with targeted test statistics&lt;/h3&gt;

&lt;p&gt;Instead of checking a single quantity, we usually use a set of statistics&lt;/p&gt;

\[T(y)\in\{\bar y,\operatorname{Var}(y),Q_{0.95}(y),\max(y),\operatorname{IQR}(y)\}.\]

&lt;p&gt;Each statistic answers a different question: the mean for the center, the variance for dispersion, a high quantile and the max for the tails. A model can pass the check on the center but fail completely in the tails; therefore, if the problem involves extreme risk, a tail check must be treated as mandatory.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_multiple_test_statistics.png&quot; alt=&quot;Multiple Test Statistics&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;33-a-quantitative-example-correct-mean-wrong-tail&quot;&gt;3.3. A quantitative example: correct mean, wrong tail&lt;/h3&gt;

&lt;p&gt;Suppose the real data has a mean of about 20 and the model also reproduces this mean well. However, the observed maximum is 61, while the posterior predictive replicates rarely exceed 45. The correct scientific conclusion is then not “the model is good”, but “the model is suitable for the average level but not for extreme events”. The same model can be acceptable for everyday operational forecasting but cannot be used for tail-risk management.&lt;/p&gt;

&lt;h3 id=&quot;experiment-posterior-predictive-check&quot;&gt;Experiment: posterior predictive check&lt;/h3&gt;

&lt;p&gt;Simulate data replicates from the posterior and compare them with the real data through a test statistic.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;ppc-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-interpreting-the-bayesian-p-value-in-context&quot;&gt;4. Interpreting the Bayesian p-value in context&lt;/h2&gt;

&lt;p&gt;For a test statistic \(T(\cdot)\), the Bayesian p-value is written&lt;/p&gt;

\[p_B = P\big(T(\tilde y)\ge T(y)\mid y\big).\]

&lt;p&gt;A value around 0.5 indicates that the observed data is typical under the model for the statistic being considered; a value too close to 0 or 1 suggests that the observed data falls in a rare region of the world the model generates. The key point is that \(p_B\) is not a “final verdict” on the whole model: it reflects only one specific direction of checking, so it should always be read together with plots and with other statistics.&lt;/p&gt;

&lt;h2 id=&quot;5-using-ppc-to-diagnose-the-type-of-model-misfit&quot;&gt;5. Using PPC to diagnose the type of model misfit&lt;/h2&gt;

&lt;p&gt;The greatest strength of PPC is that it shows in what way the model is wrong, not only how much. In regression, three typical errors are variance that changes with the predictor (heteroskedasticity), a nonlinear relationship forced to be linear, and a likelihood whose tails are too thin to produce outliers. These three kinds of error leave three very different visual signatures on the residual plot and the Q-Q plot.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_model_inadequacy_detection.png&quot; alt=&quot;Model Inadequacy Detection&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_graphical_methods.png&quot; alt=&quot;Graphical PPC Methods&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;51-example-of-a-wrong-likelihood&quot;&gt;5.1. Example of a wrong likelihood&lt;/h3&gt;

&lt;p&gt;If the data has substantial outliers but the model uses a Normal likelihood, the posterior predictive usually reproduces the tails poorly and makes the prediction interval too narrow around the center. In this context, replacing the Normal with a Student-t is not “changing the model to make it look nice”, but fixing the mechanism correctly: we allow the data to produce outliers with a more reasonable probability.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter08/ppc_good_vs_bad_models.png&quot; alt=&quot;Good vs Bad PPC Models&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-practical-rules-to-avoid-a-formal-empty-ppc&quot;&gt;6. Practical rules to avoid a formal, empty PPC&lt;/h2&gt;

&lt;p&gt;Good PPC practice can be summarized in three principles. First, the statistic must be tied to the decision question; for example, a risk problem needs a tail check and must not stop at the mean. Second, always combine global and conditional checks; a model can be right on the global average but badly wrong in an important predictor region. Third, PPC does not stop at diagnosis but must lead to model revision: change the likelihood, add nonlinear structure, model the variance, or add group variables when there is evidence of leftover structure.&lt;/p&gt;

&lt;h2 id=&quot;7-conclusion-of-lesson-81&quot;&gt;7. Conclusion of Lesson 8.1&lt;/h2&gt;

&lt;p&gt;PPC is the bridge from inference to model criticism: it forces us to answer the core question of statistical modeling, namely whether the real data lies within the world the model creates. A mature workflow never ends at the parameter posterior; it is complete only when the model passes posterior predictive checks appropriate to the application goal.&lt;/p&gt;

&lt;p&gt;Next lesson: &lt;strong&gt;Information Criteria (WAIC, LOO)&lt;/strong&gt; to compare models on the same out-of-sample predictive criterion.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-catching-zero-inflation-with-a-hand-calculated-bayesian-p-value&quot;&gt;Worked Numerical Example: Catching Zero-Inflation With a Hand-Calculated Bayesian p-value&lt;/h3&gt;

&lt;p&gt;Suppose you observe 100 daily store orders with mean \(\bar{y} = 2.0\), and &lt;strong&gt;35 of the 100 days had 0 orders&lt;/strong&gt; (\(T(y_{\text{obs}}) = 35\) zeros). You fit a Poisson model (posterior \(\lambda \approx 2.0\)) and simulate 10 replicated 100-day datasets \(y^{\text{rep}}\) (expecting \(100 \cdot e^{-2} \approx 13.5\) zeros each):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Replicated Dataset \(s\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;1&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;2&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;3&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;4&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;5&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;6&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;7&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;8&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;9&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;10&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Simulated Zero Days \(T(y^{\text{rep},(s)})\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;12&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;15&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;11&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;14&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;18&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;13&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;16&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;10&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;14&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;15&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Compare against \(T(y_{\text{obs}}) = \mathbf{35}\) zeros: &lt;strong&gt;0 out of 10&lt;/strong&gt; replicated datasets ever reach 35 zeros (\(p_B = 0 / 10 = \mathbf{0.00}\))! Even though the Poisson model matched the &lt;em&gt;mean&lt;/em&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2.0&lt;/code&gt;) perfectly, the PPC proves conclusively that the real world has massive &lt;strong&gt;zero-inflation&lt;/strong&gt;—directing you immediately to a Zero-Inflated Poisson or Negative Binomial model!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-sharp-posterior-predictive-checks&quot;&gt;Explanation: Four Rules for Sharp Posterior Predictive Checks&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Never test a statistic the model is &lt;em&gt;forced&lt;/em&gt; to match:&lt;/strong&gt; Checking &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean(y_rep)&lt;/code&gt; on an OLS Normal model almost always gives \(p_B \approx 0.50\) even when the model is wildly misspecified—check &lt;strong&gt;tails, zeros, variance, skewness, and subgroup means&lt;/strong&gt; instead!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Don’t confuse a Bayesian p-value with a frequentist null p-value:&lt;/strong&gt; \(p_B = 0.02\) doesn’t mean “reject science”—it measures the specific aspect of reality your current generative story fails to capture.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Run PPCs on &lt;em&gt;held-out&lt;/em&gt; data when checking overfitting:&lt;/strong&gt; In-sample PPCs use the same data twice and can look slightly optimistic for very flexible models.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always pair visual plots with targeted numerical test statistics:&lt;/strong&gt; Eyes catch bimodal bumps; numerical \(T(y)\) catches subtle variance inflation.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Why is checking &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max(y_rep)&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fraction_of_zeros(y_rep)&lt;/code&gt; a much more informative Posterior Predictive Check for a Poisson model than checking &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean(y_rep)&lt;/code&gt;?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yDPJnV9vcHs&quot;&gt;What is a posterior predictive check and why is it useful?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the posterior predictive check as model criticism, matching the lesson’s separation of MCMC convergence from the fit of the generative story.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R9NQY2Hyl14&quot;&gt;26 - Prior and posterior predictive distributions - an introduction&lt;/a&gt; — Ox educ, English. Watch how prior predictive and posterior predictive differ, supporting the part on reproducing features of the data.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=IhTfuO8wSDA&quot;&gt;Posterior Predictive Sampling in PyMC by (Luciano Paz)&lt;/a&gt; — PyMC Developers, English. Watch how to draw posterior predictive samples in PyMC, for when the lesson moves from definition to practice.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why can a model that reproduces the mean well but is clearly wrong at \(Q_{0.95}\) still be dangerous in an operational problem?&lt;/li&gt;
  &lt;li&gt;When the Bayesian p-value of the variance statistic is very close to 1, which kind of misfit do you suspect first?&lt;/li&gt;
  &lt;li&gt;In a problem with high tail risk, which statistic would you prioritize adding to the PPC set, and why?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition), Chapter 6.&lt;/li&gt;
  &lt;li&gt;Gabry, J., et al. (2019). “Visualization in Bayesian workflow.” &lt;em&gt;JRSS A&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter08/08_02_information_criteria/&quot;&gt;8.2 Information Criteria (WAIC, LOO)&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 3.4: Hamiltonian Monte Carlo (HMC/NUTS) & Chẩn đoán Hội tụ</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter03/03_04_hmc_nuts_diagnostics/"/>
   <updated>2025-01-03T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter03/03_04_hmc_nuts_diagnostics</id>
   <content type="html">&lt;p&gt;Trong không gian 100 chiều, một bước nhảy ngẫu nhiên mù quáng của Metropolis gần như chắc chắn rơi ra ngoài vùng có xác suất cao (“tập điển hình” — &lt;em&gt;typical set&lt;/em&gt;), khiến chuỗi giậm chân tại chỗ. Các công cụ hiện đại như &lt;strong&gt;PyMC&lt;/strong&gt;, &lt;strong&gt;Stan&lt;/strong&gt; và &lt;strong&gt;NumPyro&lt;/strong&gt; giải quyết bài toán này bằng một ý tưởng mượn từ vật lý cơ học cổ điển: &lt;strong&gt;Hamiltonian Monte Carlo (HMC)&lt;/strong&gt; và biến thể tự điều chỉnh &lt;strong&gt;No-U-Turn Sampler (NUTS)&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-cơ-học-hamiltonian-trong-hmc-so-với-bước-nhảy-ngẫu-nhiên&quot;&gt;Video ngắn: Cơ học Hamiltonian trong HMC so với bước nhảy ngẫu nhiên&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/mcmc-metropolis-hmc.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video minh họa trực quan bằng mô phỏng vật lý: so sánh bước đi ngẫu nhiên Metropolis dễ bị từ chối với viên bi HMC trượt không ma sát trong giếng thế năng \(U(\theta) = -\log p(\theta \mid y)\) nhờ tích phân nhảy cóc (leapfrog) bảo toàn năng lượng.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Hiểu ẩn dụ vật lý của HMC: biến hậu nghiệm thành thế năng \(U(\theta) = -\log \tilde{p}(\theta)\), bơm động lượng ngẫu nhiên \(p\) và trượt theo phương trình Hamilton.&lt;/li&gt;
  &lt;li&gt;Nắm vai trò của thuật toán &lt;strong&gt;Leapfrog&lt;/strong&gt; và cơ chế dừng tự động &lt;strong&gt;NUTS&lt;/strong&gt; (No-U-Turn Sampler).&lt;/li&gt;
  &lt;li&gt;Sử dụng thành thạo bốn chỉ số chẩn đoán hội tụ bắt buộc trong ArviZ/PyMC: &lt;strong&gt;Trace plot&lt;/strong&gt;, &lt;strong&gt;\(\hat{R}\) (Gelman–Rubin)&lt;/strong&gt;, &lt;strong&gt;ESS (Effective Sample Size)&lt;/strong&gt; và &lt;strong&gt;Divergent transitions&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-từ-bước-đi-ngẫu-nhiên-sang-động-lực-học-hamilton&quot;&gt;Kiến thức cần nhớ: Từ Bước đi Ngẫu nhiên sang Động lực học Hamilton&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thế năng và Động năng:&lt;/strong&gt; Đặt thế năng \(U(\theta) = -\log \tilde{p}(\theta)\) (đỉnh hậu nghiệm trở thành đáy thung lũng) và động năng \(K(p) = \frac{1}{2} p^T M^{-1} p\). Tổng cơ năng (Hamiltonian) là \(H(\theta, p) = U(\theta) + K(p)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương trình Hamilton:&lt;/strong&gt;
\(\frac{d\theta}{dt} = \frac{\partial H}{\partial p} = M^{-1} p, \qquad \frac{dp}{dt} = -\frac{\partial H}{\partial \theta} = \nabla_\theta \log \tilde{p}(\theta).\)
Nhờ sử dụng &lt;strong&gt;gradient&lt;/strong&gt; \(\nabla_\theta \log \tilde{p}(\theta)\), hạt HMC biết chính xác hướng thung lũng để lướt đi rất xa chỉ trong một lần lấy mẫu mà vẫn giữ tỷ lệ chấp nhận cao!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích phân nhảy cóc (Leapfrog Integrator):&lt;/strong&gt; Rời rạc hóa thời gian bằng bước \(\epsilon\) theo thứ tự: nửa bước động lượng \(\to\) trọn bước vị trí \(\to\) nửa bước động lượng, giúp bảo toàn thể tích không gian pha (symplectic) và độ lệch năng lượng nhỏ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;NUTS (Hoffman &amp;amp; Gelman, 2014):&lt;/strong&gt; Tự động dừng quỹ đạo ngay khi hạt bắt đầu quay đầu (U-turn), loại bỏ gánh nặng chọn tay số bước \(L\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1-bốn-trụ-cột-chẩn-đoán-hội-tụ-mcmc&quot;&gt;1. Bốn trụ cột Chẩn đoán Hội tụ MCMC&lt;/h2&gt;

&lt;p&gt;Chạy xong MCMC &lt;strong&gt;chưa bao giờ&lt;/strong&gt; đồng nghĩa với kết quả đã đáng tin. Trước khi đọc bảng summary, hãy luôn kiểm tra:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter03/mcmc_diagnostics.png&quot; alt=&quot;So sánh chuỗi MCMC hội tụ tốt và chuỗi chưa hội tụ&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 3.4. Trái: 3 chuỗi độc lập trộn đều như “con sâu rậm lông” (\(\hat{R} \approx 1.00\), ESS cao). Phải: các chuỗi trôi dạt tách biệt nhau (\(\hat{R} &amp;gt; 1.2\)) — tuyệt đối không được dùng để suy luận.&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Trace Plot &amp;amp; Rank Plot:&lt;/strong&gt; Nhiều chuỗi khởi tạo từ điểm khác nhau phải trộn chồng khít lên nhau, không có xu hướng trôi dạt hay bị kẹt phẳng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thống kê Gelman–Rubin (\(\hat{R}\)):&lt;/strong&gt; Đo tỷ số giữa phương sai &lt;strong&gt;giữa các chuỗi&lt;/strong&gt; và phương sai &lt;strong&gt;trong từng chuỗi&lt;/strong&gt;. Ngưỡng chuẩn hiện đại (Vehtari et al., 2021): &lt;strong&gt;\(\hat{R} &amp;lt; 1.01\)&lt;/strong&gt; (ngưỡng cổ điển trong Kruschke là \(1.1\) nhưng nay quá lỏng).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cỡ mẫu hiệu dụng (ESS — Effective Sample Size):&lt;/strong&gt; Vì các mẫu MCMC có tự tương quan \(\rho_k\) ở độ trễ \(k\), lượng thông tin thực sự của \(N\) mẫu chỉ tương đương:
\(\text{ESS} = \frac{N}{1 + 2\sum_{k=1}^{\infty} \rho_k}.\)
Nên đạt \(\text{ESS}_{\text{bulk}} &amp;gt; 400\) (và \(\text{ESS}_{\text{tail}} &amp;gt; 400\)) cho mọi tham số; nếu cần biên 95% HDI rất ổn định, Kruschke khuyến nghị ESS cỡ vài nghìn trở lên.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Divergent Transitions (Chuyển trạng thái phân kỳ):&lt;/strong&gt; Đặc trưng cực quý của HMC/NUTS! Khi độ cong hậu nghiệm quá gắt (như phễu Neal ở Chương 9), bước nhảy Leapfrog bị văng năng lượng tạo ra &lt;strong&gt;divergence&lt;/strong&gt;. Dù chỉ có vài divergence cũng là tín hiệu cảnh báo cấu trúc hình học mô hình cần được tái tham số hóa.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-cầm-tay-chỉ-việc-chẩn-đoán-chuỗi-với-pymc-và-arviz&quot;&gt;Ví dụ cầm tay chỉ việc: Chẩn đoán chuỗi với PyMC và ArviZ&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Binomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draws&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_accept&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hdi_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sd&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;hdi_2.5%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;hdi_97.5%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ess_bulk&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ess_tail&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r_hat&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Số divergence:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;diverging&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tự cài đặt Leapfrog 1 chiều:&lt;/strong&gt; Cho thế năng \(U(\theta) = \frac{1}{2}\theta^2\) (tương ứng chuẩn tắc \(\mathcal{N}(0,1)\)). Viết 10 dòng Python mô phỏng 100 bước Leapfrog từ \((\theta_0, p_0) = (0, 1)\) với \(\epsilon = 0.2\) và \(\epsilon = 1.9\). Quan sát tổng năng lượng \(H = \frac{1}{2}(\theta^2 + p^2)\) ở hai trường hợp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính tay ESS:&lt;/strong&gt; Một chuỗi dài \(N = 4000\) có tự tương quan suy giảm theo cấp số nhân \(\rho_k = 0.8^k\). Dùng công thức chuỗi hình học để tính \(\text{ESS}\) và cho biết chuỗi này tương đương bao nhiêu mẫu độc lập.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chẩn đoán thực tế:&lt;/strong&gt; Chạy đoạn mã PyMC ở trên với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;draws=50, tune=20&lt;/code&gt; rồi tăng lên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;draws=2000, tune=1000&lt;/code&gt;. So sánh \(\hat{R}\), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ess_bulk&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ess_tail&lt;/code&gt; và độ ổn định của biên 95% HDI giữa hai lần chạy.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 3.3: Monte Carlo, Metropolis–Hastings & Gibbs Sampling</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter03/03_03_monte_carlo_and_mcmc/"/>
   <updated>2025-01-03T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter03/03_03_monte_carlo_and_mcmc</id>
   <content type="html">&lt;p&gt;Trong một mô hình Bayes có 20 tham số, xấp xỉ lưới đòi hỏi số điểm nhiều hơn số nguyên tử trong vũ trụ, còn xấp xỉ Laplace lại thất bại khi hậu nghiệm lệch hoặc hình phễu. Làm sao lấy mẫu chính xác từ \(p(\theta \mid y) = \frac{p(y \mid \theta) p(\theta)}{p(y)}\) khi ta &lt;strong&gt;thậm chí không tính được hằng số chuẩn hóa \(p(y)\)&lt;/strong&gt; ở mẫu số? Câu trả lời làm thay đổi toàn bộ khoa học dữ liệu thế kỷ 20–21 là &lt;strong&gt;Markov Chain Monte Carlo (MCMC)&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-metropolishastings-bước-nhảy-chấp-nhậntừ-chối&quot;&gt;Video ngắn: Metropolis–Hastings: bước nhảy chấp nhận/từ chối&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/metropolis-random-walk.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 26 giây (có thuyết minh tiếng Việt): minh họa từng bước đề xuất, tỷ số chấp nhận r triệt tiêu mẫu số p(y), chấp nhận/từ chối và quá trình mẫu tụ về đỉnh Beta(7, 4).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Hiểu tại sao tỷ số hậu nghiệm \(\frac{p(\theta^* \mid y)}{p(\theta^{(t)} \mid y)}\) triệt tiêu hoàn toàn hằng số chuẩn hóa \(p(y)\).&lt;/li&gt;
  &lt;li&gt;Nắm vững quy tắc đề xuất và chấp nhận của thuật toán &lt;strong&gt;Metropolis–Hastings&lt;/strong&gt; (theo Blitzstein &amp;amp; Hwang và Kruschke).&lt;/li&gt;
  &lt;li&gt;Hiểu &lt;strong&gt;Gibbs Sampling&lt;/strong&gt; như trường hợp đặc biệt của Metropolis–Hastings với tỷ lệ chấp nhận 100% khi biết phân phối điều kiện đầy đủ.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-chuỗi-markov-và-cân-bằng-chi-tiết&quot;&gt;Kiến thức cần nhớ: Chuỗi Markov và Cân bằng chi tiết&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ý tưởng cốt lõi:&lt;/strong&gt; Thay vì rút các mẫu độc lập, MCMC xây dựng một bước đi ngẫu nhiên (chuỗi Markov \(\theta^{(0)}, \theta^{(1)}, \theta^{(2)}, \dots\)) sao cho &lt;strong&gt;phân phối dừng (stationary distribution)&lt;/strong&gt; của chuỗi trùng đúng với hậu nghiệm \(p(\theta \mid y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điều kiện cân bằng chi tiết (Detailed Balance):&lt;/strong&gt; Nếu xác suất chuyển trạng thái \(T(\theta \to \theta&apos;)\) thỏa mãn
\(\pi(\theta)\,T(\theta \to \theta&apos;) = \pi(\theta&apos;)\,T(\theta&apos; \to \theta)\)
thì \(\pi(\theta) = p(\theta \mid y)\) chắc chắn là phân phối dừng của chuỗi.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Triệt tiêu hằng số chuẩn hóa:&lt;/strong&gt; Vì quy tắc chấp nhận chỉ dùng tỷ số \(\frac{\tilde{p}(\theta^*)}{\tilde{p}(\theta^{(t)})}\) với \(\tilde{p}(\theta) = p(y \mid \theta) p(\theta)\), ta không bao giờ phải tính tích phân mẫu số \(p(y)\)!&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1-thuật-toán-metropolishastings&quot;&gt;1. Thuật toán Metropolis–Hastings&lt;/h2&gt;

&lt;p&gt;Bắt đầu từ trạng thái hiện tại \(\theta^{(t)}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đề xuất (Propose):&lt;/strong&gt; Rút ứng viên \(\theta^* \sim q(\theta^* \mid \theta^{(t)})\) (ví dụ: bước nhảy Gaussian \(\theta^* = \theta^{(t)} + \epsilon,\ \epsilon \sim \mathcal{N}(0, \sigma_{\text{step}}^2)\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính xác suất chấp nhận:&lt;/strong&gt;
\(\alpha(\theta^{(t)}, \theta^*) = \min\!\left(1,\ \frac{\tilde{p}(\theta^*)\, q(\theta^{(t)} \mid \theta^*)}{\tilde{p}(\theta^{(t)})\, q(\theta^* \mid \theta^{(t)})}\right).\)
Nếu phân phối đề xuất đối xứng (\(q(\theta^{(t)} \mid \theta^*) = q(\theta^* \mid \theta^{(t)})\)), tỷ số \(q\) triệt tiêu — ta thu được &lt;strong&gt;thuật toán Metropolis&lt;/strong&gt; kinh điển.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quyết định:&lt;/strong&gt; Rút \(u \sim \operatorname{Uniform}(0, 1)\). Nếu \(u &amp;lt; \alpha\) thì nhận \(\theta^{(t+1)} = \theta^*\); ngược lại giữ nguyên \(\theta^{(t+1)} = \theta^{(t)}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-cầm-tay-chỉ-việc-3-bước-metropolis-trên-operatornamebeta7-4&quot;&gt;Ví dụ cầm tay chỉ việc: 3 bước Metropolis trên \(\operatorname{Beta}(7, 4)\)&lt;/h3&gt;

&lt;p&gt;Với mật độ chưa chuẩn hóa \(\tilde{p}(\theta) = \theta^6 (1-\theta)^3\) trên \((0, 1)\), giả sử chuỗi bắt đầu ở \(\theta^{(0)} = 0.40\) (\(\tilde{p}(0.40) = 0.4^6 \cdot 0.6^3 \approx 8.85 \times 10^{-4}\)):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1:&lt;/strong&gt; Đề xuất \(\theta^* = 0.60\) (\(\tilde{p}(0.60) = 0.6^6 \cdot 0.4^3 \approx 2.99 \times 10^{-3}\)). Tỷ số \(r = 2.99/0.885 \approx 3.37 &amp;gt; 1 \implies \alpha = 1\). &lt;strong&gt;Chấp nhận chắc chắn&lt;/strong&gt;, chuyển sang \(\theta^{(1)} = 0.60\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2:&lt;/strong&gt; Đề xuất \(\theta^* = 0.85\) (\(\tilde{p}(0.85) \approx 1.27 \times 10^{-3}\)). Tỷ số \(r = 1.27/2.99 \approx 0.425\). Rút \(u = 0.62 &amp;gt; 0.425 \implies\) &lt;strong&gt;Từ chối&lt;/strong&gt;, giữ nguyên \(\theta^{(2)} = 0.60\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3:&lt;/strong&gt; Đề xuất \(\theta^* = 0.70\) (\(\tilde{p}(0.70) \approx 3.18 \times 10^{-3}\)). Tỷ số \(r \approx 1.06 &amp;gt; 1 \implies \alpha = 1\). &lt;strong&gt;Chấp nhận&lt;/strong&gt;, chuyển sang \(\theta^{(3)} = 0.70\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter03/mh_trace_hist.png&quot; alt=&quot;Quỹ đạo và phân phối mẫu Metropolis-Hastings cho Beta(7,4)&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 3.3. Chuỗi Metropolis đi lang thang qua không gian tham số (trái); sau khi bỏ đoạn burn-in, biểu đồ tần suất khớp chặt với phân phối \(\operatorname{Beta}(7, 4)\) thực sự (phải).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-gibbs-sampling-cập-nhật-luân-phiên-theo-tọa-độ&quot;&gt;2. Gibbs Sampling: Cập nhật luân phiên theo tọa độ&lt;/h2&gt;

&lt;p&gt;Khi có nhiều tham số \((\theta_1, \theta_2, \dots, \theta_d)\) và ta biết dạng giải tích của từng &lt;strong&gt;phân phối điều kiện đầy đủ&lt;/strong&gt; \(p(\theta_j \mid \theta_{-j}, y)\), &lt;strong&gt;Gibbs Sampling&lt;/strong&gt; lần lượt rút:
\(\theta_1^{(t+1)} \sim p(\theta_1 \mid \theta_2^{(t)}, \dots, \theta_d^{(t)}, y), \qquad \theta_2^{(t+1)} \sim p(\theta_2 \mid \theta_1^{(t+1)}, \dots, \theta_d^{(t)}, y), \dots\)&lt;/p&gt;

&lt;p&gt;Như Kruschke chỉ ra, Gibbs Sampling chính là một trường hợp đặc biệt của Metropolis–Hastings trong đó đề xuất trùng khít với phân phối điều kiện đầy đủ nên xác suất chấp nhận luôn bằng &lt;strong&gt;100%&lt;/strong&gt;. Tuy nhiên, khi các tham số tương quan mạnh (hậu nghiệm dạng hẻm núi chéo hẹp), cả Random-Walk Metropolis lẫn Gibbs đều đi zíc-zắc cực chậm — mở đường cho HMC/NUTS ở bài 3.4.&lt;/p&gt;

&lt;h3 id=&quot;tương-tác-chạy-thử-metropolis-gibbs-và-hmc&quot;&gt;Tương tác: Chạy thử Metropolis, Gibbs và HMC&lt;/h3&gt;

&lt;div data-demo=&quot;mcmc-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Ảnh hưởng của bước nhảy \(\sigma_{\text{step}}\):&lt;/strong&gt; Viết vòng lặp Metropolis 5.000 bước cho \(\operatorname{Beta}(7, 4)\) với ba giá trị \(\sigma_{\text{step}} \in \{0.01,\ 0.25,\ 2.0\}\). So sánh tỷ lệ chấp nhận và hình dạng trace plot.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chứng minh cân bằng chi tiết:&lt;/strong&gt; Kiểm tra trực tiếp rằng với xác suất chấp nhận \(\alpha(x, y) = \min\!\left(1, \frac{\pi(y) q(x \mid y)}{\pi(x) q(y \mid x)}\right)\), đẳng thức \(\pi(x) q(y \mid x) \alpha(x, y) = \pi(y) q(x \mid y) \alpha(y, x)\) luôn đúng với mọi \(x \neq y\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gibbs cho chuẩn 2 chiều:&lt;/strong&gt; Biết \((X, Y) \sim \mathcal{N}\!\left(\mathbf{0}, \begin{pmatrix} 1 &amp;amp; \rho \\ \rho &amp;amp; 1 \end{pmatrix}\right)\) với \(\rho = 0.95\). Viết Gibbs sampler dùng \(X \mid Y=y \sim \mathcal{N}(\rho y, 1-\rho^2)\) và quan sát hiện tượng tự tương quan cao khi \(\rho \to 1\).&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 3.2: Xấp xỉ Laplace (Quadratic Approximation)</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter03/03_02_laplace_approximation/"/>
   <updated>2025-01-03T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter03/03_02_laplace_approximation</id>
   <content type="html">&lt;p&gt;Xấp xỉ lưới ở Chương 2 hoạt động hoàn hảo trong 1–2 chiều, nhưng hoàn toàn sụp đổ khi mô hình có 10 hay 50 tham số. Trước khi dùng đến MCMC, các nhà thống kê (từ Pierre-Simon Laplace thế kỷ 18 đến hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;quap()&lt;/code&gt; trong &lt;em&gt;Statistical Rethinking&lt;/em&gt;) phát hiện một hiện tượng đáng kinh ngạc: khi cỡ mẫu đủ lớn, đỉnh của hầu hết phân phối hậu nghiệm trơn đều trông giống một &lt;strong&gt;hình chuông Gaussian&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-xấp-xỉ-laplace-hội-tụ-khi-cỡ-mẫu-n-tăng&quot;&gt;Video ngắn: Xấp xỉ Laplace hội tụ khi cỡ mẫu n tăng&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/laplace-quadratic-approx.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 28 giây (có thuyết minh tiếng Việt): so sánh đường chuẩn Gaussian Laplace tại đỉnh MAP với phân phối Beta chính xác khi tăng cỡ mẫu n từ 6 → 9 → 30 → 75 kèm độ cong Hessian H cập nhật trực tiếp.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Hiểu ý tưởng khai triển Taylor bậc 2 quanh điểm MAP của \(\log p(\theta \mid y)\).&lt;/li&gt;
  &lt;li&gt;Tự tính tay được xấp xỉ Laplace cho mô hình Beta–Binomial và đối chiếu với hậu nghiệm chính xác.&lt;/li&gt;
  &lt;li&gt;Nhận diện rõ khi nào xấp xỉ Laplace chính xác và khi nào nó thất bại (mẫu nhỏ, biên tham số, hậu nghiệm đa đỉnh).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-định-lý-bernsteinvon-mises-và-khai-triển-taylor&quot;&gt;Kiến thức cần nhớ: Định lý Bernstein–von Mises và Khai triển Taylor&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Độ cong quyết định độ bất định:&lt;/strong&gt; Log-hậu nghiệm \(\ell(\theta) = \log p(\theta \mid y)\) đạt cực đại tại \(\hat{\theta}_{\text{MAP}}\) (nơi đạo hàm bậc nhất \(\ell&apos;(\hat{\theta}_{\text{MAP}}) = 0\)). Độ cong âm \(H = -\ell&apos;&apos;(\hat{\theta}_{\text{MAP}})\) càng lớn (đỉnh càng nhọn), phương sai hậu nghiệm \(\sigma^2 \approx 1/H\) càng nhỏ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Công thức xấp xỉ bậc hai (Quadratic Approximation):&lt;/strong&gt;
\(\log p(\theta \mid y) \approx \log p(\hat{\theta}_{\text{MAP}} \mid y) - \frac{1}{2} H (\theta - \hat{\theta}_{\text{MAP}})^2 \implies \theta \mid y \approx \mathcal{N}\!\left(\hat{\theta}_{\text{MAP}},\ H^{-1}\right).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trong nhiều chiều:&lt;/strong&gt; Với vector tham số \(\boldsymbol{\theta} \in \mathbb{R}^d\), ma trận hiệp phương sai xấp xỉ là nghịch đảo của ma trận Hessian âm: \(\boldsymbol{\Sigma} = \left[-\nabla^2 \log p(\boldsymbol{\theta} \mid y)\big\vert_{\hat{\boldsymbol{\theta}}_{\text{MAP}}}\right]^{-1}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1-ví-dụ-cầm-tay-chỉ-việc-xấp-xỉ-laplace-cho-bài-toán-tung-đồng-xu&quot;&gt;1. Ví dụ cầm tay chỉ việc: Xấp xỉ Laplace cho bài toán tung đồng xu&lt;/h2&gt;

&lt;p&gt;Giả sử prior là \(\operatorname{Beta}(1, 1)\) (đều) và ta quan sát \(k = 6\) mặt ngửa trong \(n = 9\) lần tung. Hậu nghiệm chính xác là \(\operatorname{Beta}(7, 4)\), có hàm log-hậu nghiệm (bỏ hằng số):&lt;/p&gt;

\[\ell(\theta) = 6 \ln \theta + 3 \ln(1 - \theta).\]

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tìm điểm MAP:&lt;/strong&gt; Giải \(\ell&apos;(\theta) = \frac{6}{\theta} - \frac{3}{1-\theta} = 0 \implies \hat{\theta}_{\text{MAP}} = \frac{6}{9} \approx 0.667\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính đạo hàm bậc hai (Hessian):&lt;/strong&gt;
\(\ell&apos;&apos;(\theta) = -\frac{6}{\theta^2} - \frac{3}{(1-\theta)^2}.\)
Tại \(\hat{\theta} = 2/3\): \(H = -\ell&apos;&apos;(2/3) = \frac{6}{(2/3)^2} + \frac{3}{(1/3)^2} = 13.5 + 27 = 40.5\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Suy ra xấp xỉ Gaussian:&lt;/strong&gt; Độ lệch chuẩn \(\hat{\sigma} = 1/\sqrt{40.5} \approx 0.157\), nên Laplace cho \(\theta \mid y \approx \mathcal{N}(0.667,\ 0.157^2)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter03/laplace_approximation.png&quot; alt=&quot;So sánh Xấp xỉ Laplace và Beta chính xác khi n=9 và n=30&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 3.2. Với \(n=9\) (trái), xấp xỉ Laplace hơi đối xứng quá mức và tràn nhẹ qua \(\theta=1\); khi tăng lên \(n=30\) (phải), đường nét đứt Laplace gần như trùng khít với phân phối Beta chính xác.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-khi-nào-xấp-xỉ-laplace-thất-bại&quot;&gt;2. Khi nào Xấp xỉ Laplace thất bại?&lt;/h2&gt;

&lt;p&gt;Dù cực nhanh (chỉ cần tối ưu hóa tìm cực đại và tính Hessian), xấp xỉ Laplace có ba điểm mù lớn:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối lệch mạnh hoặc gần biên:&lt;/strong&gt; Ví dụ tham số độ lệch chuẩn \(\sigma &amp;gt; 0\) hay xác suất \(p \approx 0.01\) — đường cong Gaussian có thể gán xác suất cho giá trị âm vô nghĩa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hậu nghiệm đa đỉnh (multimodal):&lt;/strong&gt; Khai triển Taylor cục bộ quanh một đỉnh sẽ mù hoàn toàn với các đỉnh còn lại (rất phổ biến trong mô hình hỗn hợp ở Chương 10).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hình học hình phễu (Neal’s Funnel):&lt;/strong&gt; Trong mô hình phân cấp (Chương 9), độ cong thay đổi dữ dội theo vùng nên một ma trận Hessian duy nhất không thể đại diện cho toàn bộ hậu nghiệm.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;tương-tác-so-sánh-lưới-chính-xác-với-xấp-xỉ-trơn&quot;&gt;Tương tác: So sánh lưới chính xác với xấp xỉ trơn&lt;/h3&gt;

&lt;div data-demo=&quot;grid-explainer&quot; data-lang=&quot;vi&quot; data-prior=&quot;flat&quot; data-k=&quot;6&quot; data-n=&quot;9&quot; data-points=&quot;100&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính tay cho mô hình Gamma–Poisson:&lt;/strong&gt; Giả sử \(y_1, \dots, y_n \sim \operatorname{Poisson}(\lambda)\) với tổng \(S = \sum y_i = 20, n = 4\) và prior \(\lambda \sim \operatorname{Gamma}(2, 1)\). Tìm \(\hat{\lambda}_{\text{MAP}}\), tính \(H = -\ell&apos;&apos;(\hat{\lambda}_{\text{MAP}})\) và viết phân phối Laplace xấp xỉ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biến đổi sang thang không bị chặn:&lt;/strong&gt; Nếu đặt \(\phi = \operatorname{logit}(\theta) = \ln\frac{\theta}{1-\theta}\), vì sao xấp xỉ Laplace trên \(\phi\) thường chính xác hơn nhiều so với trên \(\theta \in (0, 1)\)?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thực hành Python:&lt;/strong&gt; Dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.optimize.minimize&lt;/code&gt; để tìm MAP và nghịch đảo Hessian cho bài toán hồi quy logistic 1 biến trên 30 điểm dữ liệu mô phỏng.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 3.1: Lấy mẫu từ Hậu nghiệm & Khoảng đáng tin (HDI vs. ETI)</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter03/03_01_sampling_the_imaginary/"/>
   <updated>2025-01-03T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter03/03_01_sampling_the_imaginary</id>
   <content type="html">&lt;p&gt;Một bác sĩ nói với bạn rằng xét nghiệm dương tính có xác suất mắc bệnh thực sự là 0.16, nhưng bệnh nhân lại rất khó hình dung “0.16” là lớn hay nhỏ. Nếu đổi sang ngôn ngữ tần suất tự nhiên — &lt;em&gt;trong 1.000 người có kết quả dương tính, chỉ khoảng 160 người thực sự mắc bệnh&lt;/em&gt; — mọi người lập tức hiểu ra. Đó chính là triết lý &lt;strong&gt;Lấy mẫu từ Hậu nghiệm (Sampling the Imaginary)&lt;/strong&gt; của Richard McElreath: thay vì vật lộn với các tích phân giải tích phức tạp trên phân phối hậu nghiệm \(p(\theta \mid y)\), ta rút hàng nghìn mẫu \(\theta^{(1)}, \dots, \theta^{(S)}\) từ hậu nghiệm và biến mọi câu hỏi xác suất thành &lt;strong&gt;phép đếm đơn giản&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;
&lt;h3 id=&quot;video-ngắn-lấy-mẫu-hậu-nghiệm-hdi-vs-eti-trên-phân-phối-lệch&quot;&gt;Video ngắn: Lấy mẫu hậu nghiệm: HDI vs. ETI trên phân phối lệch&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/sampling-hdi-eti.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 38 giây (có thuyết minh tiếng Việt): rút mẫu từ phân phối lệch Beta(2, 10), so sánh khoảng 95% ETI cắt đều 2 đuôi với khoảng 95% HDI hẹp nhất bằng đường ngưỡng mật độ trượt trực tiếp.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Biến đổi các bài toán tích phân hậu nghiệm (xác suất khoảng, kỳ vọng hàm phi tuyến, dự báo hậu nghiệm) thành phép đếm trên tập mẫu.&lt;/li&gt;
  &lt;li&gt;Phân biệt rạch ròi &lt;strong&gt;Khoảng mật độ cao nhất (HDI / HPDI)&lt;/strong&gt; với &lt;strong&gt;Khoảng hai đuôi đều nhau (ETI / Percentile Interval)&lt;/strong&gt; trên phân phối lệch.&lt;/li&gt;
  &lt;li&gt;Hiểu cách chọn ước lượng điểm tối ưu (mean, median, MAP) gắn với từng hàm mất mát (loss function).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-từ-tích-phân-sang-phép-đếm&quot;&gt;Kiến thức cần nhớ: Từ Tích phân sang Phép đếm&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tích phân Monte Carlo cơ bản:&lt;/strong&gt; Với mọi hàm \(g(\theta)\), kỳ vọng hậu nghiệm \(\mathbb{E}[g(\theta) \mid y] = \int g(\theta) p(\theta \mid y)\,d\theta \approx \frac{1}{S}\sum_{s=1}^S g(\theta^{(s)})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất hậu nghiệm của một mệnh đề:&lt;/strong&gt; \(P(\theta &amp;gt; c \mid y) \approx \frac{1}{S}\sum_{s=1}^S \mathbb{I}(\theta^{(s)} &amp;gt; c)\). Không cần tra bảng hay tính tích phân tay.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tóm tắt bất định (Credible Intervals):&lt;/strong&gt; Khác với khoảng tin cậy tần suất (confidence interval), khoảng đáng tin 95% (credible interval) cho phép phát biểu trực tiếp: &lt;em&gt;với dữ liệu đã quan sát và mô hình đã chọn, xác suất tham số nằm trong khoảng này là 95%&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1-hdi-và-eti-khi-nào-hai-khoảng-này-khác-nhau&quot;&gt;1. HDI và ETI: Khi nào hai khoảng này khác nhau?&lt;/h2&gt;

&lt;p&gt;Xét phân phối hậu nghiệm lệch phải \(\theta \mid y \sim \operatorname{Beta}(2, 10)\) (ví dụ: quan sát 1 ca thành công trong 10 thử nghiệm với prior đều \(\operatorname{Beta}(1, 1)\)).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter03/hdi_vs_eti.png&quot; alt=&quot;So sánh 95% ETI và 95% HDI trên phân phối lệch Beta(2,10)&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 3.1. Trên phân phối lệch phải \(\operatorname{Beta}(2, 10)\), khoảng ETI cắt đều 2.5% mỗi đuôi nên dài hơn và bỏ sót vùng mật độ cao gần 0, trong khi 95% HDI là khoảng hẹp nhất chứa đúng các giá trị khả dĩ nhất.&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Equal-Tailed Interval (ETI 95%):&lt;/strong&gt; Lấy phân vị thứ 2.5% và 97.5%. Với \(\operatorname{Beta}(2, 10)\), ETI 95% là \([0.023,\ 0.413]\) (độ rộng \(0.390\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Highest Density Interval (HDI 95%):&lt;/strong&gt; Là khoảng &lt;strong&gt;ngắn nhất&lt;/strong&gt; chứa 95% khối lượng xác suất, sao cho mọi điểm bên trong đều có mật độ cao hơn mọi điểm bên ngoài (Kruschke, &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt;). Với \(\operatorname{Beta}(2, 10)\), HDI 95% là \([0.005,\ 0.365]\) (độ rộng \(0.360\)), bao gồm cả đỉnh mode tại \(\theta = 1/10 = 0.10\) và dịch sát về phía vùng mật độ cao.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;ví-dụ-cầm-tay-chỉ-việc-tóm-tắt-mẫu-hậu-nghiệm-bằng-python&quot;&gt;Ví dụ cầm tay chỉ việc: Tóm tắt mẫu hậu nghiệm bằng Python&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20_000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 1. Câu hỏi xác suất trực tiếp bằng phép đếm
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_below_20&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;          &lt;span class=&quot;c1&quot;&gt;# ~ 0.678
# 2. ETI 95%
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eti_95&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quantile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.025&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.975&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 3. HDI 95% (thuật toán cửa sổ trượt ngắn nhất trên mẫu đã sắp xếp)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ceil&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.95&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;widths&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;i_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;widths&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;hdi_95&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;P(theta &amp;lt; 0.20) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_below_20&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, ETI = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eti_95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, HDI = (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hdi_95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hdi_95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;2-hàm-mất-mát-và-ước-lượng-điểm&quot;&gt;2. Hàm mất mát và Ước lượng điểm&lt;/h2&gt;

&lt;p&gt;Nếu buộc phải chọn một con số duy nhất \(\hat{\theta}\) thay vì cả phân phối hậu nghiệm, ta phải chỉ rõ &lt;strong&gt;hàm mất mát&lt;/strong&gt; \(L(\theta, \hat{\theta})\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Hàm mất mát&lt;/th&gt;
      &lt;th&gt;Biểu thức \(L(\theta, \hat{\theta})\)&lt;/th&gt;
      &lt;th&gt;Ước lượng điểm tối ưu Bayes&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Sai số bình phương&lt;/td&gt;
      &lt;td&gt;\((\theta - \hat{\theta})^2\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Posterior Mean&lt;/strong&gt; \(\mathbb{E}[\theta \mid y]\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Sai số tuyệt đối&lt;/td&gt;
      &lt;td&gt;\(\vert \theta - \hat{\theta} \vert\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Posterior Median&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mất mát 0–1&lt;/td&gt;
      &lt;td&gt;\(\mathbb{I}(\theta \neq \hat{\theta})\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;MAP (Posterior Mode)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;tương-tác-so-sánh-khoảng-tin-cậy-và-khoảng-đáng-tin&quot;&gt;Tương tác: So sánh khoảng tin cậy và khoảng đáng tin&lt;/h3&gt;

&lt;div data-demo=&quot;interval-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-dự-báo-hậu-nghiệm-posterior-predictive-sampling&quot;&gt;3. Dự báo Hậu nghiệm (Posterior Predictive Sampling)&lt;/h2&gt;

&lt;p&gt;Từ tập mẫu \(\theta^{(s)}\), ta dễ dàng tạo &lt;strong&gt;phân phối dự báo hậu nghiệm&lt;/strong&gt; cho dữ liệu mới \(\tilde{y}\) mà không cần giải tích phân \(\int p(\tilde{y} \mid \theta) p(\theta \mid y)\,d\theta\): chỉ cần với mỗi \(\theta^{(s)}\), sinh \(\tilde{y}^{(s)} \sim p(\tilde{y} \mid \theta^{(s)})\). Bằng cách này, dự báo tự động mang theo &lt;strong&gt;cả hai nguồn bất định&lt;/strong&gt;: bất định về tham số \(\theta\) và bất định ngẫu nhiên của chính quá trình quan sát.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-tập-thực-hành&quot;&gt;Bài tập thực hành&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính tay và kiểm chứng bằng mẫu:&lt;/strong&gt; Cho hậu nghiệm \(\theta \mid y \sim \operatorname{Beta}(1, 5)\). Hãy tính giải tích xác suất \(P(\theta &amp;lt; 0.3 \mid y)\), sau đó rút \(10^4\) mẫu bằng NumPy để đối chiếu sai số Monte Carlo.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;HDI vs. ETI:&lt;/strong&gt; Với hậu nghiệm \(\operatorname{Beta}(1, 5)\), hãy giải thích tại sao đầu dưới của 95% HDI đúng bằng \(0\) trong khi đầu dưới của 95% ETI lớn hơn \(0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mất mát bất đối xứng:&lt;/strong&gt; Giả sử dự đoán cao hơn thực tế tốn phạt gấp 3 lần dự đoán thấp hơn thực tế: \(L(\theta, \hat{\theta}) = 3(\hat{\theta} - \theta)\) nếu \(\hat{\theta} &amp;gt; \theta\) và \((\theta - \hat{\theta})\) nếu \(\hat{\theta} \le \theta\). Dùng tập mẫu hậu nghiệm để tìm \(\hat{\theta}\) tối ưu bằng tìm kiếm số.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 3.4: Hamiltonian Monte Carlo (HMC/NUTS) & Convergence Diagnostics</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter03/03_04_hmc_nuts_diagnostics/"/>
   <updated>2025-01-03T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter03/03_04_hmc_nuts_diagnostics</id>
   <content type="html">&lt;p&gt;In 100 dimensions, blind random-walk proposals almost always land outside the posterior’s high-probability &lt;strong&gt;typical set&lt;/strong&gt;, trapping Metropolis chains. Modern probabilistic programming engines—&lt;strong&gt;PyMC&lt;/strong&gt;, &lt;strong&gt;Stan&lt;/strong&gt;, and &lt;strong&gt;NumPyro&lt;/strong&gt;—solve this by borrowing classical physics: &lt;strong&gt;Hamiltonian Monte Carlo (HMC)&lt;/strong&gt; and its self-tuning extension, the &lt;strong&gt;No-U-Turn Sampler (NUTS)&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;short-video-hmc-physics-vs-random-walk-metropolis&quot;&gt;Short Video: HMC Physics vs. Random-Walk Metropolis&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:12px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/mcmc-metropolis-hmc.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Physics-driven animation comparing random-walk Metropolis rejections against a frictionless HMC particle gliding across the potential energy bowl \(U(\theta) = -\log p(\theta \mid y)\) via symplectic leapfrog integration (Vietnamese narration).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Understand HMC’s physical analogy: potential energy \(U(\theta) = -\log \tilde{p}(\theta)\), random momentum \(p\), and Hamiltonian trajectories.&lt;/li&gt;
  &lt;li&gt;Understand &lt;strong&gt;Leapfrog integration&lt;/strong&gt; and &lt;strong&gt;NUTS&lt;/strong&gt; automatic trajectory termination.&lt;/li&gt;
  &lt;li&gt;Diagnose MCMC health using &lt;strong&gt;Trace plots&lt;/strong&gt;, &lt;strong&gt;\(\hat{R}\) (Gelman–Rubin)&lt;/strong&gt;, &lt;strong&gt;ESS&lt;/strong&gt;, and &lt;strong&gt;Divergent transitions&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-physics-replaces-random-walks&quot;&gt;Key Ideas: Physics Replaces Random Walks&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hamiltonian energy:&lt;/strong&gt; Combine potential energy \(U(\theta) = -\log \tilde{p}(\theta)\) with kinetic energy \(K(p) = \frac{1}{2} p^T M^{-1} p\) to get \(H(\theta, p) = U(\theta) + K(p)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hamilton’s equations:&lt;/strong&gt;
\(\frac{d\theta}{dt} = M^{-1} p, \qquad \frac{dp}{dt} = \nabla_\theta \log \tilde{p}(\theta).\)
Using the &lt;strong&gt;gradient&lt;/strong&gt; lets HMC glide far across the typical set in a single transition with high acceptance.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Leapfrog &amp;amp; NUTS:&lt;/strong&gt; Leapfrog updates momentum by half a step, position by a full step, and momentum by half a step to conserve energy accurately. &lt;strong&gt;NUTS&lt;/strong&gt; automatically stops simulating as soon as the trajectory begins making a U-turn.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1-the-four-essential-mcmc-diagnostics&quot;&gt;1. The Four Essential MCMC Diagnostics&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter03/mcmc_diagnostics.png&quot; alt=&quot;Healthy vs Non-Converged MCMC Chains&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 3.4. Left: well-mixed chains (\(\hat{R} \approx 1.00\), high ESS). Right: drifting chains (\(\hat{R} &amp;gt; 1.2\)) that must not be trusted.&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Trace / Rank plots:&lt;/strong&gt; Multiple independently initialized chains should overlap like a “fuzzy caterpillar.”&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;\(\hat{R}\) (Gelman–Rubin):&lt;/strong&gt; Compares between-chain to within-chain variance. Modern threshold: &lt;strong&gt;\(\hat{R} &amp;lt; 1.01\)&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Effective Sample Size (ESS):&lt;/strong&gt; Accounts for autocorrelation \(\rho_k\):
\(\text{ESS} = \frac{N}{1 + 2\sum_{k=1}^{\infty} \rho_k}.\)
Aim for \(\text{ESS}_{\text{bulk}} &amp;gt; 400\) and \(\text{ESS}_{\text{tail}} &amp;gt; 400\) (higher for precise tail/HDI bounds).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Divergent transitions:&lt;/strong&gt; When posterior curvature spikes sharply (such as Neal’s funnel in Chapter 9), Leapfrog energy conservation breaks down, flagging a &lt;strong&gt;divergence&lt;/strong&gt;—a priceless geometric warning.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-running-diagnostics-in-pymc--arviz&quot;&gt;Worked Example: Running Diagnostics in PyMC &amp;amp; ArviZ&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Binomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draws&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_accept&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hdi_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sd&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;hdi_2.5%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;hdi_97.5%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ess_bulk&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ess_tail&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r_hat&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Divergences:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;diverging&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;1D Leapfrog lab:&lt;/strong&gt; Simulate 100 Leapfrog steps on \(U(\theta) = \frac{1}{2}\theta^2\) from \((\theta_0, p_0) = (0, 1)\) with \(\epsilon = 0.2\) vs. \(\epsilon = 1.9\) and plot total energy \(H(t)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Analytical ESS:&lt;/strong&gt; Compute ESS for \(N = 4000\) draws with geometric autocorrelation \(\rho_k = 0.8^k\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diagnostic sensitivity:&lt;/strong&gt; Compare &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;r_hat&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ess_bulk&lt;/code&gt;, and 95% HDI stability in the PyMC snippet above between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;draws=50&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;draws=2000&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 3.3: Monte Carlo, Metropolis–Hastings & Gibbs Sampling</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter03/03_03_monte_carlo_and_mcmc/"/>
   <updated>2025-01-03T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter03/03_03_monte_carlo_and_mcmc</id>
   <content type="html">&lt;p&gt;In a 20-parameter Bayesian model, grid approximation requires more points than atoms in the observable universe, while Laplace approximation fails on skewed or funnel-shaped posteriors. How can we draw exact asymptotic samples from \(p(\theta \mid y) = \frac{p(y \mid \theta) p(\theta)}{p(y)}\) without ever computing the normalizing integral \(p(y)\)? The breakthrough answer is &lt;strong&gt;Markov Chain Monte Carlo (MCMC)&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Understand why posterior ratios \(\frac{p(\theta^* \mid y)}{p(\theta^{(t)} \mid y)}\) cancel the intractable normalizing constant \(p(y)\).&lt;/li&gt;
  &lt;li&gt;Implement and trace the &lt;strong&gt;Metropolis–Hastings&lt;/strong&gt; proposal–acceptance algorithm.&lt;/li&gt;
  &lt;li&gt;Understand &lt;strong&gt;Gibbs Sampling&lt;/strong&gt; as a special case of Metropolis–Hastings with 100% acceptance via full conditional distributions.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-markov-chains--detailed-balance&quot;&gt;Key Ideas: Markov Chains &amp;amp; Detailed Balance&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Stationary target:&lt;/strong&gt; MCMC constructs a Markov chain \(\theta^{(0)}, \theta^{(1)}, \dots\) whose long-run stationary distribution equals the target posterior \(\pi(\theta) = p(\theta \mid y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Detailed balance:&lt;/strong&gt; If transitions satisfy \(\pi(\theta) T(\theta \to \theta&apos;) = \pi(\theta&apos;) T(\theta&apos; \to \theta)\), then \(\pi\) is guaranteed to be stationary.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;No normalizing constant needed:&lt;/strong&gt; Acceptance ratios depend only on \(\tilde{p}(\theta) = p(y \mid \theta) p(\theta)\), bypassing \(p(y)\) completely.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1-the-metropolishastings-algorithm&quot;&gt;1. The Metropolis–Hastings Algorithm&lt;/h2&gt;

&lt;p&gt;From current state \(\theta^{(t)}\):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Propose&lt;/strong&gt; \(\theta^* \sim q(\theta^* \mid \theta^{(t)})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute acceptance probability:&lt;/strong&gt;
\(\alpha(\theta^{(t)}, \theta^*) = \min\!\left(1,\ \frac{\tilde{p}(\theta^*)\, q(\theta^{(t)} \mid \theta^*)}{\tilde{p}(\theta^{(t)})\, q(\theta^* \mid \theta^{(t)})}\right).\)
For symmetric proposals (\(q(\theta^{(t)} \mid \theta^*) = q(\theta^* \mid \theta^{(t)})\)), this simplifies to the classic &lt;strong&gt;Metropolis&lt;/strong&gt; ratio \(\min(1, \tilde{p}(\theta^*)/\tilde{p}(\theta^{(t)}))\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Accept or stay:&lt;/strong&gt; Draw \(u \sim \operatorname{Uniform}(0, 1)\); if \(u &amp;lt; \alpha\) set \(\theta^{(t+1)} = \theta^*\), else stay at \(\theta^{(t)}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-3-steps-on-operatornamebeta7-4&quot;&gt;Worked Example: 3 Steps on \(\operatorname{Beta}(7, 4)\)&lt;/h3&gt;

&lt;p&gt;With unnormalized density \(\tilde{p}(\theta) = \theta^6 (1-\theta)^3\) starting at \(\theta^{(0)} = 0.40\) (\(\tilde{p} \approx 8.85 \times 10^{-4}\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; Propose \(\theta^* = 0.60\) (\(\tilde{p} \approx 2.99 \times 10^{-3}\)). Ratio \(r \approx 3.37 &amp;gt; 1 \implies\) accept, \(\theta^{(1)} = 0.60\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Propose \(\theta^* = 0.85\) (\(\tilde{p} \approx 1.27 \times 10^{-3}\)). Ratio \(r \approx 0.425\). With \(u = 0.62 &amp;gt; 0.425 \implies\) reject, \(\theta^{(2)} = 0.60\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Propose \(\theta^* = 0.70\) (\(\tilde{p} \approx 3.18 \times 10^{-3}\)). Ratio \(r \approx 1.06 &amp;gt; 1 \implies\) accept, \(\theta^{(3)} = 0.70\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter03/mh_trace_hist.png&quot; alt=&quot;Metropolis-Hastings trace and histogram for Beta(7,4)&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 3.3. Metropolis trace (left) and post-burn-in histogram matching the exact \(\operatorname{Beta}(7, 4)\) density (right).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-gibbs-sampling&quot;&gt;2. Gibbs Sampling&lt;/h2&gt;

&lt;p&gt;When full conditionals \(p(\theta_j \mid \theta_{-j}, y)\) are known in closed form, &lt;strong&gt;Gibbs sampling&lt;/strong&gt; cycles through each coordinate drawing directly from its conditional posterior. Because the proposal equals the exact conditional posterior, every move is accepted (acceptance rate = 100%). Yet under strong parameter correlation, both random-walk Metropolis and Gibbs zig-zag slowly—motivating HMC/NUTS in Lesson 3.4.&lt;/p&gt;

&lt;h3 id=&quot;interactive-compare-metropolis-gibbs-and-hmc&quot;&gt;Interactive: Compare Metropolis, Gibbs, and HMC&lt;/h3&gt;

&lt;div data-demo=&quot;mcmc-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Step-size tuning:&lt;/strong&gt; Run a 5,000-step Metropolis chain for \(\operatorname{Beta}(7, 4)\) with \(\sigma_{\text{step}} \in \{0.01, 0.25, 2.0\}\) and compare acceptance rates and trace mixing.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify detailed balance:&lt;/strong&gt; Prove that \(\pi(x) q(y \mid x) \alpha(x, y) = \pi(y) q(x \mid y) \alpha(y, x)\) for all \(x \neq y\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Correlated Gibbs:&lt;/strong&gt; Implement a Gibbs sampler for a bivariate normal with \(\rho = 0.95\) and measure its lag-1 autocorrelation.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 3.2: Laplace (Quadratic) Approximation</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter03/03_02_laplace_approximation/"/>
   <updated>2025-01-03T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter03/03_02_laplace_approximation</id>
   <content type="html">&lt;p&gt;Grid approximation works cleanly in one or two dimensions, but collapses exponentially when a model has 10 or 50 parameters. Before reaching for MCMC, statisticians—from Pierre-Simon Laplace in the 18th century to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;quap()&lt;/code&gt; in &lt;em&gt;Statistical Rethinking&lt;/em&gt;—exploit a remarkable regularity: as sample size grows, the peak of most smooth posteriors looks like a &lt;strong&gt;Gaussian bell curve&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Derive the second-order Taylor expansion of \(\log p(\theta \mid y)\) around the MAP estimate.&lt;/li&gt;
  &lt;li&gt;Compute a Laplace approximation by hand for Beta–Binomial updating and compare it with the exact posterior.&lt;/li&gt;
  &lt;li&gt;Identify when Laplace approximation fails (small samples, parameter boundaries, multimodality, funnel geometry).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-curvature-determines-uncertainty&quot;&gt;Key Ideas: Curvature Determines Uncertainty&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Log-posterior curvature:&lt;/strong&gt; Let \(\ell(\theta) = \log p(\theta \mid y)\). At the mode \(\hat{\theta}_{\text{MAP}}\), \(\ell&apos;(\hat{\theta}_{\text{MAP}}) = 0\). The negative second derivative \(H = -\ell&apos;&apos;(\hat{\theta}_{\text{MAP}})\) measures how sharply peaked the posterior is; larger curvature means smaller posterior variance \(\sigma^2 \approx 1/H\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quadratic approximation:&lt;/strong&gt;
\(\log p(\theta \mid y) \approx \log p(\hat{\theta}_{\text{MAP}} \mid y) - \frac{1}{2} H (\theta - \hat{\theta}_{\text{MAP}})^2 \implies \theta \mid y \approx \mathcal{N}\!\left(\hat{\theta}_{\text{MAP}},\ H^{-1}\right).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multivariate form:&lt;/strong&gt; For \(\boldsymbol{\theta} \in \mathbb{R}^d\), \(\boldsymbol{\Sigma} = \left[-\nabla^2 \log p(\boldsymbol{\theta} \mid y)\big\vert_{\hat{\boldsymbol{\theta}}_{\text{MAP}}}\right]^{-1}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1-worked-example-coin-flipping-by-hand&quot;&gt;1. Worked Example: Coin Flipping by Hand&lt;/h2&gt;

&lt;p&gt;Under a flat \(\operatorname{Beta}(1, 1)\) prior with \(k = 6\) heads in \(n = 9\) tosses, the exact posterior is \(\operatorname{Beta}(7, 4)\) with log-posterior (up to a constant):&lt;/p&gt;

\[\ell(\theta) = 6 \ln \theta + 3 \ln(1 - \theta).\]

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Find MAP:&lt;/strong&gt; \(\ell&apos;(\theta) = \frac{6}{\theta} - \frac{3}{1-\theta} = 0 \implies \hat{\theta}_{\text{MAP}} = \frac{2}{3} \approx 0.667\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute curvature:&lt;/strong&gt; \(H = -\ell&apos;&apos;(2/3) = \frac{6}{(2/3)^2} + \frac{3}{(1/3)^2} = 13.5 + 27 = 40.5\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gaussian approximation:&lt;/strong&gt; \(\hat{\sigma} = 1/\sqrt{40.5} \approx 0.157 \implies \theta \mid y \approx \mathcal{N}(0.667,\ 0.157^2)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter03/laplace_approximation.png&quot; alt=&quot;Laplace approximation vs exact Beta for n=9 and n=30&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 3.2. At \(n=9\) (left), the symmetric Gaussian spills slightly past \(\theta=1\); at \(n=30\) (right), the Laplace approximation closely matches the exact Beta density.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-where-laplace-approximation-breaks-down&quot;&gt;2. Where Laplace Approximation Breaks Down&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Skewness and boundaries:&lt;/strong&gt; Constrained parameters (\(\sigma &amp;gt; 0\), \(p \approx 0.01\)) can leak probability mass outside legal bounds.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multimodality:&lt;/strong&gt; A local quadratic expansion around one peak misses all other modes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Varying curvature (Neal’s Funnel):&lt;/strong&gt; In hierarchical models (Chapter 9), curvature changes drastically across space, defeating any single Hessian matrix.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;interactive-compare-exact-grid-posterior-with-smooth-shapes&quot;&gt;Interactive: Compare Exact Grid Posterior with Smooth Shapes&lt;/h3&gt;

&lt;div data-demo=&quot;grid-explainer&quot; data-lang=&quot;en&quot; data-prior=&quot;flat&quot; data-k=&quot;6&quot; data-n=&quot;9&quot; data-points=&quot;100&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gamma–Poisson by hand:&lt;/strong&gt; Given \(y_1, \dots, y_4 \sim \operatorname{Poisson}(\lambda)\) with \(\sum y_i = 20\) and prior \(\lambda \sim \operatorname{Gamma}(2, 1)\), derive \(\hat{\lambda}_{\text{MAP}}\) and the Laplace Gaussian approximation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Unconstrained transforms:&lt;/strong&gt; Explain why applying Laplace approximation to \(\phi = \operatorname{logit}(\theta)\) and transforming back is far more accurate than approximating directly on \(\theta \in (0, 1)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Numerical Hessian in Python:&lt;/strong&gt; Use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.optimize.minimize&lt;/code&gt; to compute the MAP and inverse Hessian for a 1-predictor logistic regression on 30 simulated points.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 3.1: Sampling the Imaginary & Credible Intervals (HDI vs. ETI)</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter03/03_01_sampling_the_imaginary/"/>
   <updated>2025-01-03T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter03/03_01_sampling_the_imaginary</id>
   <content type="html">&lt;p&gt;When a clinician says a positive test implies a 0.16 probability of disease, most patients struggle to calibrate that number. Reframed as natural frequencies—&lt;em&gt;out of 1,000 people who test positive, only about 160 actually have the disease&lt;/em&gt;—intuition clicks immediately. That is Richard McElreath’s &lt;strong&gt;Sampling the Imaginary&lt;/strong&gt; philosophy: instead of wrestling with intractable posterior integrals over \(p(\theta \mid y)\), draw thousands of samples \(\theta^{(1)}, \dots, \theta^{(S)}\) from the posterior and turn every probability question into &lt;strong&gt;counting&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Convert posterior expectations, interval probabilities, and nonlinear transformations into simple sample averages and counts.&lt;/li&gt;
  &lt;li&gt;Distinguish the &lt;strong&gt;Highest Density Interval (HDI / HPDI)&lt;/strong&gt; from the &lt;strong&gt;Equal-Tailed Interval (ETI)&lt;/strong&gt; on skewed posteriors.&lt;/li&gt;
  &lt;li&gt;Connect point estimates (mean, median, MAP) to their corresponding decision-theoretic loss functions.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-ideas-from-integrals-to-counting&quot;&gt;Key Ideas: From Integrals to Counting&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Monte Carlo expectation:&lt;/strong&gt; For any function \(g(\theta)\), \(\mathbb{E}[g(\theta) \mid y] = \int g(\theta) p(\theta \mid y)\,d\theta \approx \frac{1}{S}\sum_{s=1}^S g(\theta^{(s)})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Event probability by counting:&lt;/strong&gt; \(P(\theta &amp;gt; c \mid y) \approx \frac{1}{S}\sum_{s=1}^S \mathbb{I}(\theta^{(s)} &amp;gt; c)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Credible intervals:&lt;/strong&gt; Unlike frequentist confidence intervals, a 95% credible interval directly states that—given the observed data and model—the parameter lies inside the interval with 95% posterior probability.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1-hdi-vs-eti-on-skewed-distributions&quot;&gt;1. HDI vs. ETI on Skewed Distributions&lt;/h2&gt;

&lt;p&gt;Consider the right-skewed posterior \(\theta \mid y \sim \operatorname{Beta}(2, 10)\) (e.g., 1 success in 10 trials under a flat \(\operatorname{Beta}(1, 1)\) prior).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter03/hdi_vs_eti.png&quot; alt=&quot;95% ETI vs 95% HDI on skewed Beta(2,10)&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 3.1. On a skewed \(\operatorname{Beta}(2, 10)\) posterior, the 95% ETI trims 2.5% from each tail—producing a wider interval that excludes high-density values near 0—whereas the 95% HDI is the narrowest interval containing 95% of the mass.&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Equal-Tailed Interval (95% ETI):&lt;/strong&gt; The 2.5th and 97.5th percentiles give \([0.023,\ 0.413]\) (width \(0.390\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Highest Density Interval (95% HDI):&lt;/strong&gt; The &lt;strong&gt;narrowest&lt;/strong&gt; interval spanning 95% probability mass so every point inside has higher density than every point outside (Kruschke, &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt;). Here the 95% HDI is \([0.005,\ 0.365]\) (width \(0.360\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-summarizing-posterior-samples-in-python&quot;&gt;Worked Example: Summarizing Posterior Samples in Python&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20_000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;p_below_20&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;          &lt;span class=&quot;c1&quot;&gt;# ~ 0.678
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eti_95&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quantile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.025&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.975&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ceil&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.95&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;i_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;hdi_95&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s_sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;P(theta &amp;lt; 0.20) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_below_20&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, ETI = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eti_95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, HDI = (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hdi_95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hdi_95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;2-loss-functions-and-point-estimates&quot;&gt;2. Loss Functions and Point Estimates&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Loss Function&lt;/th&gt;
      &lt;th&gt;Formula \(L(\theta, \hat{\theta})\)&lt;/th&gt;
      &lt;th&gt;Bayes-Optimal Point Estimate&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Squared error&lt;/td&gt;
      &lt;td&gt;\((\theta - \hat{\theta})^2\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Posterior Mean&lt;/strong&gt; \(\mathbb{E}[\theta \mid y]\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Absolute error&lt;/td&gt;
      &lt;td&gt;\(\vert \theta - \hat{\theta} \vert\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Posterior Median&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;0–1 loss&lt;/td&gt;
      &lt;td&gt;\(\mathbb{I}(\theta \neq \hat{\theta})\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;MAP (Posterior Mode)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;interactive-confidence-vs-credible-intervals&quot;&gt;Interactive: Confidence vs. Credible Intervals&lt;/h3&gt;

&lt;div data-demo=&quot;interval-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-posterior-predictive-sampling&quot;&gt;3. Posterior Predictive Sampling&lt;/h2&gt;

&lt;p&gt;To predict new data \(\tilde{y}\) without solving \(\int p(\tilde{y} \mid \theta) p(\theta \mid y)\,d\theta\) analytically, draw \(\tilde{y}^{(s)} \sim p(\tilde{y} \mid \theta^{(s)})\) for every posterior sample \(\theta^{(s)}\). This automatically propagates both &lt;strong&gt;parameter uncertainty&lt;/strong&gt; and &lt;strong&gt;observation noise&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Analytical vs. Monte Carlo:&lt;/strong&gt; For \(\theta \mid y \sim \operatorname{Beta}(1, 5)\), compute \(P(\theta &amp;lt; 0.3 \mid y)\) analytically, then verify with \(10^4\) NumPy draws.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;HDI boundary behavior:&lt;/strong&gt; Explain why the lower endpoint of the 95% HDI for \(\operatorname{Beta}(1, 5)\) is exactly \(0\) while the 95% ETI lower endpoint is strictly positive.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Asymmetric loss:&lt;/strong&gt; Suppose overestimation costs 3× as much as underestimation. Use posterior draws from \(\operatorname{Beta}(2, 10)\) to find the optimal point estimate \(\hat{\theta}\) numerically.&lt;/li&gt;
&lt;/ol&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 7.3: Feature Selection - Chọn Predictors Quan trọng</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter07/07_03_feature_selection/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter07/07_03_feature_selection</id>
   <content type="html">&lt;p&gt;Trong các bộ dữ liệu sinh học, tài chính hay hành vi người dùng hiện đại, ta thường có hàng chục đến hàng nghìn biến dự báo nhưng chỉ một nhóm nhỏ trong đó thực sự mang tín hiệu. Chọn lọc từng biến bằng phương pháp truyền thống kiểu &lt;em&gt;stepwise regression&lt;/em&gt; (thêm/bớt theo \(p\)-value) nổi tiếng là mong manh: chỉ cần bỏ đi vài dòng dữ liệu, danh sách biến “có ý nghĩa” đã đổi khác hoàn toàn, nhất là khi các biến có đa cộng tuyến.&lt;/p&gt;

&lt;p&gt;Thống kê Bayes tiếp cận chọn lọc đặc trưng theo hướng nhân văn và trung thực hơn nhiều: thay vì ép buộc câu trả lời cứng “chọn hay bỏ”, ta tính &lt;strong&gt;xác suất hậu nghiệm chọn biến (Posterior Inclusion Probability — PIP)&lt;/strong&gt; hoặc dùng &lt;strong&gt;prior co cụm liên tục (Horseshoe)&lt;/strong&gt; để giữ trọn vẹn bất định chọn mô hình.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành bài học này, bạn sẽ hiểu &lt;strong&gt;chọn biến (feature selection)&lt;/strong&gt; như bài toán xác định những biến dự báo thực sự quan trọng trong số rất nhiều biến ứng viên. Bài học trình bày các hướng tiếp cận Bayes như tiên nghiệm Laplace, spike-and-slab và horseshoe, đồng thời so sánh với các phương pháp tần suất quen thuộc như Lasso hay chọn biến từng bước (stepwise). Mục tiêu không chỉ là biết các công cụ hiện có, mà là hiểu mỗi công cụ mã hóa giả định gì về độ thưa của mô hình và khi nào nên áp dụng từng cách tiếp cận trong dữ liệu nhiều chiều.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-không-gian-2p-mô-hình-pip-và-prior-co-cụm-thưa&quot;&gt;Kiến thức cần nhớ: Không gian \(2^p\) mô hình, PIP và Prior Co cụm Thưa&lt;/h2&gt;

&lt;p&gt;Để nắm chắc chiến lược chọn lọc biến Bayes, hãy kết nối ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Vấn đề tổ hợp \(2^p\) mô hình &amp;amp; Bất ổn của Stepwise:&lt;/strong&gt; Với \(p\) biến dự báo, có tới \(2^p\) tập con mô hình khả dĩ. Các thuật toán tham lam chọn ra đúng một tập con duy nhất thường đánh giá quá cao độ chắc chắn của các hệ số còn lại (&lt;em&gt;post-selection inference bias&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Spike-and-Slab &amp;amp; Xác suất chọn biến (PIP):&lt;/strong&gt; Mô hình hóa mỗi hệ số qua biến chỉ thị \(\gamma_j \in \{0, 1\}\): nếu \(\gamma_j = 0\) hệ số nằm ở đỉnh nhọn tại 0 (&lt;em&gt;spike&lt;/em&gt;); nếu \(\gamma_j = 1\) hệ số lấy từ phân phối rộng (&lt;em&gt;slab&lt;/em&gt;). Trung bình hậu nghiệm \(\mathrm{PIP}_j = P(\gamma_j = 1 \mid y)\) cho biết xác suất biến \(j\) thuộc mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Co cụm liên tục (Horseshoe) &amp;amp; Lựa chọn theo Dự báo (Projection Predictive):&lt;/strong&gt; Trong thực hành với PyMC/Stan, lấy mẫu biến rời rạc \(\gamma_j\) có thể khó hội tụ; prior Horseshoe (liên tục, thân thiện với HMC/NUTS) và phương pháp &lt;em&gt;projection predictive&lt;/em&gt; (Piironen &amp;amp; Vehtari) là lựa chọn hiện đại vừa ổn định vừa đạt độ chính xác dự báo cao.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-bài-toán-khi-có-quá-nhiều-biến-dự-báo&quot;&gt;Giới thiệu: Bài toán khi có quá nhiều biến dự báo&lt;/h2&gt;

&lt;p&gt;Giả sử bạn có 100 biến dự báo tiềm năng nhưng chỉ khoảng 5 biến trong số đó thực sự mang tín hiệu. Nếu giữ toàn bộ biến, mô hình dễ bị quá khớp; nếu thử mọi tổ hợp có thể, chi phí tính toán sẽ bùng nổ vì số mô hình lên tới \(2^{100}\); còn nếu kiểm định từng biến riêng lẻ, ta lại đối mặt với nguy cơ &lt;strong&gt;phát hiện sai (false discoveries)&lt;/strong&gt; do kiểm định lặp nhiều lần (multiple testing). Vì vậy, mục tiêu của chọn biến không chỉ là làm mô hình gọn hơn, mà là nhận diện một cách có nguyên tắc các biến thực sự liên quan trong khi vẫn kiểm soát được độ bất định và chi phí tính toán.&lt;/p&gt;

&lt;h2 id=&quot;1-các-phương-pháp-tần-suất-frequentist-approaches&quot;&gt;1. Các phương pháp tần suất (Frequentist Approaches)&lt;/h2&gt;

&lt;h3 id=&quot;11-lasso-điều-chuẩn-l1&quot;&gt;1.1. Lasso (Điều chuẩn L1)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Lasso&lt;/strong&gt; có khả năng đưa một số hệ số về &lt;strong&gt;đúng bằng 0&lt;/strong&gt;, nhờ đó thực hiện chọn biến tự động.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/lasso_feature_selection.png&quot; alt=&quot;Lasso Feature Selection&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ví dụ trong hình sử dụng một tập dữ liệu gồm 20 đặc trưng, trong đó chỉ 5 đặc trưng đầu có hệ số thật khác 0. Khi \(\alpha\) còn rất nhỏ như 0.001 hoặc 0.01, điều chuẩn quá yếu nên mô hình vẫn giữ khoảng 13 đặc trưng, tức còn nhiều biến nhiễu lọt vào. Khi tăng lên mức trung bình như 0.1, các hệ số bắt đầu co mạnh hơn về 0 nhưng số biến được giữ lại vẫn còn lớn. Chỉ khi \(\alpha\) đủ mạnh (chẳng hạn 0.5), hiệu ứng thưa mới thể hiện rõ: nhiều hệ số bị ép về đúng 0 và số đặc trưng được chọn giảm xuống. Như vậy, Lasso chọn biến bằng cách triệt tiêu trực tiếp một số hệ số, và mức độ &lt;strong&gt;thưa (sparsity)&lt;/strong&gt; tăng lên khi cường độ điều chuẩn mạnh hơn.&lt;/p&gt;

&lt;h3 id=&quot;12-chọn-alpha-bằng-kiểm-định-chéo-cross-validation&quot;&gt;1.2. Chọn \(\alpha\) bằng kiểm định chéo (Cross-Validation)&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/lasso_cv_regularization_path.png&quot; alt=&quot;Lasso CV and Regularization Path&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Kết quả kiểm định chéo trong ví dụ này chọn \(\alpha=1.0\) làm mức điều chuẩn tối ưu theo năng lực dự báo ngoài mẫu. Ở mức này, mô hình giữ lại 7 đặc trưng — nhiều hơn một chút so với 5 đặc trưng thật sự liên quan nhưng đã khá sát với cấu trúc thưa của dữ liệu. Đường điều chuẩn (regularization path) ở hình bên phải bổ sung một trực giác quan trọng: khi \(\alpha\) nhỏ, phần lớn hệ số khác 0 và có độ lớn đáng kể; khi \(\alpha\) tăng dần, các hệ số co về 0 với tốc độ khác nhau, và những đặc trưng mang tín hiệu thật thường tồn tại lâu hơn các biến nhiễu. Nhờ vậy, kiểm định chéo không chỉ chọn mức điều chuẩn tối ưu mà còn cho thấy trình tự từng biến rời khỏi mô hình.&lt;/p&gt;

&lt;h2 id=&quot;2-các-phương-pháp-bayes-bayesian-approaches&quot;&gt;2. Các phương pháp Bayes (Bayesian Approaches)&lt;/h2&gt;

&lt;h3 id=&quot;21-tiên-nghiệm-laplace-bayesian-lasso&quot;&gt;2.1. Tiên nghiệm Laplace (Bayesian Lasso)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Tiên nghiệm Laplace&lt;/strong&gt; là phiên bản tương ứng trong thống kê Bayes của hồi quy Lasso:&lt;/p&gt;

\[\beta_j \sim \text{Laplace}(0, b)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Bayesian Lasso
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bayesian_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Laplace priors
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Laplace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Laplace!
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;trace_lasso&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                           &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Extract coefficients
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_lasso&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Coefficients
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_coef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bayesian Lasso&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
           &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Feature Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BAYESIAN LASSO&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Laplace Prior)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Posterior distributions (first 6 features)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient Value&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR DISTRIBUTIONS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;First 6 features&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;22-tiên-nghiệm-horseshoe-horseshoe-prior&quot;&gt;2.2. Tiên nghiệm Horseshoe (Horseshoe Prior)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Tiên nghiệm Horseshoe&lt;/strong&gt; linh hoạt hơn tiên nghiệm Laplace vì nó vừa cho phép một số hệ số thực sự lớn tồn tại nhờ phần đuôi dày, vừa co rất mạnh các hệ số nhỏ về gần 0. Nhờ cơ chế đồng thời giữ lại tín hiệu mạnh và nén chặt nhiễu yếu, horseshoe trở thành lựa chọn rất hiệu quả trong các bài toán có tín hiệu thưa.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Horseshoe prior
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;horseshoe_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Horseshoe prior
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;tau&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfCauchy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;tau&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Global shrinkage
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;lambda_j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfCauchy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lambda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Local shrinkage
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tau&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;trace_horseshoe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Extract
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_horseshoe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compare all methods
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;methods&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_coef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lasso (Freq.)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lasso_cv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coef_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bayesian Lasso&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Horseshoe&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;coef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;methods&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;coef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
              &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Feature Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
                                 &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Non-zero: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;FEATURE SELECTION COMPARISON&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True non-zero: 5&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lasso: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lasso_cv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coef_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; selected&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bayesian Lasso: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; selected&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Horseshoe: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; selected&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;thử-nghiệm-so-sánh-cơ-chế-co-rút-của-gaussian-laplace-và-horseshoe&quot;&gt;Thử nghiệm: So sánh cơ chế co rút của Gaussian, Laplace và Horseshoe&lt;/h3&gt;

&lt;p&gt;Với 50 hệ số nhưng chỉ 5 hệ số thật sự lớn, hãy so sánh trung bình hậu nghiệm và đường cong co rút của từng loại tiên nghiệm.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;horseshoe-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;video-ngắn-chọn-biến-bằng-horseshoe-prior--pip-ép-nhiễu-về-0--giữ-tín-hiệu-mạnh&quot;&gt;Video ngắn: Chọn Biến bằng Horseshoe Prior &amp;amp; PIP: Ép Nhiễu về 0 — Giữ Tín hiệu Mạnh&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch07-03a-horseshoe-vs-ridge-pip.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 19 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): so sánh trực tiếp MLE thô, Ridge (co đều làm tụt cả tín hiệu thật) và Horseshoe Prior ép sạch 4 biến nhiễu về 0.&lt;/p&gt;

&lt;h2 id=&quot;3-xác-suất-hậu-nghiệm-chọn-biến-posterior-inclusion-probabilities&quot;&gt;3. Xác suất hậu nghiệm chọn biến (Posterior Inclusion Probabilities)&lt;/h2&gt;

&lt;p&gt;Ưu điểm quan trọng của cách tiếp cận Bayes là không chỉ trả về một danh sách biến được chọn, mà còn định lượng được độ bất định của chính việc lựa chọn đó. &lt;strong&gt;Xác suất hậu nghiệm chọn biến (Posterior Inclusion Probability — PIP)&lt;/strong&gt; đo xác suất hậu nghiệm để độ lớn của một hệ số vượt qua một ngưỡng thực dụng khác 0, cho phép ta đánh giá mức độ chắc chắn về tầm quan trọng của từng biến thay vì chỉ đưa ra quyết định nhị phân chọn hoặc bỏ.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Compute PIPs
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples_horseshoe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# PIP = proportion of posterior samples where |β| &amp;gt; threshold
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pips&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# PIPs
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pips&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Threshold = 0.5&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Feature Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior Inclusion Probability&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR INCLUSION PROBABILITIES&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
                 &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;P(|β| &amp;gt; 0.1 &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\\&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mid data)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Coefficient vs PIP
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_samples_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pips&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pips&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;va&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior Inclusion Probability&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;COEFFICIENT vs PIP&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Large |β| → High PIP&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;FEATURES WITH HIGH PIP (&amp;gt; 0.5)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;selected&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pips&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Selected features: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;selected&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True relevant: [0, 1, 2, 3, 4]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;→ Bayesian approach quantifies uncertainty!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;4-nghiên-cứu-tình-huống-ứng-dụng-phần-3-độ-ổn-định-chọn-biến-và-rủi-ro-diễn-giải&quot;&gt;4. Nghiên cứu tình huống ứng dụng (Phần 3): Độ ổn định chọn biến và rủi ro diễn giải&lt;/h2&gt;

&lt;p&gt;Trong bài toán thực tế, một đặc trưng được chọn trong một lần chạy đơn lẻ chưa đủ để khẳng định nó thực sự quan trọng. Ta cần kiểm tra &lt;strong&gt;độ ổn định của việc chọn biến (stability selection)&lt;/strong&gt; qua nhiều lần lấy mẫu lại (resampling).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;ridge_fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;eye&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;solve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;bootstrap_stability&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_boot&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;picks&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_boot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_boot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;integers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;Xb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;beta_b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;ridge_fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Xb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;picks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;picks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# selection frequency
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;stability&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;bootstrap_stability&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_lambda&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Quy tac don gian: chon bien co tan suat xuat hien &amp;gt;= 0.7
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stable_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stability&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Stable features (freq &amp;gt;= 0.7):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stable_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;41-phân-tầng-ngưỡng-theo-độ-bất-định&quot;&gt;4.1. Phân tầng ngưỡng theo độ bất định&lt;/h3&gt;

&lt;p&gt;Thay vì dùng một ngưỡng cắt cứng duy nhất, nên báo cáo kết quả theo nhiều mức độ tin cậy:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mức cao (\(\ge 0.9\))&lt;/strong&gt;: bằng chứng rất mạnh, phù hợp để đưa vào mô hình diễn giải chính.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mức trung bình (\(0.7 - 0.9\))&lt;/strong&gt;: khá ổn định, cần đối chiếu thêm với kiến thức chuyên môn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mức thấp (\(&amp;lt; 0.7\))&lt;/strong&gt;: chưa ổn định, chỉ nên xem là đặc trưng dự phòng.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Với mô hình Bayes, ta có thể kết hợp thêm ngưỡng PIP (ví dụ \(\text{PIP} \ge 0.8\)) để trình bày minh bạch độ bất định của việc chọn biến.&lt;/p&gt;

&lt;h3 id=&quot;42-rủi-ro-diễn-giải-trong-học-máy&quot;&gt;4.2. Rủi ro diễn giải trong học máy&lt;/h3&gt;

&lt;p&gt;Ngay cả khi một đặc trưng được chọn ổn định, việc diễn giải vẫn tiềm ẩn nhiều rủi ro:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đa cộng tuyến (Collinearity)&lt;/strong&gt;: đặc trưng được chọn có thể chỉ đại diện cho một cụm biến tương quan với nhau, không nhất thiết là nguyên nhân trực tiếp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thiên lệch biến đại diện (Proxy bias)&lt;/strong&gt;: đặc trưng có thể vô tình đóng vai trò biến thay thế cho các thuộc tính nhạy cảm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trôi dữ liệu (Data drift)&lt;/strong&gt;: tần suất được chọn có thể thay đổi theo thời gian khi phân phối dữ liệu biến động.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng cách với khả năng hành động (Actionability gap)&lt;/strong&gt;: một đặc trưng quan trọng về mặt dự báo chưa chắc đã can thiệp được trong vận hành thực tế.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Điểm kiểm tra quyết định 3 (kết thúc nghiên cứu tình huống)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Báo cáo đồng thời hiệu năng ngoài mẫu, độ bất định chọn biến (PIP/stability) và các cảnh báo diễn giải.&lt;/li&gt;
  &lt;li&gt;Chỉ chốt danh sách đặc trưng phục vụ hành động sau khi đã kiểm tra đầy đủ cả ba lớp trên.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nếu muốn tái lập toàn bộ nghiên cứu tình huống xuyên suốt các bài 7.1 đến 7.3, bạn có thể chạy script:&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;python img/chapter_img/chapter07/generate_applied_ml_workflow_tradeoffs.py&lt;/code&gt;&lt;/p&gt;

&lt;h2 id=&quot;5-khi-nào-nên-dùng-phương-pháp-nào&quot;&gt;5. Khi nào nên dùng phương pháp nào?&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Phương pháp&lt;/th&gt;
      &lt;th&gt;Ưu điểm&lt;/th&gt;
      &lt;th&gt;Hạn chế&lt;/th&gt;
      &lt;th&gt;Khi nào nên dùng&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Lasso&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Nhanh, tạo lời giải thưa&lt;/td&gt;
      &lt;td&gt;Không định lượng độ bất định&lt;/td&gt;
      &lt;td&gt;Cỡ mẫu lớn, cần kết quả nhanh&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Bayesian Lasso&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Có độ bất định, linh hoạt&lt;/td&gt;
      &lt;td&gt;Chậm hơn&lt;/td&gt;
      &lt;td&gt;Cần định lượng độ bất định của hệ số&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Horseshoe&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Đuôi dày, co rút thích nghi linh hoạt&lt;/td&gt;
      &lt;td&gt;Phức tạp hơn&lt;/td&gt;
      &lt;td&gt;Giả định tín hiệu có độ thưa mạnh&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Spike-and-Slab&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Chọn biến tường minh&lt;/td&gt;
      &lt;td&gt;Rất chậm&lt;/td&gt;
      &lt;td&gt;Số biến \(p\) nhỏ, cần xác suất chọn biến trực tiếp&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;Chọn biến (feature selection) nhằm nhận diện các biến dự báo thực sự liên quan khi số biến ứng viên lớn và nguy cơ quá khớp cao. Lasso sử dụng phạt L1 để tạo lời giải thưa, Bayesian Lasso biểu diễn cùng ý tưởng qua tiên nghiệm Laplace, còn tiên nghiệm horseshoe mang lại cơ chế co rút chọn lọc hơn khi chỉ có một số ít tín hiệu mạnh nằm lẫn giữa nhiều biến nhiễu. Quan trọng hơn, hướng tiếp cận Bayes cung cấp khả năng &lt;strong&gt;định lượng độ bất định&lt;/strong&gt; cho quá trình chọn biến (chẳng hạn qua Posterior Inclusion Probabilities), thay vì chỉ trả về một danh sách cố định.&lt;/p&gt;

&lt;p&gt;Chọn biến không nên bị xem như thao tác lọc cơ học, mà là một phần của quá trình suy luận về cấu trúc tín hiệu trong dữ liệu.&lt;/p&gt;

&lt;p&gt;Kết thúc Chương 07 về điều chuẩn (Regularization), đánh đổi độ lệch – phương sai (Bias-Variance) và chọn biến (Feature Selection).&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tính-xác-suất-chọn-biến-pip-từ-trọng-số-hậu-nghiệm-của-không-gian-mô-hình&quot;&gt;Giải thích: Tính Xác suất chọn biến (PIP) từ trọng số hậu nghiệm của không gian mô hình&lt;/h2&gt;

&lt;p&gt;Khi nhiều mô hình con cùng giải thích dữ liệu gần tương đương nhau (đặc biệt khi hai biến dự báo tương quan mạnh), PIP giúp ta không đưa ra kết luận cực đoan. Hãy đi qua 3 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính xác suất hậu nghiệm \(P(M_k \mid y)\) cho từng mô hình con \(M_k\)&lt;/strong&gt; (tổng các xác suất mô hình bằng 1).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Với mỗi biến \(X_j\), cộng xác suất hậu nghiệm của tất cả các mô hình có chứa \(X_j\):&lt;/strong&gt;
\(\mathrm{PIP}_j = \sum_{k:\; X_j \in M_k} P(M_k \mid y).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diễn giải theo ngưỡng hành động:&lt;/strong&gt; \(\mathrm{PIP}_j &amp;gt; 0.5\) tương ứng mô hình xác suất trung vị (&lt;em&gt;median probability model&lt;/em&gt;); nếu hai biến tương quan cao cùng chia nhau \(\mathrm{PIP} \approx 0.45\) mỗi biến, tổng xác suất có ít nhất một trong hai biến lại rất cao (\(\approx 0.90\)).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-tính-pip-khi-x_2-và-x_3-đa-cộng-tuyến&quot;&gt;Ví dụ tính toán làm từng bước: Tính PIP khi \(X_2\) và \(X_3\) đa cộng tuyến&lt;/h3&gt;

&lt;p&gt;Giả sử có 3 biến dự báo \(X_1, X_2, X_3\) (trong đó \(X_2\) và \(X_3\) tương quan mạnh với nhau). Ta xét 4 mô hình có xác suất hậu nghiệm đáng kể:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Mô hình \(M_k\)&lt;/th&gt;
      &lt;th&gt;Các biến có mặt&lt;/th&gt;
      &lt;th&gt;Xác suất hậu nghiệm \(P(M_k \vert y)\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(M_1\)&lt;/td&gt;
      &lt;td&gt;\(\{X_1, X_2\}\)&lt;/td&gt;
      &lt;td&gt;\(0.45\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(M_2\)&lt;/td&gt;
      &lt;td&gt;\(\{X_1, X_3\}\)&lt;/td&gt;
      &lt;td&gt;\(0.40\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(M_3\)&lt;/td&gt;
      &lt;td&gt;\(\{X_1, X_2, X_3\}\)&lt;/td&gt;
      &lt;td&gt;\(0.10\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(M_4\)&lt;/td&gt;
      &lt;td&gt;\(\{X_1\}\)&lt;/td&gt;
      &lt;td&gt;\(0.05\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Tổng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(1.00\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Tính tay PIP cho từng biến:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathrm{PIP}(X_1) = 0.45 + 0.40 + 0.10 + 0.05 = 1.00\) (chắc chắn quan trọng).&lt;/li&gt;
  &lt;li&gt;\(\mathrm{PIP}(X_2) = 0.45 + 0.10 = 0.55\).&lt;/li&gt;
  &lt;li&gt;\(\mathrm{PIP}(X_3) = 0.40 + 0.10 = 0.50\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nếu chỉ chọn mô hình đỉnh \(M_1\), ta sẽ vứt bỏ \(X_3\) và tuyên bố nhầm rằng \(X_3\) “không liên quan”. Bảng PIP cho thấy đúng sự thật: dữ liệu cần \(X_1\) cùng với &lt;em&gt;ít nhất một trong hai&lt;/em&gt; biến \(X_2\) hoặc \(X_3\) (xác suất \(0.45 + 0.40 + 0.10 = 0.95\)), nhưng không đủ để phân định rạch ròi giữa hai biến tương quan này.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhầm rằng \(\mathrm{PIP}_j = 0.50\) nghĩa là biến \(X_j\) vô dụng. Khi có đa cộng tuyến, xác suất bị chia đôi giữa các biến thay thế nhau — cần kiểm tra cả xác suất hậu nghiệm đồng thời của cụm biến.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Trong ví dụ trên, xác suất mô hình chứa đồng thời cả hai biến tương quan \(X_2\) và \(X_3\) chỉ là \(P(M_3 \mid y) = 0.10\) — phản ánh cơ chế “dao cạo Occam” tự động phạt độ phức tạp thừa của suy diễn Bayes.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NGf0voTMlcs&quot;&gt;Regularization Part 2: Lasso (L1) Regression&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giải thích vì sao phạt L1 có thể đưa một số hệ số về đúng 0 để chọn biến.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Mv6MSIVKEIc&quot;&gt;Lecture 31 Bayesian Regression and Variable Selection (Part A)&lt;/a&gt; — Nicholas Zabaras, English. Trình bày hồi quy Bayes và bài toán chọn biến bằng các phân phối tiên nghiệm co rút khi có nhiều biến dự báo.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuhvfvY8ISc&quot;&gt;Regularized Horseshoe - Aki Vehtari&lt;/a&gt; — Stan, English. Giới thiệu tiên nghiệm regularized horseshoe cho bài toán tín hiệu thưa trong thống kê Bayes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 1&lt;/strong&gt;: Sinh dữ liệu có cấu trúc thưa, so sánh Lasso, Bayesian Lasso và Horseshoe để xem phương pháp nào khôi phục các đặc trưng thật tốt nhất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 2&lt;/strong&gt;: Tính xác suất hậu nghiệm chọn biến (PIP) và kiểm tra tập biến được chọn thay đổi ra sao ở các ngưỡng 0.5, 0.7 và 0.9.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 3&lt;/strong&gt;: Vẽ đường điều chuẩn (regularization path) của các hệ số theo \(\lambda\) và quan sát thời điểm từng đặc trưng đi vào hoặc rời khỏi mô hình.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 4&lt;/strong&gt;: Thực hiện chọn biến trên một tập dữ liệu thực nhiều chiều và diễn giải các đặc trưng được chọn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 5&lt;/strong&gt;: So sánh thời gian tính toán giữa Lasso và các phương pháp Bayes, đồng thời phân tích những đánh đổi đi kèm.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Carvalho, C. M., et al. (2010).&lt;/strong&gt; “The horseshoe estimator for sparse signals.” &lt;em&gt;Biometrika&lt;/em&gt;, 97(2), 465-480.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Piironen, J., &amp;amp; Vehtari, A. (2017).&lt;/strong&gt; “Sparsity information and regularization in the horseshoe and other shrinkage priors.” &lt;em&gt;Electronic Journal of Statistics&lt;/em&gt;, 11(2), 5018-5051.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., et al. (2020).&lt;/strong&gt; &lt;em&gt;Regression and Other Stories&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 11: Assumptions, diagnostics, and model evaluation&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Chương tiếp theo: &lt;a href=&quot;/contents/vi/chapter08/&quot;&gt;Chapter 08: Model Comparison&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 7.2: Bias-Variance Tradeoff - Cốt lõi của Model Selection</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter07/07_02_bias_variance_tradeoff/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter07/07_02_bias_variance_tradeoff</id>
   <content type="html">&lt;p&gt;Một mô hình quá đơn giản bỏ sót quy luật thật (dưới khớp — &lt;em&gt;underfitting&lt;/em&gt;); một mô hình quá phức tạp học thuộc luôn cả nhiễu ngẫu nhiên của tập huấn luyện (quá khớp — &lt;em&gt;overfitting&lt;/em&gt;). Giữa hai thái cực ấy là một định luật toán học chi phối mọi bài toán dự báo từ hồi quy tuyến tính đến mạng nơ-ron: &lt;strong&gt;đánh đổi độ chệch – phương sai (bias–variance tradeoff)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Bài học này không chỉ chứng minh phép phân rã sai số dự báo thành ba thành phần bất biến, mà còn giải thích cách thống kê Bayes tiếp cận sự đánh đổi này bằng tích phân trên hậu nghiệm (&lt;em&gt;Bayesian model averaging&lt;/em&gt;) và đường cong học (&lt;em&gt;learning curves&lt;/em&gt;).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành bài học này, bạn sẽ hiểu rõ &lt;strong&gt;sự đánh đổi giữa độ lệch và phương sai (bias-variance tradeoff)&lt;/strong&gt; — một trong những khái niệm nền tảng của học máy và thống kê. Bài học giải thích vì sao mô hình quá đơn giản thường có &lt;strong&gt;độ lệch cao (high bias)&lt;/strong&gt;, vì sao mô hình quá phức tạp thường có &lt;strong&gt;phương sai cao (high variance)&lt;/strong&gt;, và vì sao mục tiêu của chọn mô hình không phải là đẩy một thành phần xuống thấp nhất có thể, mà là tìm điểm cân bằng giúp tổng sai số dự báo nhỏ nhất. Đây là cơ sở trực tiếp để hiểu điều chuẩn, quá khớp và logic của việc lựa chọn mô hình.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-phân-rã-sai-số-dự-báo-đường-cong-học-và-cách-giải-của-bayes&quot;&gt;Kiến thức cần nhớ: Phân rã Sai số Dự báo, Đường cong Học và Cách giải của Bayes&lt;/h2&gt;

&lt;p&gt;Bức tranh tổng thể về độ phức tạp mô hình đứng trên ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân rã sai số ngoài mẫu (Expected Prediction Error):&lt;/strong&gt; Tại một điểm mới \(x_0\), sai số bình phương kỳ vọng luôn tách thành: \(\mathbb{E}[(y_0 - \hat f(x_0))^2] = \mathrm{Bias}(\hat f(x_0))^2 + \mathrm{Var}(\hat f(x_0)) + \sigma_\varepsilon^2\). Thành phần cuối \(\sigma_\varepsilon^2\) là &lt;strong&gt;nhiễu không thể khử (irreducible noise)&lt;/strong&gt; — không mô hình nào vượt qua được trần này.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chẩn đoán bằng Đường cong học (Learning Curves):&lt;/strong&gt; Vẽ sai số tập huấn luyện và tập kiểm định theo cỡ mẫu \(n\) giúp phân biệt tức thì hai bệnh: hai đường hội tụ sát nhau ở mức lỗi cao là &lt;strong&gt;High Bias&lt;/strong&gt; (cần mô hình giàu biểu diễn hơn); hai đường cách xa nhau với lỗi huấn luyện rất thấp là &lt;strong&gt;High Variance&lt;/strong&gt; (cần thêm dữ liệu hoặc điều chuẩn mạnh hơn).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cách tiếp cận của Bayes:&lt;/strong&gt; Thay vì chọn một điểm tham số cố định (dễ có phương sai cao), dự báo hậu nghiệm lấy trung bình có trọng số trên toàn bộ phân phối hậu nghiệm \(\mathbb{E}_{\theta \mid y}[f(x_0; \theta)]\) — tự động giảm phương sai nhờ hiệu ứng tổ hợp (&lt;em&gt;ensembling&lt;/em&gt;) kết hợp điều chuẩn từ prior.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-hai-nguồn-sai-số&quot;&gt;Giới thiệu: Hai nguồn sai số&lt;/h2&gt;

&lt;p&gt;Khi một mô hình dự đoán sai, sai số đó thường không bắt nguồn từ một nguyên nhân duy nhất. Một phần sai số xuất phát từ việc mô hình quá đơn giản nên bỏ sót cấu trúc thật của dữ liệu — đó là &lt;strong&gt;độ lệch (bias)&lt;/strong&gt;. Phần khác xuất phát từ việc mô hình quá nhạy với dữ liệu huấn luyện, khiến chỉ cần thay đổi mẫu một chút là dự đoán đã dao động mạnh — đó là &lt;strong&gt;phương sai (variance)&lt;/strong&gt;. Hai thành phần này thường biến thiên ngược chiều: giảm độ lệch thường làm phương sai tăng, còn ép phương sai xuống quá mạnh lại làm độ lệch tăng lên.&lt;/p&gt;

&lt;h2 id=&quot;1-định-nghĩa-độ-lệch-và-phương-sai&quot;&gt;1. Định nghĩa độ lệch và phương sai&lt;/h2&gt;

&lt;h3 id=&quot;11-định-nghĩa-toán-học&quot;&gt;1.1. Định nghĩa toán học&lt;/h3&gt;

&lt;p&gt;Giả sử ta huấn luyện mô hình nhiều lần trên các tập dữ liệu khác nhau được lấy từ cùng một phân phối.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Độ lệch (Bias)&lt;/strong&gt;: Sai lệch giữa &lt;strong&gt;dự đoán trung bình&lt;/strong&gt; và &lt;strong&gt;giá trị thật&lt;/strong&gt;:
\(\text{Bias}[\hat{f}(x)] = \mathbb{E}[\hat{f}(x)] - f(x)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phương sai (Variance)&lt;/strong&gt;: Mức độ dao động của các dự đoán giữa các tập dữ liệu khác nhau:
\(\text{Variance}[\hat{f}(x)] = \mathbb{E}[(\hat{f}(x) - \mathbb{E}[\hat{f}(x)])^2]\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tổng sai số&lt;/strong&gt;:
\(\mathbb{E}[(y - \hat{f}(x))^2] = \text{Bias}^2 + \text{Variance} + \text{Irreducible Error}\)&lt;/p&gt;

&lt;h3 id=&quot;12-trực-giác-hình-học&quot;&gt;1.2. Trực giác hình học&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/bias_variance_demonstration.png&quot; alt=&quot;Bias-Variance Demonstration&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Hình minh họa làm rõ trực giác này. Với mô hình bậc 1, các đường khớp từ nhiều tập dữ liệu khá gần nhau (phương sai thấp), nhưng hầu hết đều lệch xa quy luật thật (độ lệch cao) — đây là trạng thái thiếu khớp điển hình. Với mô hình bậc 3, độ linh hoạt vừa đủ để bám sát quy luật thật mà chưa dao động mạnh giữa các mẫu, nên độ lệch giảm trong khi phương sai vẫn trong tầm kiểm soát — đây là vùng cân bằng tốt của sự đánh đổi. Với mô hình bậc 10, đường trung bình có thể gần quy luật thật hơn (độ lệch thấp hơn), nhưng từng mô hình riêng lẻ lại dao động mạnh theo mẫu huấn luyện (phương sai tăng vọt). Quan sát 50 tập huấn luyện như 50 lần lặp của cùng một bài toán giúp ta hình dung trực tiếp phương sai là mức độ dao động của dự đoán khi dữ liệu thay đổi.&lt;/p&gt;

&lt;h2 id=&quot;2-phân-rã-sai-số-mse--bias--variance--nhiễu&quot;&gt;2. Phân rã sai số: MSE = Bias² + Variance + Nhiễu&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/mse_decomposition.png&quot; alt=&quot;MSE Decomposition&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Nhìn vào phép phân rã MSE, ta thấy ngay vì sao không thể chọn mô hình dựa trên một thành phần đơn lẻ. Ở vùng độ phức tạp thấp (như bậc 1 hoặc 2), thành phần \(\text{Bias}^2\) lớn vì mô hình quá đơn giản để mô tả dữ liệu, dù phương sai khá thấp. Khi độ phức tạp tăng lên vùng trung gian, hai thành phần cân bằng hơn và tổng MSE đạt mức nhỏ nhất. Nếu tiếp tục tăng độ phức tạp, độ lệch có thể giảm thêm chút ít nhưng phương sai tăng rất mạnh, kéo MSE tăng trở lại. Biểu đồ xếp chồng ở bên phải cho thấy rõ mục tiêu không phải tối thiểu hóa riêng độ lệch hay riêng phương sai, mà là tối thiểu hóa tổng sai số dự báo.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-độ-lệch-phương-sai-và-tổng-sai-số-theo-độ-phức-tạp&quot;&gt;Thử nghiệm: Độ lệch, phương sai và tổng sai số theo độ phức tạp&lt;/h3&gt;

&lt;p&gt;Lặp trên 100 tập dữ liệu cho mỗi bậc đa thức để quan sát \(\text{Bias}^2\) giảm, phương sai tăng, tổng sai số có dạng chữ U, và cách tiên nghiệm chặt (Ridge) nén phương sai.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;biasvar-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-điều-chuẩn-và-sự-đánh-đổi-độ-lệch--phương-sai&quot;&gt;3. Điều chuẩn và sự đánh đổi độ lệch – phương sai&lt;/h2&gt;

&lt;p&gt;Điều chuẩn đóng vai trò là nút điều chỉnh sự đánh đổi này. Khi điều chuẩn yếu (\(\lambda\) nhỏ), mô hình linh hoạt hơn nên độ lệch thường thấp nhưng phương sai cao. Khi điều chuẩn mạnh (\(\lambda\) lớn), mô hình bị ràng buộc đơn giản hơn nên phương sai giảm, đổi lại độ lệch tăng lên.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/regularization_bias_variance.png&quot; alt=&quot;Regularization Bias-Variance&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ví dụ với đa thức bậc 10 minh họa rõ điểm này. Khi \(\lambda=0.001\), điều chuẩn quá yếu nên mô hình dao động mạnh, phương sai rất lớn và quá khớp rõ rệt. Khi tăng dần lên \(0.1\) rồi \(1\), phương sai giảm đáng kể và mô hình bước vào vùng cân bằng tốt hơn. Nếu tiếp tục tăng lên \(10\) hay \(100\), mô hình bị bó quá chặt, đường dự đoán trở nên gần như phẳng, phương sai thấp nhưng độ lệch tăng cao — tức quay trở lại vùng thiếu khớp. Như vậy, \(\lambda\) không phải càng lớn càng tốt, mà cần được chọn sao cho độ lệch và phương sai cân bằng tốt nhất cho mục tiêu dự báo.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-đánh-đổi-bias--variance-đường-cong-chữ-u--điểm-vàng-tối-ưu&quot;&gt;Video ngắn: Đánh đổi Bias – Variance: Đường cong Chữ U &amp;amp; Điểm Vàng Tối ưu&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch07-02a-bias-variance-u-curve.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 22 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): trượt độ phức tạp mô hình từ thiếu khớp sang quá khớp để theo dõi Bias² giảm, Variance tăng vọt và điểm cân bằng tổng sai số nhỏ nhất.&lt;/p&gt;

&lt;h2 id=&quot;4-góc-nhìn-bayes&quot;&gt;4. Góc nhìn Bayes&lt;/h2&gt;

&lt;p&gt;Trong thống kê Bayes, vai trò của điều chuẩn chuyển thành vai trò của &lt;strong&gt;độ mạnh tiên nghiệm (prior strength)&lt;/strong&gt;. Tiên nghiệm yếu để dữ liệu quyết định nhiều hơn nên mô hình linh hoạt hơn nhưng cũng dễ dao động hơn; tiên nghiệm mạnh ràng buộc mô hình chặt hơn giúp giảm phương sai, nhưng có thể làm tăng độ lệch nếu tiên nghiệm quá cứng.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;true_function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x_data_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_data_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Different prior strengths
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior_sds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ravel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_sd&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior_sds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_sd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Varying prior strength
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data_z&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_data_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                         &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Posterior predictions
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;alpha_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Plot
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x_plot_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_plot_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_plot_z&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_plot&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_plot_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.05&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zorder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zorder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_sd&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;title_color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;subtitle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(High Bias)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_sd&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;title_color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;subtitle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(High Variance)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;title_color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;subtitle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Balanced)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Prior SD = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior_sd&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;subtitle&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                       &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title_color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-chiến-lược-kiểm-định-và-đường-cong-học-learning-curves-trong-thực-tế&quot;&gt;5. Chiến lược kiểm định và đường cong học (Learning Curves) trong thực tế&lt;/h2&gt;

&lt;p&gt;Sự đánh đổi độ lệch – phương sai chỉ thực sự trở thành công cụ ra quyết định khi ta đo lường nó trên dữ liệu ngoài mẫu:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Điểm trên tập huấn luyện (Train score)&lt;/strong&gt; giúp theo dõi khả năng học trên dữ liệu đã thấy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điểm trên tập kiểm định (Validation score)&lt;/strong&gt; đo mức độ khái quát hóa để tinh chỉnh độ phức tạp hoặc độ rộng tiên nghiệm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điểm trên tập kiểm tra (Test score)&lt;/strong&gt; là kết quả báo cáo cuối cùng, chỉ sử dụng đúng một lần sau khi đã chốt lựa chọn mô hình.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cách đọc nhanh đường cong học:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Tập huấn luyện tốt, tập kiểm định kém và khoảng cách giữa hai tập lớn → &lt;strong&gt;phương sai cao (high variance)&lt;/strong&gt;, cần điều chuẩn mạnh hơn hoặc bổ sung dữ liệu.&lt;/li&gt;
  &lt;li&gt;Cả tập huấn luyện lẫn tập kiểm định đều kém → &lt;strong&gt;độ lệch cao (high bias)&lt;/strong&gt;, cần mô hình linh hoạt hơn hoặc bổ sung đặc trưng phù hợp.&lt;/li&gt;
  &lt;li&gt;Điểm trên tập kiểm định ổn định quanh mức tối ưu khi điều chỉnh cường độ điều chuẩn → đây là vùng cân bằng phù hợp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;6-nghiên-cứu-tình-huống-ứng-dụng-phần-2-tinh-chỉnh-độ-phức-tạp-bằng-tập-kiểm-định&quot;&gt;6. Nghiên cứu tình huống ứng dụng (Phần 2): Tinh chỉnh độ phức tạp bằng tập kiểm định&lt;/h2&gt;

&lt;p&gt;Tiếp nối thiết lập dữ liệu từ bài 7.1, ta sử dụng công thức nghiệm đóng của hồi quy Ridge để quét qua các cường độ điều chuẩn và chọn mức cân bằng độ lệch – phương sai dựa trên RMSE trên tập validation.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;ridge_fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;eye&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;solve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rmse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;lambdas&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;val_scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;coefs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambdas&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;ridge_fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;coefs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rmse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_train_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_train_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rmse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_val_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_val_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;best_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;best_lambda&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambdas&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;best_beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;coefs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_rmse&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rmse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_test_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_test_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Best lambda (validation): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_lambda&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Train RMSE (z-scale): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Validation RMSE (z-scale): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Test RMSE (z-scale): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_rmse&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/applied_ml_workflow_tradeoffs.png&quot; alt=&quot;Applied ML Workflow Tradeoffs&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Hình trên tóm tắt ba quyết định chính trong quy trình ứng dụng: (1) chọn cường độ điều chuẩn bằng RMSE trên tập validation, (2) kiểm tra độ lớn hệ số sau khi co rút, và (3) đánh giá độ ổn định khi chọn biến qua tần suất bootstrap.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Điểm kiểm tra quyết định 2&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nếu chỉ tối ưu RMSE trên tập huấn luyện, mô hình thường bị đẩy vào vùng quá khớp.&lt;/li&gt;
  &lt;li&gt;Chỉ khi tối ưu RMSE trên tập validation và giữ tập test cho bước cuối cùng, ta mới có cơ sở đáng tin cậy để đánh giá khả năng khái quát hóa.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;7-danh-sách-kiểm-tra-tinh-chỉnh-từ-đánh-đổi-đến-hành-động&quot;&gt;7. Danh sách kiểm tra tinh chỉnh: Từ đánh đổi đến hành động&lt;/h2&gt;

&lt;p&gt;Khi cần chọn độ phức tạp mô hình trong bài toán hồi quy hoặc phân lớp:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Chọn thước đo phù hợp với mục tiêu bài toán thay vì dùng metric một cách hình thức.&lt;/li&gt;
  &lt;li&gt;Dùng lưới giá trị hợp lý cho cường độ điều chuẩn hoặc độ rộng tiên nghiệm thay vì quét quá rộng thiếu kiểm soát.&lt;/li&gt;
  &lt;li&gt;Theo dõi đồng thời khoảng cách giữa train và validation cùng độ ổn định qua các fold.&lt;/li&gt;
  &lt;li&gt;Kết hợp hiệu năng ngoài mẫu với kiểm tra dự báo hậu nghiệm để phát hiện sai lệch cấu trúc mô hình (model misspecification).&lt;/li&gt;
  &lt;li&gt;Chốt mô hình dựa trên lập luận có thể giải thích được, chứ không chỉ dựa vào điểm số cao nhất đơn thuần.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;Sự đánh đổi giữa độ lệch và phương sai cho thấy sai số dự báo không thể được đánh giá chỉ bằng độ khớp trên tập huấn luyện. &lt;strong&gt;Độ lệch (bias)&lt;/strong&gt; phản ánh cái giá của một mô hình quá đơn giản, còn &lt;strong&gt;phương sai (variance)&lt;/strong&gt; phản ánh cái giá của một mô hình quá nhạy với dữ liệu huấn luyện. Công thức \(\text{MSE}=\text{Bias}^2+\text{Variance}+\text{Irreducible Error}\) nhắc ta rằng mô hình tốt là mô hình cân bằng được hai xu hướng đối nghịch này. Điều chuẩn là công cụ thực hành để điều chỉnh điểm cân bằng đó, và trong thống kê Bayes, chính độ mạnh của phân phối tiên nghiệm đảm nhiệm vai trò ấy.&lt;/p&gt;

&lt;p&gt;Điểm cốt lõi cần ghi nhớ là một mô hình khớp rất sát tập huấn luyện chưa chắc là mô hình tốt; mô hình tốt phải khái quát hóa hiệu quả trên dữ liệu mới.&lt;/p&gt;

&lt;p&gt;Bài tiếp theo: &lt;strong&gt;Chọn biến (Feature Selection)&lt;/strong&gt; — hoàn tất nghiên cứu tình huống bằng kiểm tra độ ổn định (stability selection) và diễn giải có xét đến độ bất định.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tính-trực-tiếp-ba-thành-phần-của-mse-để-chọn-độ-phức-tạp-tối-ưu&quot;&gt;Giải thích: Tính trực tiếp ba thành phần của MSE để chọn độ phức tạp tối ưu&lt;/h2&gt;

&lt;p&gt;Khi so sánh 3 mô hình có độ phức tạp tăng dần trên cùng một bài toán có nhiễu nền \(\sigma_\varepsilon = 2.0\) (tức \(\sigma_\varepsilon^2 = 4.0\)), hãy đọc bảng phân rã theo 3 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính \(\mathrm{Bias}^2\):&lt;/strong&gt; Đo sai lệch hệ thống trung bình so với hàm thật \(f(x_0)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính \(\mathrm{Variance}\):&lt;/strong&gt; Đo độ dao động của dự báo khi thay đổi tập huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cộng với nhiễu không thể khử \(\sigma_\varepsilon^2\):&lt;/strong&gt; Chọn mô hình cực tiểu hóa &lt;strong&gt;tổng&lt;/strong&gt; cả ba thành phần, chứ không chọn mô hình có Bias = 0!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-chọn-giữa-mô-hình-đơn-giản-vừa-phải-và-phức-tạp&quot;&gt;Ví dụ tính toán làm từng bước: Chọn giữa Mô hình đơn giản, Vừa phải và Phức tạp&lt;/h3&gt;

&lt;p&gt;Giả sử hàm thật tại \(x_0\) là \(f(x_0) = 10.0\) và nhiễu đo lường có phương sai \(\sigma_\varepsilon^2 = 4.0\). Kết quả đánh giá ba mô hình:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Mô hình&lt;/th&gt;
      &lt;th&gt;\(\mathrm{Bias}\)&lt;/th&gt;
      &lt;th&gt;\(\mathrm{Bias}^2\)&lt;/th&gt;
      &lt;th&gt;\(\mathrm{Variance}\)&lt;/th&gt;
      &lt;th&gt;Nhiễu nền \(\sigma_\varepsilon^2\)&lt;/th&gt;
      &lt;th&gt;Tổng MSE dự báo&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Mô hình 1 (Quá đơn giản)&lt;/td&gt;
      &lt;td&gt;\(-3.0\)&lt;/td&gt;
      &lt;td&gt;\(9.00\)&lt;/td&gt;
      &lt;td&gt;\(0.50\)&lt;/td&gt;
      &lt;td&gt;\(4.00\)&lt;/td&gt;
      &lt;td&gt;\(13.50\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mô hình 2 (Điều chuẩn vừa phải)&lt;/td&gt;
      &lt;td&gt;\(-1.0\)&lt;/td&gt;
      &lt;td&gt;\(1.00\)&lt;/td&gt;
      &lt;td&gt;\(1.50\)&lt;/td&gt;
      &lt;td&gt;\(4.00\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(6.50\)&lt;/strong&gt; (tối ưu)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mô hình 3 (Quá phức tạp)&lt;/td&gt;
      &lt;td&gt;\(0.0\)&lt;/td&gt;
      &lt;td&gt;\(0.00\)&lt;/td&gt;
      &lt;td&gt;\(6.00\)&lt;/td&gt;
      &lt;td&gt;\(4.00\)&lt;/td&gt;
      &lt;td&gt;\(10.00\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Dù Mô hình 3 hoàn toàn không chệch (\(\mathrm{Bias} = 0\)), phương sai quá lớn (\(6.00\)) khiến tổng sai số dự báo của nó (\(10.00\)) thua xa Mô hình 2 (\(6.50\)). Đồng thời, không một mô hình nào có thể kéo tổng MSE xuống dưới \(4.00\) vì nhiễu nền không thể khử.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Cố gắng tăng độ phức tạp hoặc chạy thêm vòng lặp để kéo lỗi tập huấn luyện xuống gần 0 — khi lỗi huấn luyện thấp hơn cả \(\sigma_\varepsilon^2 = 4.00\), đó chính là bằng chứng chắc chắn mô hình đang học thuộc nhiễu!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu bạn thu thập thêm dữ liệu gấp 4 lần cho Mô hình 3 khiến phương sai của nó giảm 4 lần (từ \(6.00\) xuống \(1.50\)) trong khi Bias vẫn bằng \(0\), tổng MSE mới của Mô hình 3 sẽ là \(0 + 1.50 + 4.00 = 5.50\) — vượt qua Mô hình 2. Điều này giải thích vì sao cỡ mẫu lớn cho phép dùng mô hình phức tạp hơn.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giải thích sự khác biệt giữa mô hình quá đơn giản bị lệch hệ thống và mô hình quá linh hoạt dao động theo mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qmVT35gFW-Q&quot;&gt;[Proof] MSE = Variance + Bias²&lt;/a&gt; — math et al, English. Chứng minh hệ thức phân rã MSE thành bình phương độ lệch cộng phương sai.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=fSytzGwwBVw&quot;&gt;Machine Learning Fundamentals: Cross Validation&lt;/a&gt; — StatQuest with Josh Starmer, English. Trình bày kiểm định chéo như cách ước lượng sai số ngoài mẫu, hỗ trợ phần đường cong học và chọn độ phức tạp.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 1&lt;/strong&gt;: Tự cài đặt phép phân rã độ lệch – phương sai từ đầu và kiểm chứng hệ thức \(\text{MSE} = \text{Bias}^2 + \text{Variance}\) (trên phần sai số của hàm dự đoán).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 2&lt;/strong&gt;: Sinh dữ liệu, tính độ lệch và phương sai cho các mô hình có độ phức tạp khác nhau, rồi tìm mức độ phức tạp tối ưu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 3&lt;/strong&gt;: Dùng hồi quy Ridge với nhiều giá trị \(\lambda\) khác nhau, vẽ đường cong độ lệch – phương sai và tìm \(\lambda\) tối ưu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 4&lt;/strong&gt;: Xây dựng các mô hình Bayes với nhiều độ lệch chuẩn tiên nghiệm khác nhau, tính phương sai hậu nghiệm và liên hệ với sự đánh đổi độ lệch – phương sai.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 5&lt;/strong&gt;: Trên một tập dữ liệu thực, chia tập train/test, minh họa hiện tượng quá khớp bằng đa thức bậc cao và khắc phục bằng điều chuẩn.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Hastie, T., Tibshirani, R., &amp;amp; Friedman, J. (2009).&lt;/strong&gt; &lt;em&gt;The Elements of Statistical Learning&lt;/em&gt; (2nd Edition). Springer.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 7: Model Assessment and Selection&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;James, G., et al. (2013).&lt;/strong&gt; &lt;em&gt;An Introduction to Statistical Learning&lt;/em&gt;. Springer.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 2: Statistical Learning&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter07/07_03_feature_selection/&quot;&gt;7.3 Feature Selection&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 7.1: Regularization với Priors - Ngăn Overfitting</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter07/07_01_regularization_priors/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter07/07_01_regularization_priors</id>
   <content type="html">&lt;p&gt;Trong học máy truyền thống, điều chuẩn Ridge (\(L_2\)) và Lasso (\(L_1\)) thường được giới thiệu như những “hạng phạt thêm vào hàm mất mát” để chống quá khớp. Nhưng dưới góc nhìn thống kê Bayes, chúng không hề là thủ thuật tối ưu tùy hứng: tìm đỉnh hậu nghiệm (MAP) với prior Gaussian chính là hồi quy Ridge, còn với prior Laplace chính là hồi quy Lasso!&lt;/p&gt;

&lt;p&gt;Bài mở đầu Chương 7 này bóc tách mối tương đương toán học tuyệt đẹp ấy, đồng thời cho thấy bước tiến của Bayes đầy đủ: thay vì chỉ lấy một điểm MAP duy nhất, ta giữ toàn bộ phân phối hậu nghiệm để vừa co cụm hệ số nhiễu vừa bảo toàn trọn vẹn độ bất định.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành bài học này, bạn sẽ hiểu &lt;strong&gt;điều chuẩn (regularization)&lt;/strong&gt; như một cơ chế cốt lõi để ngăn &lt;strong&gt;quá khớp (overfitting)&lt;/strong&gt;. Bài học làm rõ vì sao phân phối tiên nghiệm (prior) trong thống kê Bayes tự nhiên thực hiện điều chuẩn, mối liên hệ giữa tiên nghiệm với hồi quy Ridge và Lasso trong thống kê tần suất (frequentist), và khi nào ta thực sự cần điều chuẩn thay vì tiếp tục tăng độ phức tạp của mô hình. Đây là kỹ năng thiết yếu khi xây dựng mô hình có nhiều &lt;strong&gt;biến dự báo (predictors)&lt;/strong&gt;, đặc biệt khi số lượng biến vượt quá khả năng kiểm soát bằng trực giác.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-tương-đương-map--penalty-hình-học-prior-và-co-cụm-thích-nghi&quot;&gt;Kiến thức cần nhớ: Tương đương MAP – Penalty, Hình học Prior và Co cụm thích nghi&lt;/h2&gt;

&lt;p&gt;Để hiểu bản chất điều chuẩn Bayes ở mức độ chuyên sâu, hãy liên kết ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tương đương đại số giữa Prior và Penalty:&lt;/strong&gt; Trong bài toán tối đa hóa log-posterior \(\log p(\beta \mid y) = \log p(y \mid \beta) + \log p(\beta) + C\), thành phần \(\log p(\beta)\) đóng vai trò chính xác của số hạng phạt. Prior \(\mathcal{N}(0, \tau^2)\) sinh ra hạng phạt \(-\frac{\beta^2}{2\tau^2}\) (Ridge \(L_2\) với \(\lambda = \sigma^2/\tau^2\)), còn prior \(\text{Laplace}(0, b)\) sinh ra hạng phạt \(-\frac{\vert\beta\vert}{b}\) (Lasso \(L_1\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hình học của Prior (Đuôi mỏng vs. Nhọn tại 0 vs. Đuôi dày):&lt;/strong&gt; Prior Gaussian co đều mọi hệ số; prior Laplace nhọn tại 0 (khuyến khích thưa tại MAP); còn prior Horseshoe có đỉnh cực nhọn tại 0 kết hợp đuôi dày như Cauchy để co mạnh nhiễu về 0 mà &lt;em&gt;không&lt;/em&gt; co quá tay các tín hiệu thật lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa biến dự báo (Standardization):&lt;/strong&gt; Mọi prior điều chuẩn đều phụ thuộc thang đo của biến \(x_j\). Nếu không chuẩn hóa biến dự báo về trung bình 0, độ lệch chuẩn 1 trước khi đặt cùng một prior \(\tau\), biến có đơn vị lớn hơn sẽ bị phạt nhẹ hơn một cách bất công.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-vấn-đề-quá-khớp-overfitting&quot;&gt;Giới thiệu: Vấn đề quá khớp (Overfitting)&lt;/h2&gt;

&lt;p&gt;Giả sử bạn chỉ có 20 điểm dữ liệu nhưng muốn khớp một mô hình hồi quy đa thức (polynomial regression). Câu hỏi tưởng như mang tính kỹ thuật — nên chọn bậc 1, bậc 10 hay bậc 15 — thực chất dẫn thẳng tới một vấn đề nền tảng của thống kê hiện đại. Nếu mô hình quá đơn giản, nó sẽ bị &lt;strong&gt;thiếu khớp (underfit)&lt;/strong&gt; và bỏ sót cấu trúc quan trọng; ngược lại, nếu mô hình quá linh hoạt, nó sẽ bám chặt cả những dao động ngẫu nhiên của dữ liệu huấn luyện. Khi đó, mô hình học &lt;strong&gt;nhiễu (noise)&lt;/strong&gt; thay vì &lt;strong&gt;tín hiệu (signal)&lt;/strong&gt;: kết quả có vẻ rất tốt trên tập huấn luyện nhưng lại dự đoán kém trên dữ liệu mới. Đó là hiện tượng quá khớp (overfitting).&lt;/p&gt;

&lt;h2 id=&quot;1-minh-họa-hiện-tượng-quá-khớp&quot;&gt;1. Minh họa hiện tượng quá khớp&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/overfitting_demonstration.png&quot; alt=&quot;Overfitting Demonstration&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Hình minh họa cho thấy rõ cơ chế của vấn đề. Với đa thức bậc 1, mô hình quá đơn giản nên cả sai số huấn luyện lẫn sai số kiểm tra đều cao — đây là trạng thái thiếu khớp điển hình. Với bậc 3, mô hình đủ linh hoạt để nắm bắt xu hướng chính mà chưa học thuộc nhiễu, nhờ đó cả hai loại sai số đều giảm. Khi tăng lên bậc 10, mô hình khớp rất sát dữ liệu huấn luyện nhưng sai số kiểm tra lại tăng, vì nó đã ghi nhớ các dao động ngẫu nhiên không lặp lại ở dữ liệu mới. Đến bậc 15, hiện tượng này trở nên cực đoan hơn khi mô hình gần như mất khả năng &lt;strong&gt;khái quát hóa (generalize)&lt;/strong&gt;. Điểm cần ghi nhớ là sai số kiểm tra thường tăng trở lại khi mô hình quá phức tạp, và đó là lúc điều chuẩn trở nên cần thiết.&lt;/p&gt;

&lt;h2 id=&quot;2-điều-chuẩn-regularization-hướng-giải-quyết&quot;&gt;2. Điều chuẩn (Regularization): Hướng giải quyết&lt;/h2&gt;

&lt;p&gt;Ý tưởng cốt lõi của điều chuẩn là không để mô hình tự do sử dụng các hệ số quá lớn chỉ nhằm bám sát dữ liệu huấn luyện. Ta bổ sung một cơ chế ưu tiên các mô hình đơn giản hơn bằng cách phạt những cấu hình hệ số quá cực đoan.&lt;/p&gt;

&lt;h3 id=&quot;21-hồi-quy-ridge-điều-chuẩn-l2&quot;&gt;2.1. Hồi quy Ridge (Điều chuẩn L2)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Hàm mục tiêu&lt;/strong&gt;:
\(\min_{\beta} \sum_{i=1}^n (y_i - \hat{y}_i)^2 + \lambda \sum_{j=1}^p \beta_j^2\)&lt;/p&gt;

&lt;p&gt;Trong biểu thức này, hạng tử đầu tiên yêu cầu mô hình khớp dữ liệu, còn hạng tử thứ hai phạt tổng bình phương các hệ số để giữ chúng ở quy mô vừa phải. Tham số \(\lambda\) điều khiển mức độ phạt: \(\lambda\) càng lớn thì điều chuẩn càng mạnh và các hệ số càng bị kéo gần về 0.&lt;/p&gt;

&lt;p&gt;Từ góc nhìn Bayes, hồi quy Ridge tương ứng với việc đặt &lt;strong&gt;tiên nghiệm chuẩn (Normal prior)&lt;/strong&gt; lên các hệ số:&lt;/p&gt;

\[\beta_j \sim \text{Normal}(0, \sigma^2)\]

&lt;h3 id=&quot;22-hồi-quy-lasso-điều-chuẩn-l1&quot;&gt;2.2. Hồi quy Lasso (Điều chuẩn L1)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Hàm mục tiêu&lt;/strong&gt;:
\(\min_{\beta} \sum_{i=1}^n (y_i - \hat{y}_i)^2 + \lambda \sum_{j=1}^p |\beta_j|\)&lt;/p&gt;

&lt;p&gt;Trong ngôn ngữ Bayes, Lasso tương ứng với việc đặt &lt;strong&gt;tiên nghiệm Laplace (Laplace prior)&lt;/strong&gt; lên các hệ số:&lt;/p&gt;

\[\beta_j \sim \text{Laplace}(0, b)\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/regularization_priors.png&quot; alt=&quot;Regularization Priors&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Hình so sánh các phân phối tiên nghiệm cho thấy điều chuẩn trong thống kê Bayes là một lựa chọn mô hình hóa trực tiếp chứ không phải thủ thuật bổ sung từ bên ngoài. &lt;strong&gt;Tiên nghiệm chuẩn&lt;/strong&gt; ở hình bên trái có tâm tại 0 và đỉnh trơn, nên có xu hướng co các hệ số về gần 0 nhưng hiếm khi ép chúng bằng đúng 0; cách này phù hợp khi ta tin rằng nhiều biến dự báo đều có đóng góp nhỏ. &lt;strong&gt;Tiên nghiệm Laplace&lt;/strong&gt; ở hình giữa nhọn hơn tại 0 và có đuôi dày hơn, nên khuyến khích &lt;strong&gt;tính thưa (sparsity)&lt;/strong&gt; — nhiều hệ số bị đẩy mạnh về gần 0 hơn — do đó đặc biệt hữu ích cho bài toán &lt;strong&gt;chọn biến (feature selection)&lt;/strong&gt;. Hình so sánh bên phải nhấn mạnh rằng chọn tiên nghiệm thực chất là chọn một cơ chế điều chuẩn: tiên nghiệm phẳng gần như không điều chuẩn, trong khi tiên nghiệm chuẩn và Laplace mã hóa những mức độ và kiểu co rút khác nhau.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-tiên-nghiệm-chuẩn-co-rút-hệ-số-ridge&quot;&gt;Thử nghiệm: Tiên nghiệm chuẩn co rút hệ số (Ridge)&lt;/h3&gt;

&lt;p&gt;Giảm \(\tau\) từng bước để quan sát đường cong mượt dần, trong khi sai số kiểm tra giảm xuống rồi tăng trở lại.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;shrink-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;video-ngắn-điều-chuẩn-bằng-prior-hình-tròn-ridge-normal-vs-hình-thoi-lasso-laplace&quot;&gt;Video ngắn: Điều chuẩn bằng Prior: Hình tròn Ridge (Normal) vs Hình thoi Lasso (Laplace)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch07-01a-ridge-lasso-prior-geometry.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 22 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): cho thấy Prior làm phẳng đường cong quá khớp và giải thích trực quan vì sao hình thoi Laplace ép hệ số nhiễu về đúng 0.&lt;/p&gt;

&lt;h2 id=&quot;3-điều-chuẩn-bayes-trong-pymc&quot;&gt;3. Điều chuẩn Bayes trong PyMC&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate data with many predictors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 20 predictors
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Only first 3 predictors matter
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Standardize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Model 1: Weak priors (no regularization)
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_weak&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Weak!
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Weak!
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;trace_weak&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                          &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Model 2: Strong priors (regularization)
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Strong regularization!
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;trace_reg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                         &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compare coefficients
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_weak&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_weak&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_reg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# True coefficients
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictor Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;TRUE COEFFICIENTS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Only first 3 non-zero&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Weak priors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_weak&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictor Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;WEAK PRIORS (No Regularization)&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
                 &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Many non-zero coefficients&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Strong priors (regularization)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictor Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;STRONG PRIORS (Regularization)&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
                 &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shrinkage toward 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;REGULARIZATION EFFECT&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weak priors:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Non-zero coefficients: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_weak&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Max |β|: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_weak&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Strong priors (regularization):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Non-zero coefficients: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Max |β|: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;→ Regularization shrinks coefficients toward 0!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;4-lựa-chọn-cường-độ-điều-chuẩn&quot;&gt;4. Lựa chọn cường độ điều chuẩn&lt;/h2&gt;

&lt;p&gt;Một trong những câu hỏi thực tế nhất là nên điều chuẩn mạnh đến mức nào — hay theo ngôn ngữ Bayes, phân phối tiên nghiệm nên hẹp đến đâu để vừa kiểm soát quá khớp vừa không làm mất tín hiệu thật.&lt;/p&gt;

&lt;h3 id=&quot;41-kiểm-định-chéo-cross-validation&quot;&gt;4.1. Kiểm định chéo (Cross-Validation)&lt;/h3&gt;

&lt;p&gt;Một cách tiếp cận thực dụng là dùng kiểm định chéo (cross-validation) để chọn độ rộng tiên nghiệm sao cho năng lực dự báo ngoài mẫu đạt tốt nhất.&lt;/p&gt;

&lt;h3 id=&quot;42-kiểm-tra-dự-báo-tiên-nghiệm-prior-predictive-checks&quot;&gt;4.2. Kiểm tra dự báo tiên nghiệm (Prior Predictive Checks)&lt;/h3&gt;

&lt;p&gt;Một cách tiếp cận mang tính Bayes hơn là dùng &lt;strong&gt;kiểm tra dự báo tiên nghiệm (prior predictive checks)&lt;/strong&gt; để xem tiên nghiệm hiện tại có sinh ra những dự đoán hợp lý hay không, trước cả khi đưa dữ liệu vào khớp mô hình.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Prior predictive check
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_check&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_prior&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Sample from prior
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;prior_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample_prior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_prior_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_prior&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Prior predictions
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_prior_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_prior_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.02&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y (standardized)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PRIOR PREDICTIVE CHECK&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
                 &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Do priors generate reasonable data?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Prior means and SDs
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior_means&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_prior_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;prior_sds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_prior_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior_means&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_sds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed mean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed SD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Prior Predicted Mean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Prior Predicted SD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PRIOR PREDICTIONS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean vs SD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;43-danh-sách-kiểm-tra-chọn-độ-mạnh-tiên-nghiệm-trong-quy-trình-học-máy&quot;&gt;4.3. Danh sách kiểm tra chọn độ mạnh tiên nghiệm trong quy trình học máy&lt;/h3&gt;

&lt;p&gt;Trong thực tế học máy, độ mạnh của tiên nghiệm (hay cường độ điều chuẩn) nên được chọn theo một quy trình rõ ràng thay vì thử nghiệm ngẫu nhiên:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Xác định mục tiêu dự báo và thước đo&lt;/strong&gt;: chọn metric phù hợp với bài toán (RMSE, MAE, log-loss, calibration…).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chia tập dữ liệu ngay từ đầu&lt;/strong&gt;: tách train/validation/test trước khi tinh chỉnh bất kỳ tham số nào.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chỉ khớp bước tiền xử lý trên tập huấn luyện&lt;/strong&gt;: chuẩn hóa, điền khuyết và mã hóa phải học từ tập train rồi mới áp dụng sang validation và test để tránh rò rỉ dữ liệu (data leakage).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tinh chỉnh độ rộng tiên nghiệm trên tập validation&lt;/strong&gt;: quét qua một lưới giá trị độ rộng tiên nghiệm hợp lý và so sánh hiệu năng ngoài mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thực hiện kiểm tra dự báo tiên nghiệm&lt;/strong&gt;: loại bỏ những tiên nghiệm sinh ra dự đoán phi lý trước khi đánh giá chi tiết kết quả khớp mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh giá trên tập test đúng một lần cuối&lt;/strong&gt;: chỉ dùng tập test ở bước cuối cùng để bảo toàn tính khách quan.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Quy trình trên kết nối trực tiếp tư duy Bayes với quy trình huấn luyện học máy: tiên nghiệm không chỉ là yếu tố lý thuyết, mà là một siêu tham số mang ý nghĩa mô hình hóa rõ ràng.&lt;/p&gt;

&lt;h2 id=&quot;5-nghiên-cứu-tình-huống-ứng-dụng-phần-1-thiết-lập-chia-tập-và-kiểm-soát-rò-rỉ-dữ-liệu&quot;&gt;5. Nghiên cứu tình huống ứng dụng (Phần 1): Thiết lập, chia tập và kiểm soát rò rỉ dữ liệu&lt;/h2&gt;

&lt;p&gt;Ta xây dựng một bài toán hồi quy nhiều chiều giả lập: dự đoán giá trị liên tục từ 25 biến dự báo, trong đó chỉ một số ít biến thực sự mang tín hiệu. Mục tiêu của Phần 1 là thiết lập pipeline xử lý dữ liệu đúng cách.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;180&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sparse ground truth: chi 6 bien co signal
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 60/20/20 split
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;permutation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;val_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Preprocessing fit tren train only (anti-leakage)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_train_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_val_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_test_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;mu_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sd_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;y_train_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_y&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_val_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_y&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_test_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_y&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Điểm kiểm tra quyết định 1&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chỉ bắt đầu tinh chỉnh tiên nghiệm hoặc cường độ điều chuẩn sau khi dữ liệu đã được chia tập và chuẩn hóa đúng theo quy trình chỉ dùng tập huấn luyện.&lt;/li&gt;
  &lt;li&gt;Nếu tiền xử lý được khớp trên toàn bộ dữ liệu trước khi chia tập, kết quả trên tập validation sẽ lạc quan giả tạo do rò rỉ dữ liệu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;6-khi-nào-cần-điều-chuẩn&quot;&gt;6. Khi nào cần điều chuẩn?&lt;/h2&gt;

&lt;p&gt;Điều chuẩn đặc biệt cần thiết khi số lượng biến dự báo lớn so với cỡ mẫu, khi các biến dự báo tương quan mạnh gây ra &lt;strong&gt;đa cộng tuyến (multicollinearity)&lt;/strong&gt;, khi dữ liệu ít khiến mô hình dễ dao động mạnh theo từng mẫu, hoặc khi mục tiêu là tìm lời giải thưa chỉ giữ lại một số ít biến quan trọng. Ngược lại, nếu số biến dự báo ít, cỡ mẫu lớn, các biến gần như độc lập và có cơ sở lý thuyết vững để giữ toàn bộ biến trong mô hình, vai trò của điều chuẩn sẽ thứ yếu hơn. Điều chuẩn không phải lúc nào cũng cần thiết một cách máy móc; nó là biện pháp có chủ đích khi mô hình quá linh hoạt so với lượng thông tin mà dữ liệu cung cấp.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;Điều chuẩn giúp ngăn quá khớp bằng cách kiểm soát độ lớn của các hệ số thay vì để mô hình tự do bám theo mọi dao động của dữ liệu huấn luyện. Hồi quy Ridge tương ứng với việc đặt tiên nghiệm chuẩn để co các hệ số về gần 0, còn Lasso tương ứng với tiên nghiệm Laplace và khuyến khích lời giải thưa hơn. Từ góc nhìn Bayes, điều chuẩn không phải một thành phần gắn thêm bên ngoài, mà là hệ quả tự nhiên của việc chọn tiên nghiệm phù hợp với hiểu biết về quy mô và cấu trúc của các hệ số. Cường độ điều chuẩn có thể được điều chỉnh bằng kiểm định chéo hoặc kiểm tra dự báo tiên nghiệm tùy mục tiêu phân tích.&lt;/p&gt;

&lt;p&gt;Điểm cốt lõi của bài là trong thống kê Bayes, thực hiện điều chuẩn về bản chất chính là lựa chọn phân phối tiên nghiệm một cách có cơ sở.&lt;/p&gt;

&lt;p&gt;Bài tiếp theo: &lt;strong&gt;Đánh đổi giữa độ lệch và phương sai (Bias-Variance Tradeoff)&lt;/strong&gt; — đi sâu vào chiến lược kiểm định và tinh chỉnh độ phức tạp mô hình trên cùng nghiên cứu tình huống.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-ánh-xạ-chính-xác-giữa-độ-rộng-prior-tau-và-hệ-số-phạt-ridge-lambda&quot;&gt;Giải thích: Ánh xạ chính xác giữa độ rộng Prior \(\tau\) và hệ số phạt Ridge \(\lambda\)&lt;/h2&gt;

&lt;p&gt;Nhiều người học nhớ “Gaussian là Ridge” nhưng chưa từng tự viết công thức đổi giữa \(\tau\) và \(\lambda\). Hãy đọc chậm 3 bước sau cho hồi quy tuyến tính chuẩn hóa (\(\sigma^2\) là phương sai nhiễu):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Viết âm log-posterior:&lt;/strong&gt;
\(-\log p(\beta \mid y) = \frac{1}{2\sigma^2}\sum_{i=1}^n (y_i - x_i^\top \beta)^2 + \frac{1}{2\tau^2}\sum_{j=1}^p \beta_j^2 + C.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhân cả hai vế với \(2\sigma^2\):&lt;/strong&gt; Ta thu ngay hàm mục tiêu Ridge kinh điển:
\(\sum_{i=1}^n (y_i - x_i^\top \beta)^2 + \underbrace{\frac{\sigma^2}{\tau^2}}_{\lambda}\sum_{j=1}^p \beta_j^2.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đọc công thức co cụm 1 chiều (với \(\sum x_i^2 = S_{xx}\)):&lt;/strong&gt;
\(\hat\beta_{\text{Ridge/MAP}} = \frac{S_{xx}}{S_{xx} + \sigma^2/\tau^2}\,\hat\beta_{\text{OLS}}.\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-mức-độ-co-cụm-theo-độ-rộng-prior-tau&quot;&gt;Ví dụ tính toán làm từng bước: Mức độ co cụm theo độ rộng Prior \(\tau\)&lt;/h3&gt;

&lt;p&gt;Giả sử trên một biến dự báo đã chuẩn hóa có \(S_{xx} = 20\), phương sai nhiễu \(\sigma^2 = 4\) và ước lượng OLS thô là \(\hat\beta_{\text{OLS}} = 2.0\). Hãy so sánh ba lựa chọn độ rộng prior \(\tau\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Độ rộng Prior \(\tau\)&lt;/th&gt;
      &lt;th&gt;Hệ số phạt tương đương \(\lambda = \sigma^2 / \tau^2\)&lt;/th&gt;
      &lt;th&gt;Hệ số co cụm \(\frac{S_{xx}}{S_{xx}+\lambda}\)&lt;/th&gt;
      &lt;th&gt;Ước lượng hậu nghiệm \(\hat\beta_{\text{MAP}}\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Rất rộng (\(\tau = 10\))&lt;/td&gt;
      &lt;td&gt;\(4 / 100 = 0.04\)&lt;/td&gt;
      &lt;td&gt;\(20 / 20.04 \approx 0.998\)&lt;/td&gt;
      &lt;td&gt;\(1.996\) (gần như OLS)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Vừa phải (\(\tau = 1.0\))&lt;/td&gt;
      &lt;td&gt;\(4 / 1 = 4.00\)&lt;/td&gt;
      &lt;td&gt;\(20 / 24 = 0.833\)&lt;/td&gt;
      &lt;td&gt;\(1.667\) (co nhẹ 16.7%)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mạnh (\(\tau = 0.5\))&lt;/td&gt;
      &lt;td&gt;\(4 / 0.25 = 16.00\)&lt;/td&gt;
      &lt;td&gt;\(20 / 36 = 0.556\)&lt;/td&gt;
      &lt;td&gt;\(1.111\) (co mạnh 44.4%)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nghĩ rằng chạy MCMC với prior Laplace sẽ cho ra các mẫu hậu nghiệm có hệ số bằng đúng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.000&lt;/code&gt; giống thuật toán Lasso tối ưu điểm. Trên thực tế, Lasso chỉ tạo đúng số 0 tại &lt;em&gt;đỉnh MAP&lt;/em&gt;; còn các mẫu MCMC từ hậu nghiệm liên tục luôn có xác suất rơi vào đúng điểm 0 bằng 0, chỉ tập trung dày quanh 0.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu cỡ mẫu tăng gấp 5 lần (\(S_{xx} = 100\)) mà vẫn giữ prior vừa phải \(\tau = 1.0\) (\(\lambda = 4\)), hệ số co cụm tăng lên \(100 / 104 \approx 0.962\) — đúng nguyên tắc dữ liệu nhiều dần sẽ tự động giảm tác động của prior.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Q81RR3yKn30&quot;&gt;Regularization Part 1: Ridge (L2) Regression&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giải thích cơ chế phạt L2 kéo hệ số về gần 0 để giảm phương sai, liên hệ trực tiếp với hiện tượng quá khớp ở đa thức bậc cao.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=W_SjooqeOqM&quot;&gt;Ridge Regression is a Gaussian Prior&lt;/a&gt; — DataMListic, English. Trình bày mối liên hệ giữa Ridge và tiên nghiệm chuẩn trên hệ số, củng cố góc nhìn tiên nghiệm Bayes chính là điều chuẩn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8-_hZD0BRK8&quot;&gt;Lasso Regression is a Laplace Prior&lt;/a&gt; — DataMListic, English. Giải thích sự tương ứng giữa Lasso và tiên nghiệm Laplace, bổ sung cho phần so sánh các cơ chế co rút hệ số.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 1&lt;/strong&gt;: Sinh dữ liệu nhiều chiều (\(p &amp;gt; n\)), khớp mô hình với tiên nghiệm yếu và tiên nghiệm mạnh, sau đó so sánh kết quả.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 2&lt;/strong&gt;: Triển khai tiên nghiệm Lasso (Laplace) trong PyMC và so sánh với Ridge.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 3&lt;/strong&gt;: Sử dụng kiểm định chéo (cross-validation) để chọn độ rộng tiên nghiệm tối ưu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 4&lt;/strong&gt;: Thực hiện kiểm tra dự báo tiên nghiệm với nhiều độ rộng tiên nghiệm khác nhau và xác định mức nào là hợp lý.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 5&lt;/strong&gt;: Áp dụng điều chuẩn trên một tập dữ liệu thực có nhiều biến dự báo và diễn giải kết quả thu được.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., et al. (2020).&lt;/strong&gt; &lt;em&gt;Regression and Other Stories&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 12: Transformations and regression&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 4: Geocentric Models (Priors as regularization)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter07/07_02_bias_variance_tradeoff/&quot;&gt;7.2 Bias-Variance Tradeoff&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 6.3: Model Evaluation for GLMs</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter06/06_03_model_evaluation_glm/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter06/06_03_model_evaluation_glm</id>
   <content type="html">&lt;p&gt;Trong hồi quy tuyến tính cổ điển, ta quen nhìn \(R^2\) và biểu đồ phần dư đơn giản. Nhưng khi bước sang mô hình tuyến tính tổng quát (GLM) — nơi đầu ra là 0/1 hay số đếm 0, 1, 2, … — phần dư thô \(y_i - \hat p_i\) không còn tuân theo phân phối chuẩn hay có phương sai đồng nhất nữa. Thậm chí một mô hình dự đoán luôn luôn “không gian lận” trên tập dữ liệu 99% giao dịch sạch vẫn đạt độ chính xác 99% dù hoàn toàn vô dụng.&lt;/p&gt;

&lt;p&gt;Bài học này trang bị bộ công cụ đánh giá chuyên biệt cho GLM Bayes: đường cong ROC/AUC, hiệu chỉnh xác suất (&lt;em&gt;calibration&lt;/em&gt;), log-loss / Brier score, phần dư Deviance/Pearson và kiểm tra dự báo hậu nghiệm (PPC).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành bài học này, bạn sẽ nắm cách đánh giá các &lt;strong&gt;mô hình GLM&lt;/strong&gt; như hồi quy logistic và hồi quy Poisson trong thực tế. Trọng tâm của bài là chọn đúng tiêu chí đánh giá theo bản chất của biến kết quả: từ các &lt;strong&gt;thước đo phân lớp (classification metrics)&lt;/strong&gt; như accuracy, sensitivity, specificity và đường cong ROC, đến &lt;strong&gt;đồ thị hiệu chỉnh xác suất (calibration plot)&lt;/strong&gt;, &lt;strong&gt;độ lệch mô hình (deviance)&lt;/strong&gt; và &lt;strong&gt;kiểm tra dự báo hậu nghiệm (posterior predictive checks)&lt;/strong&gt;. Một mô hình chỉ thực sự hữu ích khi ta biết rõ nó làm tốt ở điểm nào, hạn chế ở đâu và còn tồn tại những sai lệch nào.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-phân-biệt-hiệu-chỉnh-và-phản-biện-mô-hình-glm-bayes&quot;&gt;Kiến thức cần nhớ: Phân biệt, Hiệu chỉnh và Phản biện mô hình GLM Bayes&lt;/h2&gt;

&lt;p&gt;Đánh giá đúng một mô hình GLM đòi hỏi kết hợp ba trụ cột độc lập:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Khả năng phân biệt vs. Độ hiệu chỉnh (Discrimination vs. Calibration):&lt;/strong&gt; AUC-ROC chỉ đo xem mô hình có xếp hạng ca dương tính cao hơn ca âm tính hay không (bất biến nếu nhân đôi mọi xác suất miễn giữ thứ tự). Trong khi đó, &lt;strong&gt;Calibration&lt;/strong&gt; kiểm tra xem nhóm có dự báo \(p = 0.70\) có thực sự xảy ra khoảng \(70\%\) hay không — yếu tố quan trọng cho ra quyết định dựa trên chi phí.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thước đo xác suất nghiêm ngặt (Proper Scoring Rules):&lt;/strong&gt; Brier score \(\frac{1}{n}\sum (y_i - \hat p_i)^2\) và Log-loss (tương ứng Deviance / ELPD) đánh giá đồng thời cả khả năng phân biệt lẫn độ hiệu chỉnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chẩn đoán riêng cho GLM (Deviance Residuals &amp;amp; PPC):&lt;/strong&gt; Đối với Poisson/Negative Binomial, phần dư Pearson \(r_i = (y_i - \hat\lambda_i)/\sqrt{\hat\lambda_i}\) và Posterior Predictive Checks (kiểm tra tỷ lệ số 0, phương sai/trung bình, giá trị cực đại) giúp phát hiện chính xác quá phân tán hoặc thừa số 0 (&lt;em&gt;zero-inflation&lt;/em&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-đánh-giá-glms-khác-gì-so-với-hồi-quy-tuyến-tính&quot;&gt;Giới thiệu: Đánh giá GLMs khác gì so với hồi quy tuyến tính&lt;/h2&gt;

&lt;p&gt;Với hồi quy tuyến tính, ta thường dùng các chỉ số như \(R^2\), RMSE hay biểu đồ phần dư (residual) để kiểm tra mức độ khớp dữ liệu. Khi chuyển sang GLMs, tiêu chí đánh giá phải thay đổi theo loại biến kết quả. Với &lt;strong&gt;biến kết quả nhị phân (binary outcomes)&lt;/strong&gt;, ta quan tâm đến khả năng phân biệt lớp và độ hiệu chỉnh xác suất nên thường dùng accuracy, đường cong ROC hay calibration. Với &lt;strong&gt;biến kết quả đếm (count outcomes)&lt;/strong&gt;, ta cần kiểm tra mức độ khớp của phân phối, deviance và dấu hiệu &lt;strong&gt;quá phân tán (overdispersion)&lt;/strong&gt;. Dù vậy, có một nguyên tắc chung cho mọi GLM: luôn thực hiện &lt;strong&gt;kiểm tra dự báo hậu nghiệm (posterior predictive checks)&lt;/strong&gt; để so sánh dữ liệu mô hình sinh ra với dữ liệu thực tế.&lt;/p&gt;

&lt;h2 id=&quot;1-đánh-giá-hồi-quy-logistic&quot;&gt;1. Đánh giá hồi quy logistic&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/model_evaluation_glm.png&quot; alt=&quot;Model Evaluation for GLM&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;11-ma-trận-nhầm-lẫn-confusion-matrix&quot;&gt;1.1. Ma trận nhầm lẫn (Confusion Matrix)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sklearn.metrics&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;confusion_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;roc_curve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;auc&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate binary data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Fit logistic model
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logistic_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Deterministic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;invlogit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Bernoulli&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Posterior predictions
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Confusion matrices với different thresholds
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;thresholds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;thresh&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;thresholds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Predict
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;thresh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Confusion matrix
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;confusion_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;im&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;imshow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Blues&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vmin&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vmax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xticks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_yticks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xticklabels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pred 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pred 1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_yticklabels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True 1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Threshold = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;thresh&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Confusion Matrix&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                          &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Add text
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;va&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                            &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                            &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;white&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Compute metrics
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ravel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sensitivity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;if &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Recall, TPR
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;specificity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;if &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# TNR
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;precision&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;if &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Metrics text
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;metrics_text&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Accuracy: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Sensitivity: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sensitivity&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Specificity: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;specificity&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Precision: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;precision&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;off&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;metrics_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;va&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;family&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;monospace&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;bbox&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;boxstyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;facecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lightblue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;CLASSIFICATION METRICS&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Confusion Matrix Components:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  TN (True Negative): Correctly predicted 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  FP (False Positive): Incorrectly predicted 1 (Type I error)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  FN (False Negative): Incorrectly predicted 0 (Type II error)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  TP (True Positive): Correctly predicted 1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Metrics:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Accuracy = (TP + TN) / Total&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Sensitivity (Recall) = TP / (TP + FN)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Specificity = TN / (TN + FP)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Precision = TP / (TP + FP)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;111-đánh-giá-theo-quy-tắc-quyết-định-thay-vì-cố-định-ngưỡng-05&quot;&gt;1.1.1. Đánh giá theo quy tắc quyết định thay vì cố định ngưỡng 0.5&lt;/h3&gt;

&lt;p&gt;Trong phân lớp Bayes, ngưỡng 0.5 chỉ hợp lý khi chi phí của hai loại sai lầm gần như bằng nhau. Khi chi phí khác nhau, ta nên chọn ngưỡng dựa trên rủi ro kỳ vọng (expected risk).&lt;/p&gt;

&lt;p&gt;Xét bài toán hai lớp (dương tính/âm tính) với chi phí của &lt;strong&gt;dương tính giả (false positive)&lt;/strong&gt; là \(C_{FP}\) và chi phí của &lt;strong&gt;âm tính giả (false negative)&lt;/strong&gt; là \(C_{FN}\). Quy tắc tối ưu (khi không có tùy chọn từ chối) là dự đoán dương tính khi:&lt;/p&gt;

\[P(y=1\mid x) &amp;gt; \frac{C_{FP}}{C_{FP}+C_{FN}}.\]

&lt;p&gt;Nếu bổ sung hành động từ chối (reject) với chi phí \(C_R\), ta chỉ đưa ra quyết định phân lớp khi rủi ro của quyết định đó nhỏ hơn \(C_R\). Về mặt thực hành, ma trận nhầm lẫn không phải là một bảng đếm tách rời ngữ cảnh: một ngưỡng chỉ có ý nghĩa khi gắn với chi phí thực tế của từng loại sai lầm, bởi trong nhiều ứng dụng, âm tính giả nghiêm trọng hơn nhiều so với dương tính giả hoặc ngược lại.&lt;/p&gt;

&lt;h3 id=&quot;112-ví-dụ-cụ-thể-ngưỡng-05-có-thể-làm-bỏ-sót-ca-quan-trọng&quot;&gt;1.1.2. Ví dụ cụ thể: Ngưỡng 0.5 có thể làm bỏ sót ca quan trọng&lt;/h3&gt;

&lt;p&gt;Giả sử trong bài toán sàng lọc bệnh hiếm, chi phí bỏ sót một ca bệnh cao gấp 9 lần chi phí báo động giả. Khi đó:&lt;/p&gt;

\[\text{threshold tối ưu}=\frac{C_{FP}}{C_{FP}+C_{FN}}=\frac{1}{1+9}=0.1\]

&lt;p&gt;Nghĩa là chỉ cần \(P(y=1\mid x)&amp;gt;0.1\), ta đã nên chọn phương án gửi đi kiểm tra bổ sung. Nếu mô hình trả về ba xác suất \(0.18\), \(0.32\) và \(0.65\) cho ba bệnh nhân, cả ba đều cần được theo dõi tiếp. Nếu áp dụng ngưỡng 0.5 một cách máy móc, hai người đầu sẽ bị xếp là âm tính dù rủi ro bỏ sót rất lớn. Ví dụ này cho thấy hồi quy logistic không chỉ dừng ở việc gán nhãn, mà cần sử dụng xác suất hậu nghiệm gắn với chi phí quyết định của bài toán.&lt;/p&gt;

&lt;h3 id=&quot;113-hệ-số-bayes-bayes-factor-như-thước-đo-bằng-chứng-ở-mức-mô-hình&quot;&gt;1.1.3. Hệ số Bayes (Bayes Factor) như thước đo bằng chứng ở mức mô hình&lt;/h3&gt;

&lt;p&gt;Bên cạnh các thước đo phân lớp theo nhãn, ta có thể so sánh mức độ ủng hộ của dữ liệu giữa hai mô hình hoặc giả thuyết bằng &lt;strong&gt;hệ số Bayes (Bayes factor)&lt;/strong&gt;:&lt;/p&gt;

\[BF_{10}=\frac{p(D\mid M_1)}{p(D\mid M_0)}.\]

&lt;p&gt;Khi \(BF_{10}&amp;gt;1\), dữ liệu ủng hộ \(M_1\) nhiều hơn \(M_0\); khi \(BF_{10}&amp;lt;1\), bằng chứng nghiêng về \(M_0\). Như vậy, Bayes factor bổ sung cho ROC/AUC ở một góc nhìn khác: ROC đánh giá năng lực phân biệt nhãn, còn Bayes factor đo mức bằng chứng tương đối giữa các mô hình hoặc giả thuyết.&lt;/p&gt;

&lt;h3 id=&quot;12-đường-cong-roc-roc-curve&quot;&gt;1.2. Đường cong ROC (ROC Curve)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Đường cong ROC&lt;/strong&gt; biểu diễn &lt;strong&gt;độ nhạy (Sensitivity)&lt;/strong&gt; theo \(1-\text{Specificity}\) khi quét qua toàn bộ các ngưỡng phân lớp có thể. Thay vì cố định sớm ở một ngưỡng, ROC cung cấp cái nhìn tổng thể về sự đánh đổi giữa khả năng phát hiện đúng ca dương tính và tỷ lệ báo động giả. &lt;strong&gt;AUC (Area Under the Curve)&lt;/strong&gt; tóm tắt toàn bộ đường cong đó bằng một con số: giá trị gần 0.5 tương ứng với phân lớp gần như ngẫu nhiên, còn giá trị tiến gần 1 cho thấy khả năng phân biệt tốt.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Compute ROC curve
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;thresholds_roc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;roc_curve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;auc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# ROC curve
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ROC (AUC = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Random (AUC = 0.5)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fill_between&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;False Positive Rate (1 - Specificity)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True Positive Rate (Sensitivity)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ROC CURVE&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Higher AUC = Better Model&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lower right&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Threshold selection
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;thresholds_roc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sensitivity (TPR)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;thresholds_roc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Specificity (TNR)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Threshold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;THRESHOLD SELECTION&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trade-off between Sensitivity &amp;amp; Specificity&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ROC CURVE INTERPRETATION&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;AUC = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Excellent discrimination&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Good discrimination&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Acceptable discrimination&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Poor discrimination&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;13-đồ-thị-hiệu-chỉnh-xác-suất-calibration-plot&quot;&gt;1.3. Đồ thị hiệu chỉnh xác suất (Calibration Plot)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Hiệu chỉnh xác suất (calibration)&lt;/strong&gt; trả lời một câu hỏi khác với ROC: khi mô hình dự đoán xác suất là 0.7, liệu trong thực tế có khoảng 70% trường hợp như vậy xảy ra hay không? Một mô hình có thể phân biệt lớp khá tốt nhưng vẫn hiệu chỉnh kém, tức các xác suất nó đưa ra bị đẩy quá cao hoặc quá thấp. Đồ thị hiệu chỉnh xác suất giúp đánh giá độ tin cậy của chính các xác suất dự báo, chứ không chỉ nhãn phân lớp cuối cùng.&lt;/p&gt;

&lt;h3 id=&quot;131-ví-dụ-cụ-thể-auc-tốt-nhưng-xác-suất-vẫn-lệch&quot;&gt;1.3.1. Ví dụ cụ thể: AUC tốt nhưng xác suất vẫn lệch&lt;/h3&gt;

&lt;p&gt;Giả sử mô hình dự đoán cho 10 bệnh nhân với xác suất quanh mức \(0.8\), nhưng thực tế chỉ có 5 người dương tính. Mô hình vẫn có thể đạt ROC/AUC khá tốt nếu 5 người mắc bệnh nhận xác suất cao hơn phần lớn người không mắc bệnh. Tuy nhiên, xét về calibration, mô hình đang quá tự tin: dự báo “80%” nhưng tần suất thực tế chỉ khoảng “50%”.&lt;/p&gt;

&lt;p&gt;Tương tự, nếu một nhóm khác được dự báo quanh mức \(0.2\) nhưng thực tế có tới \(0.35\) số ca xảy ra, mô hình lại đang đánh giá thấp rủi ro. Như vậy, ROC trả lời câu hỏi “mô hình có xếp hạng đúng người có rủi ro cao hơn không?”, còn calibration trả lời câu hỏi “con số xác suất mô hình đưa ra có phản ánh đúng tần suất thực tế hay không?”.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Calibration plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_bins&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_bins&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;bin_centers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;observed_freq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;predicted_prob&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_bins&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;observed_freq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;predicted_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Calibration plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predicted_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed_freq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;150&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Binned data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Perfect calibration&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted Probability&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed Frequency&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;CALIBRATION PLOT&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Do predictions match reality?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Histogram of predicted probabilities
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted Probability&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Frequency&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DISTRIBUTION OF PREDICTIONS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Well-spread or concentrated?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;video-ngắn-đánh-giá-glm-hiệu-chỉnh-xác-suất-calibration--ngưỡng-quyết-định&quot;&gt;Video ngắn: Đánh giá GLM: Hiệu chỉnh Xác suất (Calibration) &amp;amp; Ngưỡng Quyết định&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch06-03a-roc-vs-calibration-threshold.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 17 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): phân biệt đường cong tự tin thái quá (AUC cao nhưng lệch xác suất) với đường hiệu chỉnh chuẩn và cách chọn ngưỡng tối ưu theo chi phí sai lầm.&lt;/p&gt;

&lt;h2 id=&quot;2-đánh-giá-hồi-quy-poisson&quot;&gt;2. Đánh giá hồi quy Poisson&lt;/h2&gt;

&lt;h3 id=&quot;21-độ-lệch-mô-hình-deviance&quot;&gt;2.1. Độ lệch mô hình (Deviance)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Deviance&lt;/strong&gt; là thước đo mức độ khớp của mô hình trong họ GLM. Theo trực giác, deviance đo khoảng cách giữa mô hình đang xét với một mô hình bão hòa (saturated model) khớp hoàn hảo dữ liệu. Giá trị deviance càng nhỏ thì mô hình càng gần mức khớp lý tưởng đó:&lt;/p&gt;

\[D = -2 \log \frac{L(\text{model})}{L(\text{saturated})}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Generate count data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;150&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Fit Poisson model
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_count_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_count_z&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambda_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Deterministic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lambda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trace_poisson&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                             &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Posterior predictions
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lambda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compute deviance
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy.stats&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_dist&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;log_lik_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_dist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logpmf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;log_lik_saturated&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_dist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logpmf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Perfect fit
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deviance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_lik_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_lik_saturated&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POISSON REGRESSION EVALUATION&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Deviance: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deviance&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (Lower = better fit)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Check overdispersion
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Overdispersion check:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Observed mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Observed variance: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Variance/Mean ratio: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Overdispersion detected!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Poisson assumption reasonable&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;211-ví-dụ-cụ-thể-trung-bình-khớp-nhưng-phương-sai-báo-động&quot;&gt;2.1.1. Ví dụ cụ thể: Trung bình khớp nhưng phương sai báo động&lt;/h3&gt;

&lt;p&gt;Giả sử số cuộc gọi hỗ trợ trong 7 ngày liên tiếp là: \(2, 3, 4, 2, 3, 4, 18\). Trung bình của chuỗi này vào khoảng \(5.1\), nên một mô hình Poisson với \(\lambda\) quanh mức 5 có vẻ khớp với giá trị trung bình. Tuy nhiên, chuỗi số liệu cho thấy sự bất thường rõ rệt: sáu ngày đầu khá thấp, còn một ngày vọt lên 18.&lt;/p&gt;

&lt;p&gt;Trong tình huống này, chỉ nhìn vào trung bình là không đủ để kết luận mô hình tốt. Nếu phân phối dự báo hậu nghiệm sinh ra các tập dữ liệu có trung bình gần 5 nhưng phương sai và giá trị cực đại nhỏ hơn dữ liệu thực rất nhiều, thì deviance, biểu đồ phần dư và PPC sẽ cùng chỉ ra rằng mô hình quá hẹp so với dữ liệu. Đây là dấu hiệu điển hình của hiện tượng quá phân tán (overdispersion) hoặc của một nguồn biến thiên chưa được đưa vào mô hình.&lt;/p&gt;

&lt;h3 id=&quot;22-biểu-đồ-phần-dư-residual-plots&quot;&gt;2.2. Biểu đồ phần dư (Residual Plots)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Residuals
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;residuals&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;residuals&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Raw residuals
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted λ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Raw Residuals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RAW RESIDUALS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Should be random around 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Pearson residuals
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted λ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pearson Residuals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PEARSON RESIDUALS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Standardized (should be in [-2, 2])&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# QQ plot
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy_stats&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;scipy_stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;probplot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dist&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Q-Q PLOT&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Check normality of residuals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Histogram of residuals
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy_stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Standard Normal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pearson Residuals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RESIDUAL DISTRIBUTION&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Compare to Normal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;3-kiểm-tra-dự-báo-hậu-nghiệm-cho-glms&quot;&gt;3. Kiểm tra dự báo hậu nghiệm cho GLMs&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# PPC for Poisson
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ppc_poisson&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample_posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ppc_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Distribution comparison
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                   &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.02&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Count&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PPC: DISTRIBUTION&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed vs Predicted&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Mean check
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pred_means&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred_means&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_mean&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean of Predicted Data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PPC: MEAN&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Does model capture mean?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Variance check
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pred_vars&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred_vars&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_var&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Variance of Predicted Data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PPC: VARIANCE&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Does model capture variance?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Max check
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pred_maxs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred_maxs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_max&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Max of Predicted Data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PPC: MAXIMUM&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Does model capture extremes?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;thử-nghiệm-kiểm-tra-dự-báo-hậu-nghiệm-cho-glm&quot;&gt;Thử nghiệm: Kiểm tra dự báo hậu nghiệm cho GLM&lt;/h3&gt;

&lt;p&gt;Quan sát độ hiệu chuẩn theo nhóm cho hồi quy logistic và thống kê số giá trị 0 cho hồi quy Poisson để so sánh mô hình đặc tả đúng với mô hình đặc tả sai.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;glmppc-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;logistic&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;Đánh giá GLM không thể chỉ sử dụng lại bộ công cụ của hồi quy tuyến tính. Với hồi quy logistic, cần xem xét đồng thời ma trận nhầm lẫn, các thước đo phân lớp như sensitivity và specificity, năng lực phân biệt tổng quát qua ROC/AUC, và độ tin cậy của xác suất dự báo qua đồ thị hiệu chỉnh xác suất. Với hồi quy Poisson, trọng tâm chuyển sang deviance, dấu hiệu quá phân tán và biểu đồ phần dư để phát hiện các cấu trúc còn bị bỏ sót. Với mọi GLM, &lt;strong&gt;kiểm tra dự báo hậu nghiệm (posterior predictive checks)&lt;/strong&gt; vẫn là bước kiểm chứng quan trọng nhất để xem dữ liệu mô hình sinh ra có tái hiện được các đặc điểm chính của dữ liệu thực hay không.&lt;/p&gt;

&lt;p&gt;Mỗi loại biến kết quả đòi hỏi bộ tiêu chí đánh giá tương ứng, và không có một chỉ số đơn lẻ nào đủ để kết luận mô hình tốt hay xấu. Cách làm hợp lý là kết hợp các thước đo chuyên biệt với kiểm tra dự báo hậu nghiệm để đánh giá mô hình từ nhiều góc độ.&lt;/p&gt;

&lt;p&gt;Kết thúc Chương 06 về các mô hình tuyến tính tổng quát (GLMs): hồi quy logistic, hồi quy Poisson và đánh giá mô hình.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-đọc-brier-score-calibration-và-phần-dư-pearson-bằng-tay&quot;&gt;Giải thích: Đọc Brier Score, Calibration và Phần dư Pearson bằng tay&lt;/h2&gt;

&lt;p&gt;Để không bao giờ bị đánh lừa bởi một chỉ số đơn lẻ (như accuracy hay AUC), hãy kiểm tra theo 4 bước sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra khả năng phân biệt (ROC-AUC / PR-AUC):&lt;/strong&gt; Đặc biệt dùng PR-AUC khi lớp dương tính hiếm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra độ hiệu chỉnh (Calibration):&lt;/strong&gt; Chia dự báo thành các nhóm xác suất và so sánh trung bình dự báo với tần suất thật.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính thước đo tổng hợp (Brier Score / Log-Loss / LOO):&lt;/strong&gt; So sánh khách quan giữa các mô hình GLM cạnh tranh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chạy PPC cho đặc trưng miền dữ liệu:&lt;/strong&gt; Với Poisson, luôn kiểm tra tỷ lệ quan sát bằng 0 và tỷ số phương sai/trung bình.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-brier-score-và-độ-hiệu-chỉnh-trên-4-dự-báo-nhị-phân&quot;&gt;Ví dụ tính toán làm từng bước: Brier Score và Độ hiệu chỉnh trên 4 dự báo nhị phân&lt;/h3&gt;

&lt;p&gt;Xét 4 ca dự báo xác suất của hai mô hình logistic trên cùng tập nhãn thật \(y = (1, 1, 0, 0)\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình A (Hiệu chỉnh tốt):&lt;/strong&gt; \(\hat p_A = (0.8, 0.7, 0.3, 0.2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình B (Đoán đúng thứ tự — cùng AUC = 1.0 — nhưng hiệu chỉnh kém):&lt;/strong&gt; \(\hat p_B = (0.55, 0.52, 0.48, 0.45)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Quan sát&lt;/th&gt;
      &lt;th&gt;Nhãn \(y_i\)&lt;/th&gt;
      &lt;th&gt;\((y_i - \hat p_{A,i})^2\)&lt;/th&gt;
      &lt;th&gt;\((y_i - \hat p_{B,i})^2\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;\(1\)&lt;/td&gt;
      &lt;td&gt;\((1 - 0.8)^2 = 0.04\)&lt;/td&gt;
      &lt;td&gt;\((1 - 0.55)^2 = 0.2025\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;\(1\)&lt;/td&gt;
      &lt;td&gt;\((1 - 0.7)^2 = 0.09\)&lt;/td&gt;
      &lt;td&gt;\((1 - 0.52)^2 = 0.2304\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;\(0\)&lt;/td&gt;
      &lt;td&gt;\((0 - 0.3)^2 = 0.09\)&lt;/td&gt;
      &lt;td&gt;\((0 - 0.48)^2 = 0.2304\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;\(0\)&lt;/td&gt;
      &lt;td&gt;\((0 - 0.2)^2 = 0.04\)&lt;/td&gt;
      &lt;td&gt;\((0 - 0.45)^2 = 0.2025\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Brier Score (trung bình)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(0.26 / 4 = 0.0650\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(0.8658 / 4 = 0.2165\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Cả hai mô hình đều đạt \(\text{AUC} = 1.00\) và \(\text{Accuracy} = 100\%\) ở ngưỡng \(0.5\), nhưng Brier Score lập tức vạch rõ Mô hình A vượt trội hơn gấp &lt;strong&gt;3.3 lần&lt;/strong&gt; (\(0.0650\) so với \(0.2165\)) nhờ dự báo xác suất sắc nét và hiệu chỉnh tốt hơn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Chỉ nhìn AUC cao (ví dụ \(0.92\)) rồi tin rằng xác suất đầu ra có thể nhân trực tiếp với lợi nhuận kỳ vọng. Nếu mô hình bị lệch calibration, quyết định tài chính dựa trên ngưỡng xác suất vẫn sẽ sai.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Trong hồi quy Poisson, nếu quan sát \(y_i = 15\) khi mô hình dự báo \(\hat\lambda_i = 4\), phần dư Pearson là \((15 - 4)/\sqrt{4} = 5.5\) — vượt rất xa ngưỡng \(\pm 2\), cảnh báo ngay điểm bất thường hoặc hiện tượng quá phân tán.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Kdsp6soqA7o&quot;&gt;Machine Learning Fundamentals: The Confusion Matrix&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giới thiệu ma trận nhầm lẫn trước khi tính accuracy, phù hợp với phần đánh giá biến kết quả nhị phân.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=AunotauS5yI&quot;&gt;Probability Calibration : Data Science Concepts&lt;/a&gt; — ritvikmath, English. Giải thích hiệu chỉnh xác suất, minh họa rằng điểm phân lớp cao chưa bảo đảm xác suất dự báo đáng tin cậy.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JC56jS2gVUE&quot;&gt;Deviance Residuals&lt;/a&gt; — StatQuest with Josh Starmer, English. Trình bày phần dư deviance, hữu ích khi đánh giá mô hình GLM đếm hoặc logistic ngoài các chỉ số phân lớp.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 1&lt;/strong&gt;: Khớp một mô hình hồi quy logistic, tính đường cong ROC và chỉ số AUC, sau đó diễn giải kết quả.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 2&lt;/strong&gt;: Vẽ đồ thị hiệu chỉnh xác suất (calibration plot) và đánh giá xem mô hình đã được hiệu chỉnh tốt chưa.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 3&lt;/strong&gt;: Khớp một mô hình hồi quy Poisson, kiểm tra hiện tượng quá phân tán (overdispersion) và nêu hướng xử lý nếu hiện tượng này xuất hiện.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 4&lt;/strong&gt;: Thực hiện kiểm tra dự báo hậu nghiệm (PPC) đầy đủ cho mô hình GLM trên các thống kê: trung bình, phương sai, giá trị cực đại và phân phối tổng thể.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 5&lt;/strong&gt;: So sánh hai mô hình hồi quy logistic bằng đường cong ROC và xác định mô hình nào tốt hơn.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., et al. (2020).&lt;/strong&gt; &lt;em&gt;Regression and Other Stories&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 11: Assumptions, diagnostics, and model evaluation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 7: Ulysses’ Compass (Model Comparison)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Chương tiếp theo: &lt;a href=&quot;/contents/vi/chapter07/&quot;&gt;Chapter 07: Regularization&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 6.2: Poisson Regression - Count Data</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter06/06_02_poisson_regression/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter06/06_02_poisson_regression</id>
   <content type="html">&lt;p&gt;Năm 1898, nhà thống kê Ladislaus Bortkiewicz công bố một nghiên cứu kỳ lạ nhưng kinh điển: đếm số binh sĩ Phổ tử vong vì bị ngựa đá trong từng quân đoàn suốt 20 năm. Các con số thu được — toàn số nguyên không âm \(0, 1, 2, 3, 4\) — khớp khít một cách đáng kinh ngạc với phân phối do Siméon Denis Poisson tìm ra trước đó nửa thế kỷ. Ngày nay, cùng cấu trúc dữ liệu đếm ấy xuất hiện khắp nơi: số ca cấp cứu mỗi ngày, số lỗi phần mềm trên mỗi nghìn dòng mã, hay số đơn hàng đặt mỗi giờ.&lt;/p&gt;

&lt;p&gt;Bài học này mở rộng khung GLM sang &lt;strong&gt;hồi quy Poisson Bayes&lt;/strong&gt; với hàm liên kết logarit, đồng thời chỉ ra cách chẩn đoán và khắc phục hiện tượng &lt;strong&gt;quá phân tán (overdispersion)&lt;/strong&gt; bằng phân phối Negative Binomial.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành bài học này, bạn sẽ hiểu &lt;strong&gt;hồi quy Poisson (Poisson regression)&lt;/strong&gt; như mô hình tiêu chuẩn cho &lt;strong&gt;dữ liệu đếm (count data)&lt;/strong&gt;, tức các dữ liệu ghi nhận số lần một sự kiện xảy ra. Bạn sẽ thấy vì sao hồi quy tuyến tính không phù hợp khi biến kết quả chỉ nhận các số nguyên không âm, vì sao &lt;strong&gt;hàm liên kết log (log link function)&lt;/strong&gt; giúp mô hình tạo ra dự đoán hợp lệ, và vì sao hệ số của mô hình nên được diễn giải thông qua &lt;strong&gt;tỷ số tốc độ (rate ratio)&lt;/strong&gt; thay vì hiệu số cộng đơn giản. Đây là mô hình GLM quan trọng thứ hai sau hồi quy logistic.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hàm-liên-kết-log-exposure-offset-và-bài-toán-quá-phân-tán&quot;&gt;Kiến thức cần nhớ: Hàm liên kết Log, Exposure Offset và Bài toán Quá phân tán&lt;/h2&gt;

&lt;p&gt;Làm chủ hồi quy dữ liệu đếm đòi hỏi nắm vững ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hàm liên kết Log &amp;amp; Tỷ số tốc độ (Rate Ratio):&lt;/strong&gt; Trong hồi quy Poisson, \(y_i \sim \text{Poisson}(\lambda_i)\) với \(\log \lambda_i = \alpha + \beta x_i \iff \lambda_i = e^{\alpha + \beta x_i}\). Hàm mũ bảo đảm tốc độ kỳ vọng \(\lambda_i\) luôn dương, và tăng \(x\) thêm 1 đơn vị sẽ &lt;strong&gt;nhân&lt;/strong&gt; số đếm kỳ vọng với \(e^\beta\) (&lt;em&gt;Incidence Rate Ratio — IRR&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biến bù phơi nhiễm (Exposure Offset):&lt;/strong&gt; Khi các quan sát có thời gian theo dõi hoặc quy mô khác nhau (ví dụ \(t_i\) ngày hay \(E_i\) nghìn người), ta mô hình hóa tốc độ trên một đơn vị phơi nhiễm: \(\log \lambda_i = \log(t_i) + \alpha + \beta x_i\) (hệ số của \(\log(t_i)\) cố định bằng 1).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quá phân tán (Overdispersion) &amp;amp; Negative Binomial:&lt;/strong&gt; Phân phối Poisson ép chặt \(\mathrm{Var}(y_i) = \mathbb{E}[y_i] = \lambda_i\). Dữ liệu thực tế thường có phương sai lớn hơn trung bình rất nhiều; nếu giữ nguyên Poisson, khoảng tin cậy hậu nghiệm sẽ hẹp giả tạo. Chuyển sang &lt;strong&gt;Negative Binomial&lt;/strong&gt; (\(\mathrm{Var}(y) = \mu + \mu^2/\phi\)) giải quyết triệt để vấn đề này.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-dữ-liệu-đếm-trong-thực-tế&quot;&gt;Giới thiệu: Dữ liệu đếm trong thực tế&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Dữ liệu đếm (count data)&lt;/strong&gt; xuất hiện trong nhiều bối cảnh thực tế, chẳng hạn như số khách đến cửa hàng mỗi giờ, số email nhận được mỗi ngày, số tai nạn trên cao tốc mỗi tháng, số bàn thắng trong một trận bóng đá, hay số đột biến trên một đoạn DNA. Điểm chung của các biến này là \(y \in \{0,1,2,3,\ldots\}\): chúng là các số nguyên không âm, thường không có chặn trên cố định, và phương sai thường tăng khi giá trị trung bình tăng. Từ đó nảy sinh câu hỏi quen thuộc: liệu ta có thể dùng hồi quy tuyến tính cho loại dữ liệu này hay không?&lt;/p&gt;

&lt;h2 id=&quot;1-hạn-chế-của-hồi-quy-tuyến-tính-với-dữ-liệu-đếm&quot;&gt;1. Hạn chế của hồi quy tuyến tính với dữ liệu đếm&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/poisson_regression_basics.png&quot; alt=&quot;Poisson Regression Basics&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Khó khăn cơ bản của hồi quy tuyến tính trong bối cảnh này là mô hình có thể tạo ra dự đoán âm, trong khi số lần xảy ra của một sự kiện không thể nhỏ hơn 0. Hình minh họa cho thấy ở hình bên trái, đường hồi quy tuyến tính có thể đi vào vùng giá trị âm; còn ở hình bên phải, hồi quy Poisson dùng &lt;strong&gt;hàm liên kết log (log link)&lt;/strong&gt; để bảo đảm tham số cường độ \(\lambda\) luôn dương. Nói cách khác, thay vì dự đoán trực tiếp số đếm, ta mô hình hóa log của tốc độ kỳ vọng để đầu ra luôn phù hợp với bản chất dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;2-hồi-quy-poisson-dưới-góc-nhìn-mô-hình-sinh&quot;&gt;2. Hồi quy Poisson dưới góc nhìn mô hình sinh&lt;/h2&gt;

&lt;h3 id=&quot;21-hàm-liên-kết-log-log-link-function&quot;&gt;2.1. Hàm liên kết log (Log Link Function)&lt;/h3&gt;

&lt;p&gt;Ý tưởng cốt lõi của hồi quy Poisson là giữ phần tuyến tính ở bên trong, nhưng dùng &lt;strong&gt;hàm liên kết log&lt;/strong&gt; để bảo đảm tốc độ kỳ vọng \(\lambda\) luôn lớn hơn 0.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hàm liên kết log&lt;/strong&gt;:
\(\log(\lambda) = \alpha + \beta x\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hàm ngược (hàm mũ)&lt;/strong&gt;:
\(\lambda = e^{\alpha + \beta x}\)&lt;/p&gt;

&lt;h3 id=&quot;22-câu-chuyện-sinh-dữ-liệu-generative-story&quot;&gt;2.2. Câu chuyện sinh dữ liệu (Generative Story)&lt;/h3&gt;

&lt;p&gt;Theo ngôn ngữ &lt;strong&gt;câu chuyện sinh dữ liệu (generative story)&lt;/strong&gt;, mô hình gồm ba bước. Từ biến dự báo \(x\), ta tạo ra đại lượng tuyến tính \(\eta=\alpha+\beta x\). Đại lượng này đi qua hàm mũ để cho tốc độ kỳ vọng \(\lambda=\exp(\eta)\). Cuối cùng, số đếm quan sát được sinh ra từ phân phối Poisson, tức \(y\sim\text{Poisson}(\lambda)\). Việc tách rõ ba bước này cho thấy mô hình vừa giữ được cấu trúc tuyến tính thuận tiện cho suy luận, vừa tôn trọng bản chất xác suất của dữ liệu đếm.&lt;/p&gt;

&lt;p&gt;Phân phối Poisson có dạng:
\(P(y = k \mid \lambda) = \frac{\lambda^k e^{-\lambda}}{k!}\)&lt;/p&gt;

&lt;p&gt;Điểm đặc trưng của phân phối này là giá trị trung bình và phương sai đều bằng \(\lambda\); tính chất này được gọi là &lt;strong&gt;đồng phân tán (equidispersion)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/exponential_function_parameters.png&quot; alt=&quot;Exponential Function Parameters&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Hình minh họa cho thấy vai trò của từng tham số trong hàm mũ. Ở hình bên trái, hàm cơ bản \(\lambda=e^\eta\) luôn dương và đi qua điểm \(\lambda=1\) khi \(\eta=0\), thể hiện mức tốc độ nền. Ở hình giữa, thay đổi &lt;strong&gt;hệ số chặn (intercept)&lt;/strong&gt; \(\alpha\) làm dịch chuyển toàn bộ đường cong lên hoặc xuống, qua đó thay đổi mức nền của tốc độ. Ở hình bên phải, thay đổi &lt;strong&gt;độ dốc (slope)&lt;/strong&gt; \(\beta\) làm tốc độ tăng nhanh hơn hoặc chậm hơn theo \(x\), phản ánh mức độ liên hệ giữa biến dự báo và cường độ xảy ra sự kiện.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-hồi-quy-poisson-hàm-mũ-eαβx--cảnh-báo-quá-phân-tán&quot;&gt;Video ngắn: Hồi quy Poisson: Hàm Mũ e^(α+βx) &amp;amp; Cảnh báo Quá phân tán&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch06-02a-poisson-exp-link-overdispersion.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 17 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): minh họa hàm liên kết log giữ tốc độ λ &amp;gt; 0 và phát hiện dữ liệu thực bị quá phân tán văng rộng hơn Poisson để chuyển sang Negative Binomial.&lt;/p&gt;

&lt;h2 id=&quot;3-hồi-quy-poisson-bayes-trong-pymc&quot;&gt;3. Hồi quy Poisson Bayes trong PyMC&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;150&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Standardize predictor
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Bayesian Poisson regression
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Priors
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# log(λ) ~ 2 → λ ~ 7
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Linear predictor
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Exponential transformation
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;lambda_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Deterministic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lambda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Likelihood
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Sample
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Summary
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR SUMMARY&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize posteriors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot_posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;suptitle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior Distributions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.05&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Trace plots
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;compact&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
             &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;suptitle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trace Plots (Check Convergence)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;thử-nghiệm-hậu-nghiệm-của-hồi-quy-poisson-và-tỷ-số-tốc-độ&quot;&gt;Thử nghiệm: Hậu nghiệm của hồi quy Poisson và tỷ số tốc độ&lt;/h3&gt;

&lt;p&gt;Thêm từng điểm dữ liệu đếm để quan sát bó đường \(\lambda(x)\) và tỷ số tốc độ \(\exp(b)\) thu hẹp dần.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;glm-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;poisson&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-diễn-giải-hệ-số-tỷ-số-tốc-độ-rate-ratios&quot;&gt;4. Diễn giải hệ số: Tỷ số tốc độ (Rate Ratios)&lt;/h2&gt;

&lt;h3 id=&quot;41-tỷ-số-tốc-độ&quot;&gt;4.1. Tỷ số tốc độ&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Trên thang log&lt;/strong&gt;:
\(\log(\lambda) = \alpha + \beta x\)&lt;/p&gt;

&lt;p&gt;Trên thang log, mỗi khi \(x\) tăng thêm 1 đơn vị thì log của tốc độ kỳ vọng tăng thêm \(\beta\) đơn vị.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trên thang tốc độ gốc&lt;/strong&gt;:
\(\lambda = e^{\alpha + \beta x}\)&lt;/p&gt;

&lt;p&gt;Khi quay về thang gốc, tốc độ kỳ vọng được nhân với \(e^\beta\). Đại lượng \(e^\beta\) này là &lt;strong&gt;tỷ số tốc độ (rate ratio)&lt;/strong&gt;, và là cách diễn giải tự nhiên nhất cho hệ số của hồi quy Poisson.&lt;/p&gt;

&lt;h3 id=&quot;42-ví-dụ-cụ-thể-số-lượt-ghé-quán-tăng-ra-sao&quot;&gt;4.2. Ví dụ cụ thể: Số lượt ghé quán tăng ra sao&lt;/h3&gt;

&lt;p&gt;Giả sử trung bình hậu nghiệm của mô hình là:&lt;/p&gt;

\[\log(\lambda)=2.30 + 0.25x\]

&lt;p&gt;trong đó \(x\) là số chiến dịch quảng cáo đang chạy trong tuần. Khi đó:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Nếu \(x=0\) thì \(\lambda=e^{2.30}\approx 10\), nghĩa là quán kỳ vọng khoảng 10 lượt ghé mỗi ngày.&lt;/li&gt;
  &lt;li&gt;Nếu \(x=1\) thì \(\lambda=e^{2.55}\approx 12.8\).&lt;/li&gt;
  &lt;li&gt;Nếu \(x=2\) thì \(\lambda=e^{2.80}\approx 16.4\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ở đây \(e^{0.25}\approx 1.28\), nên mỗi khi thêm 1 chiến dịch quảng cáo, số lượt ghé kỳ vọng được nhân khoảng 1.28 lần, tức tăng gần 28%. Điều này không có nghĩa là số lượt ghé luôn tăng cố định 0.25 lượt hay 2.8 lượt. Vì tác động trong hồi quy Poisson có tính &lt;strong&gt;nhân&lt;/strong&gt; chứ không phải &lt;strong&gt;cộng&lt;/strong&gt;, mức tăng tuyệt đối phụ thuộc vào mức nền ban đầu: từ 10 lên 12.8 là tăng khoảng 2.8 lượt, còn từ 12.8 lên 16.4 là tăng khoảng 3.6 lượt.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Compute rate ratios
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RATE RATIO INTERPRETATION&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β (log scale): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Rate Ratio (e^β): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;95% CI: [&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
      &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;97.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Interpretation:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  1 SD increase in x → rate multiply by &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% increase in rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% decrease in rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Beta (log scale)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;skyblue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β (log scale)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;COEFFICIENT β&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Log Scale)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Rate ratio
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lightgreen&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Rate Ratio (e^β)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RATE RATIO&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Multiplicative Effect)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-kiểm-tra-dự-báo-hậu-nghiệm-posterior-predictive-checks&quot;&gt;5. Kiểm tra dự báo hậu nghiệm (Posterior Predictive Checks)&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Posterior predictive
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ppc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample_posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Predicted rates
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lambda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_lower&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_upper&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;97.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argsort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;40&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior mean λ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fill_between&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_lower&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_upper&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;95% CI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y (counts)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PREDICTED RATES&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;with Uncertainty&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Observed vs Predicted
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ppc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_pred_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Perfect prediction&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted E[y]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR PREDICTIVE CHECK&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed vs Predicted&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Distribution comparison
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                   &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y (counts)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DISTRIBUTION CHECK&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed vs PPC samples&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Residuals
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;residuals&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted λ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Residuals (y - λ)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RESIDUAL PLOT&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Check for patterns&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;6-quá-phân-tán-overdispersion-khi-phương-sai-lớn-hơn-trung-bình&quot;&gt;6. Quá phân tán (Overdispersion): Khi phương sai lớn hơn trung bình&lt;/h2&gt;

&lt;p&gt;Một giả định trung tâm của hồi quy Poisson là phương sai bằng trung bình. Trong dữ liệu thực, giả định này thường bị vi phạm khi phương sai lớn hơn trung bình, hiện tượng được gọi là &lt;strong&gt;quá phân tán (overdispersion)&lt;/strong&gt;. Khi đó, mô hình Poisson thường tỏ ra quá tự tin và đánh giá thấp độ bất định. Hai hướng xử lý phổ biến là dùng &lt;strong&gt;hồi quy nhị thức âm (Negative Binomial regression)&lt;/strong&gt; để cho phép phương sai lớn hơn trung bình một cách linh hoạt, hoặc dùng &lt;strong&gt;Zero-Inflated Poisson&lt;/strong&gt; khi dữ liệu có nhiều giá trị 0 vượt quá mức mô hình Poisson thông thường giải thích được.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Check overdispersion
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;OVERDISPERSION CHECK&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed data:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Variance: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Variance/Mean ratio: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;→ Overdispersion detected!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Consider Negative Binomial or Zero-Inflated models&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;→ Poisson assumption reasonable&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;thử-nghiệm-poisson-hay-negative-binomial&quot;&gt;Thử nghiệm: Poisson hay Negative Binomial?&lt;/h3&gt;

&lt;p&gt;Từ tỷ số phương sai/trung bình đến kiểm tra dự báo hậu nghiệm: mô hình Poisson bị bác bỏ, trong khi Negative Binomial nắm bắt được độ phân tán của dữ liệu.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;overdisp-explainer&quot; data-lang=&quot;vi&quot; data-data=&quot;nb&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;Hồi quy Poisson là mô hình tự nhiên cho dữ liệu đếm vì nó khắc phục trực tiếp điểm yếu của hồi quy tuyến tính: dự đoán tuyến tính có thể âm, còn số đếm thì không. Bằng cách dùng &lt;strong&gt;hàm liên kết log&lt;/strong&gt; để mô hình hóa \(\log(\lambda)=\alpha+\beta x\) rồi chuyển về \(\lambda\) trên thang gốc, hồi quy Poisson bảo đảm tốc độ kỳ vọng luôn dương. Hệ số của mô hình được diễn giải tốt nhất qua &lt;strong&gt;tỷ số tốc độ&lt;/strong&gt; \(e^\beta\), và giả định quan trọng nhất cần kiểm tra là phương sai có xấp xỉ trung bình hay không. Nếu dữ liệu bị quá phân tán, cần chuyển sang các mô hình linh hoạt hơn.&lt;/p&gt;

&lt;p&gt;Điểm cốt lõi cần nhớ là hàm liên kết log không chỉ là một phép biến đổi toán học, mà là cơ chế giúp phần tuyến tính của mô hình tương thích với bản chất của dữ liệu đếm và dữ liệu tốc độ.&lt;/p&gt;

&lt;p&gt;Bài tiếp theo: &lt;strong&gt;Đánh giá mô hình cho GLMs (Model Evaluation for GLMs)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tính-nhanh-tốc-độ-kỳ-vọng-offset-và-kiểm-tra-quá-phân-tán&quot;&gt;Giải thích: Tính nhanh tốc độ kỳ vọng, Offset và kiểm tra Quá phân tán&lt;/h2&gt;

&lt;p&gt;Khi xây dựng và đọc mô hình hồi quy Poisson Bayes, hãy kiểm tra chậm rãi 4 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính \(\log \lambda\) từ phương trình tuyến tính&lt;/strong&gt; (cộng thêm \(\log(\text{exposure})\) nếu độ dài quan sát khác nhau).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lấy hàm mũ \(\lambda = e^{\log\lambda}\)&lt;/strong&gt; để đọc số đếm kỳ vọng thực tế.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diễn giải \(e^\beta\) theo phần trăm thay đổi nhân tính:&lt;/strong&gt; Ví dụ \(e^\beta = 1.25\) nghĩa là tăng 1 đơn vị \(x\) làm số đếm kỳ vọng tăng thêm \(25\%\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra tỷ số Phương sai / Trung bình (và PPC):&lt;/strong&gt; Nếu phương sai phần dư lớn hơn trung bình rõ rệt, cần chuyển sang Negative Binomial.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-dự-báo-số-yêu-cầu-hỗ-trợ-kỹ-thuật-theo-số-người-dùng-mới&quot;&gt;Ví dụ tính toán làm từng bước: Dự báo số yêu cầu hỗ trợ kỹ thuật theo số người dùng mới&lt;/h3&gt;

&lt;p&gt;Giả sử mô hình hồi quy Poisson Bayes cho số ticket hỗ trợ mỗi ngày có \(\alpha = 1.5\) và \(\beta = 0.2\) (với \(x\) là số nghìn người dùng mới đăng ký trong ngày):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Số nghìn người dùng mới \(x\)&lt;/th&gt;
      &lt;th&gt;\(\log \lambda = 1.5 + 0.2x\)&lt;/th&gt;
      &lt;th&gt;Số ticket kỳ vọng \(\lambda = e^{\log\lambda}\)&lt;/th&gt;
      &lt;th&gt;Độ lệch chuẩn Poisson \(\sqrt{\lambda}\)&lt;/th&gt;
      &lt;th&gt;Tỷ số so với mức trước&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(x = 0\)&lt;/td&gt;
      &lt;td&gt;\(1.50\)&lt;/td&gt;
      &lt;td&gt;\(e^{1.5} \approx 4.48\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{4.48} \approx 2.12\)&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(x = 1\)&lt;/td&gt;
      &lt;td&gt;\(1.70\)&lt;/td&gt;
      &lt;td&gt;\(e^{1.7} \approx 5.47\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{5.47} \approx 2.34\)&lt;/td&gt;
      &lt;td&gt;\(e^{0.2} \approx 1.221\; (+22.1\%)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(x = 2\)&lt;/td&gt;
      &lt;td&gt;\(1.90\)&lt;/td&gt;
      &lt;td&gt;\(e^{1.9} \approx 6.69\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{6.69} \approx 2.59\)&lt;/td&gt;
      &lt;td&gt;\(e^{0.2} \approx 1.221\; (+22.1\%)\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Nếu cùng mức \(x = 2\) nhưng ta theo dõi trong \(t = 3\) ngày liên tiếp, chỉ cần cộng offset \(\ln(3) \approx 1.099\): \(\lambda_{\text{3 ngày}} = \exp(1.90 + \ln 3) = 3 \times 6.69 = 20.07\) ticket.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Đặt prior phẳng quá rộng (như \(\beta \sim \mathcal{N}(0, 10^2)\)) trong hồi quy Poisson. Vì đi qua hàm mũ \(e^{\beta x}\), chỉ cần \(\beta = 10\) và \(x = 2\) đã sinh ra \(\lambda = e^{20} \approx 4.85 \times 10^8\) gây tràn số khi lấy mẫu MCMC!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu quan sát thực tế tại \(x = 2\) có trung bình \(\bar y = 6.7\) nhưng phương sai mẫu \(s^2 = 28.0\) (gấp hơn 4 lần trung bình), đây là dấu hiệu rõ ràng của &lt;strong&gt;quá phân tán&lt;/strong&gt; — cần thay Poisson bằng Negative Binomial.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Obpz_Uvo2rQ&quot;&gt;Poisson regression - clearly explained&lt;/a&gt; — TileStats, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Giải thích hồi quy Poisson cho dữ liệu đếm và lý do đường thẳng tuyến tính không bảo đảm được giá trị không âm.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=uGKnoAw-PFQ&quot;&gt;Regression with Count Data: Poisson and Negative Binomial&lt;/a&gt; — Matthew E. Clapham, English. So sánh mô hình Poisson với Negative Binomial, hỗ trợ phần xử lý khi phương sai lớn hơn trung bình.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jokxu18egu0&quot;&gt;Statistical Rethinking 2023 - 10 - Counts &amp;amp; Hidden Confounds&lt;/a&gt; — Richard McElreath, English. Trình bày mô hình đếm cùng các biến nhiễu ẩn, phù hợp với cách tiếp cận Poisson như một GLM Bayes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 1&lt;/strong&gt;: Sinh dữ liệu đếm, khớp mô hình hồi quy Poisson và diễn giải tỷ số tốc độ (rate ratio).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 2&lt;/strong&gt;: So sánh dự đoán giữa hồi quy tuyến tính và hồi quy Poisson, sau đó trực quan hóa sự khác biệt.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 3&lt;/strong&gt;: Xây dựng mô hình hồi quy Poisson với nhiều biến dự báo và diễn giải từng hệ số.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 4&lt;/strong&gt;: Áp dụng trên dữ liệu thực để dự đoán số lượt khách ghé thăm từ các đặc trưng thời gian và thời tiết.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 5&lt;/strong&gt;: Kiểm tra hiện tượng quá phân tán (overdispersion); nếu có, thử xây dựng mô hình Negative Binomial để thay thế.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., &amp;amp; Hill, J. (2006).&lt;/strong&gt; &lt;em&gt;Data Analysis Using Regression and Multilevel/Hierarchical Models&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 6: Generalized linear models&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 11: God Spiked the Integers&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter06/06_03_model_evaluation_glm/&quot;&gt;6.3 Model Evaluation for GLMs&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 6.1: Logistic Regression - Binary Outcomes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter06/06_01_logistic_regression/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter06/06_01_logistic_regression</id>
   <content type="html">&lt;p&gt;Khi dự đoán một kết quả nhị phân — khách hàng có rời bỏ dịch vụ không, bệnh nhân có đáp ứng thuốc không, hay giao dịch có gian lận không — đường thẳng hồi quy tuyến tính quen thuộc lập tức rơi vào bế tắc: nó có thể dự đoán xác suất bằng \(-0.3\) hoặc \(1.4\), những con số vô nghĩa về mặt xác suất. Để giữ mọi dự báo nằm gọn trong đoạn \((0, 1)\) mà vẫn tận dụng được sức mạnh của tổ hợp tuyến tính, các nhà thống kê thế kỷ 20 (Berkson, Cox) đã bắc một chiếc cầu cong mượt mà mang tên &lt;strong&gt;hàm logit&lt;/strong&gt; — khai sinh mô hình &lt;strong&gt;hồi quy logistic&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Trong bối cảnh Bayes, hồi quy logistic không chỉ cho bạn một bộ hệ số tối ưu duy nhất, mà còn trả về phân phối hậu nghiệm đầy đủ của từng tỷ số odds (&lt;em&gt;odds ratio&lt;/em&gt;) và mọi dự báo xác suất, giúp định lượng rủi ro quyết định một cách minh bạch.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành bài học này, bạn sẽ hiểu &lt;strong&gt;hồi quy logistic (logistic regression)&lt;/strong&gt; như một mô hình nền tảng cho các &lt;strong&gt;biến kết quả nhị phân (binary outcomes)&lt;/strong&gt; như có/không, thành công/thất bại, hay 0/1. Trọng tâm của bài không chỉ là thay một công thức hồi quy khác, mà là hiểu vì sao hồi quy tuyến tính không phù hợp với dữ liệu nhị phân, vì sao ta cần &lt;strong&gt;hàm liên kết (link function)&lt;/strong&gt;, và vì sao hệ số của mô hình phải được diễn giải thông qua &lt;strong&gt;tỷ số odds (odds ratio)&lt;/strong&gt; thay vì theo trực giác tuyến tính thông thường. Đây cũng là bước mở đầu để tiếp cận họ &lt;strong&gt;mô hình tuyến tính tổng quát (Generalized Linear Models — GLMs)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hàm-liên-kết-logit-tỷ-số-odds-và-suy-diễn-bayes-phi-liên-hợp&quot;&gt;Kiến thức cần nhớ: Hàm liên kết Logit, Tỷ số Odds và Suy diễn Bayes phi liên hợp&lt;/h2&gt;

&lt;p&gt;Để làm chủ hồi quy logistic Bayes ở trình độ chuyên sâu, hãy kết nối ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cấu trúc GLM với liên kết Logit (Generalized Linear Model):&lt;/strong&gt; Hồi quy logistic gắn ba thành phần: (1) thành phần ngẫu nhiên \(y_i \sim \text{Bernoulli}(p_i)\), (2) bộ dự báo tuyến tính \(\eta_i = \alpha + \beta x_i \in (-\infty, +\infty)\), và (3) hàm liên kết logit \(\eta_i = \log\frac{p_i}{1 - p_i}\) cùng hàm nghịch đảo sigmoid \(p_i = \frac{1}{1 + e^{-\eta_i}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diễn giải hệ số trên thang Log-Odds và Odds Ratio:&lt;/strong&gt; Tăng \(x\) thêm 1 đơn vị làm &lt;strong&gt;log-odds&lt;/strong&gt; tăng cộng thêm \(\beta\), tương đương nhân &lt;strong&gt;odds&lt;/strong&gt; với \(e^\beta\). Tuy nhiên, mức thay đổi trên thang &lt;em&gt;xác suất&lt;/em&gt; \(\Delta p\) là phi tuyến và phụ thuộc vào giá trị nền của \(x\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prior thông tin yếu &amp;amp; Chia tách hoàn toàn (Complete Separation):&lt;/strong&gt; Khác với hồi quy tuyến tính Gaussian, hồi quy logistic không có prior liên hợp dạng đóng nên cần MCMC (NUTS trong PyMC). Đặt prior thông tin yếu như \(\beta \sim \mathcal{N}(0, 2.5^2)\) còn giải quyết triệt để hiện tượng chia tách hoàn toàn (&lt;em&gt;complete separation&lt;/em&gt;) vốn khiến MLE phát tán ra \(\pm\infty\).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-hạn-chế-của-hồi-quy-tuyến-tính-với-dữ-liệu-nhị-phân&quot;&gt;Giới thiệu: Hạn chế của hồi quy tuyến tính với dữ liệu nhị phân&lt;/h2&gt;

&lt;p&gt;Giả sử chúng ta muốn dự đoán một người có mua sản phẩm hay không, có vượt qua kỳ thi hay không, hoặc có mắc bệnh hay không. Trong tất cả các ví dụ này, biến kết quả chỉ nhận hai giá trị, nghĩa là \(y \in \{0,1\}\). Câu hỏi tự nhiên là liệu ta có thể dùng trực tiếp mô hình hồi quy tuyến tính quen thuộc hay không:&lt;/p&gt;

\[y = \alpha + \beta x + \epsilon\]

&lt;p&gt;Vấn đề xuất hiện ngay lập tức: hồi quy tuyến tính có thể dự đoán bất kỳ giá trị nào trên trục số thực, từ âm vô cùng đến dương vô cùng, trong khi xác suất bắt buộc phải nằm trong đoạn \([0,1]\). Do đó, ta cần một mô hình vẫn giữ được phần dự báo tuyến tính ở bên trong, nhưng có cơ chế biến đổi đầu ra thành một xác suất hợp lệ.&lt;/p&gt;

&lt;h2 id=&quot;1-vì-sao-hồi-quy-tuyến-tính-không-phù-hợp&quot;&gt;1. Vì sao hồi quy tuyến tính không phù hợp&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/logistic_regression_basics.png&quot; alt=&quot;Logistic Regression Basics&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Đối với dữ liệu nhị phân, hạn chế cốt lõi của hồi quy tuyến tính nằm ở chỗ mô hình này không bị ràng buộc để đầu ra là một xác suất. Ở hình bên trái, đường hồi quy tuyến tính có thể cho ra các dự đoán nhỏ hơn 0 hoặc lớn hơn 1, vốn không có ý nghĩa khi diễn giải dưới dạng xác suất. Ở hình bên phải, hồi quy logistic khắc phục nhược điểm này bằng cách dùng &lt;strong&gt;hàm logistic (logistic function)&lt;/strong&gt; để chuyển &lt;strong&gt;bộ dự báo tuyến tính (linear predictor)&lt;/strong&gt; thành xác suất hợp lệ, bảo đảm mọi giá trị dự đoán đều nằm trong đoạn \([0,1]\).&lt;/p&gt;

&lt;h2 id=&quot;2-hồi-quy-logistic-dưới-góc-nhìn-mô-hình-sinh&quot;&gt;2. Hồi quy logistic dưới góc nhìn mô hình sinh&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/link_functions_comparison.png&quot; alt=&quot;Link Functions Comparison&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;21-hàm-liên-kết-link-function&quot;&gt;2.1. Hàm liên kết (Link Function)&lt;/h3&gt;

&lt;p&gt;Ý tưởng trung tâm của hồi quy logistic là vẫn xây dựng một biểu thức tuyến tính ở tầng bên trong, sau đó đi qua một &lt;strong&gt;hàm liên kết (link function)&lt;/strong&gt; để bảo đảm đầu ra cuối cùng là xác suất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hàm liên kết logit (Logit link function)&lt;/strong&gt;:
\(\text{logit}(p) = \log\left(\frac{p}{1-p}\right) = \alpha + \beta x\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hàm ngược (hàm logistic)&lt;/strong&gt;:
\(p = \frac{1}{1 + e^{-(\alpha + \beta x)}} = \frac{e^{\alpha + \beta x}}{1 + e^{\alpha + \beta x}}\)&lt;/p&gt;

&lt;h3 id=&quot;22-câu-chuyện-sinh-dữ-liệu-generative-story&quot;&gt;2.2. Câu chuyện sinh dữ liệu (Generative Story)&lt;/h3&gt;

&lt;p&gt;Ta có thể đọc mô hình theo đúng tinh thần &lt;strong&gt;câu chuyện sinh dữ liệu (generative story)&lt;/strong&gt; qua ba bước. Trước hết, từ biến dự báo \(x\), ta tạo ra một đại lượng tuyến tính \(\eta=\alpha+\beta x\). Tiếp theo, đại lượng này được biến đổi qua hàm logistic để cho ra xác suất \(p=\text{logistic}(\eta)\). Cuối cùng, quan sát nhị phân được sinh ra theo phân phối Bernoulli, tức \(y\sim\text{Bernoulli}(p)\). Cách viết này cho thấy hồi quy logistic không phải là một mẹo biến đổi công thức rời rạc, mà là một mô hình xác suất hoàn chỉnh.&lt;/p&gt;

&lt;h3 id=&quot;23-quy-tắc-phân-lớp-bayes-từ-tiên-nghiệm-hợp-lý-đến-hậu-nghiệm&quot;&gt;2.3. Quy tắc phân lớp Bayes từ tiên nghiệm, hợp lý đến hậu nghiệm&lt;/h3&gt;

&lt;p&gt;Cho lớp \(c_i\) và đặc trưng \(x\), xác suất hậu nghiệm của lớp có dạng:&lt;/p&gt;

\[P(c_i\mid x)=\frac{P(x\mid c_i)P(c_i)}{\sum_j P(x\mid c_j)P(c_j)}
\propto P(x\mid c_i)P(c_i).\]

&lt;p&gt;Với hàm mất mát 0-1, quy tắc phân lớp tối ưu là chọn lớp có xác suất hậu nghiệm lớn nhất:&lt;/p&gt;

\[\hat c(x)=\arg\max_i\;P(c_i\mid x).\]

&lt;p&gt;Đây là cầu nối trực tiếp từ định lý Bayes (Chương 1–2) sang bài toán phân lớp.&lt;/p&gt;

&lt;h3 id=&quot;24-ví-dụ-về-dịch-chuyển-tiên-nghiệm-prior-shift-trong-phân-lớp-trái-cây&quot;&gt;2.4. Ví dụ về dịch chuyển tiên nghiệm (prior-shift) trong phân lớp trái cây&lt;/h3&gt;

&lt;p&gt;Giả sử có 2 lớp: Táo (\(c_1\)) và Cam (\(c_2\)). Cùng một đặc trưng \(x\) cho tỷ số hợp lý (likelihood ratio):&lt;/p&gt;

\[\frac{P(x\mid c_1)}{P(x\mid c_2)}=2.\]

&lt;p&gt;Trong &lt;strong&gt;bối cảnh A&lt;/strong&gt; (siêu thị miền ôn đới), xác suất tiên nghiệm là \(P(c_1)=0.8,\;P(c_2)=0.2\). Khi đó, tỷ số odds hậu nghiệm bằng:&lt;/p&gt;

\[\frac{P(c_1\mid x)}{P(c_2\mid x)}=2\times\frac{0.8}{0.2}=8.\]

&lt;p&gt;Trong &lt;strong&gt;bối cảnh B&lt;/strong&gt; (chợ miền nhiệt đới), xác suất tiên nghiệm là \(P(c_1)=0.2,\;P(c_2)=0.8\). Khi đó:&lt;/p&gt;

\[\frac{P(c_1\mid x)}{P(c_2\mid x)}=2\times\frac{0.2}{0.8}=0.5.\]

&lt;p&gt;Như vậy, cùng một bằng chứng cảm biến \(x\) nhưng sự thay đổi của xác suất tiên nghiệm giữa các lớp có thể làm đảo ngược hoàn toàn quyết định phân lớp.&lt;/p&gt;

&lt;h3 id=&quot;25-từ-hậu-nghiệm-sang-quy-tắc-quyết-định-tối-thiểu-rủi-ro&quot;&gt;2.5. Từ hậu nghiệm sang quy tắc quyết định tối thiểu rủi ro&lt;/h3&gt;

&lt;p&gt;Khi chi phí của các loại sai lầm không giống nhau, ta không nên dùng ngưỡng 0.5 cố định. Với tập hành động \(a\), quy tắc tối ưu là chọn hành động có rủi ro kỳ vọng thấp nhất:&lt;/p&gt;

\[a^*(x)=\arg\min_a\sum_i L(a,c_i)P(c_i\mid x).\]

&lt;h4 id=&quot;ví-dụ-hai-lớp-ba-hành-động-có-tùy-chọn-từ-chối-phân-lớp&quot;&gt;Ví dụ hai lớp, ba hành động (có tùy chọn từ chối phân lớp)&lt;/h4&gt;

&lt;p&gt;Xét hai trạng thái thật là \(c_1, c_2\) và ba hành động: chọn \(c_1\), chọn \(c_2\), hoặc &lt;strong&gt;từ chối (reject)&lt;/strong&gt; để đo thêm thông tin. Trong ví dụ minh họa này, ta giả sử &lt;strong&gt;ma trận mất mát (loss matrix)&lt;/strong&gt; được chọn đơn giản: dự đoán đúng chịu chi phí 0, dự đoán nhầm chịu chi phí 10, còn quyết định &lt;strong&gt;reject&lt;/strong&gt; chịu chi phí 3 do phải đo bổ sung hoặc chờ thêm dữ liệu.&lt;/p&gt;

&lt;p&gt;Giả sử xác suất hậu nghiệm tại một điểm \(x\) là \(P(c_1\mid x)=0.55,\;P(c_2\mid x)=0.45\). Khi đó, rủi ro kỳ vọng của từng hành động là:&lt;/p&gt;

\[R(a=c_1\mid x)=10\cdot 0.45=4.5,\]

\[R(a=c_2\mid x)=10\cdot 0.55=5.5,\]

\[R(a=\text{reject}\mid x)=3.\]

&lt;p&gt;Hành động tối ưu trong trường hợp này là reject vì có rủi ro kỳ vọng thấp nhất. Đây là ví dụ chuẩn về bài toán quyết định hai lớp, ba hành động.&lt;/p&gt;

&lt;h3 id=&quot;26-hàm-phân-biệt-discriminant-và-log-discriminant&quot;&gt;2.6. Hàm phân biệt (discriminant) và log-discriminant&lt;/h3&gt;

&lt;p&gt;Trong thực hành, ta thường so sánh trực tiếp hàm phân biệt dạng log:&lt;/p&gt;

\[g_i(x)=\log P(x\mid c_i)+\log P(c_i),\]

&lt;p&gt;và chọn lớp có giá trị \(g_i(x)\) lớn nhất. Vì hàm log là phép biến đổi đơn điệu tăng, tối đa hóa xác suất hậu nghiệm tương đương với tối đa hóa log-discriminant, đồng thời ổn định hơn về mặt tính toán số khi xác suất rất nhỏ.&lt;/p&gt;

&lt;h3 id=&quot;27-trường-hợp-gaussian-biên-quyết-định-tuyến-tính-hay-bậc-hai&quot;&gt;2.7. Trường hợp Gaussian: biên quyết định tuyến tính hay bậc hai&lt;/h3&gt;

&lt;p&gt;Nếu \(P(x\mid c_i)\) là phân phối Gaussian đa biến, hình dạng của biên quyết định phụ thuộc vào cấu trúc ma trận hiệp phương sai (covariance). Khi các lớp dùng &lt;strong&gt;chung một ma trận hiệp phương sai&lt;/strong&gt; với \(\Sigma_i=\Sigma\), biên quyết định sẽ là tuyến tính, gần với trực giác của phân tích biệt thức tuyến tính (LDA). Ngược lại, khi mỗi lớp có ma trận hiệp phương sai riêng (\(\Sigma_i\) khác nhau), biên quyết định thường có dạng bậc hai, gần với trực giác của QDA. Cách nhìn này nối trực tiếp quy tắc hậu nghiệm ở mức xác suất với hình học của biên phân lớp trong không gian đặc trưng.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/logistic_function_parameters.png&quot; alt=&quot;Logistic Function Parameters&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Hình trên giúp ta quan sát vai trò của các tham số trong hàm logistic. Ở hình bên trái, hàm \(p=\frac{1}{1+e^{-\eta}}\) có dạng chữ S, đi qua điểm \(p=0.5\) khi \(\eta=0\) và tiệm cận dần về 0 và 1 ở hai đầu. Ở hình giữa, thay đổi &lt;strong&gt;hệ số chặn (intercept)&lt;/strong&gt; \(\alpha\) chủ yếu làm đường cong dịch sang trái hoặc sang phải, phản ánh sự thay đổi của mức xác suất nền. Ở hình bên phải, thay đổi &lt;strong&gt;độ dốc (slope)&lt;/strong&gt; \(\beta\) làm đường cong thoải hơn hoặc dốc hơn, phản ánh độ mạnh của mối liên hệ giữa biến dự báo và xác suất của biến kết quả.&lt;/p&gt;

&lt;h2 id=&quot;3-hồi-quy-logistic-bayes-trong-pymc&quot;&gt;3. Hồi quy logistic Bayes trong PyMC&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Standardize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Bayesian logistic regression
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logistic_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Priors
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Weakly informative
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Linear predictor
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Logistic transformation
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Deterministic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;invlogit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Likelihood
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Bernoulli&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Sample
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                              &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Summary
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR SUMMARY&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize posteriors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot_posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ref_val&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;suptitle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior Distributions&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(True: α=1, β=0.8)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.05&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Trace plots
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;compact&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
             &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;suptitle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trace Plots (Check Convergence)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;thử-nghiệm-hậu-nghiệm-của-hồi-quy-logistic-là-cả-một-họ-đường-cong&quot;&gt;Thử nghiệm: Hậu nghiệm của hồi quy logistic là cả một họ đường cong&lt;/h3&gt;

&lt;p&gt;Thêm từng điểm dữ liệu để quan sát hậu nghiệm được tính chính xác trên lưới (a, b), từ đó đọc tỷ số odds exp(b) cùng khoảng tin cậy 95%.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;glm-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;logistic&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;video-ngắn-hồi-quy-logistic-ép-đường-thẳng-vào-sigmoid-0-1--tỷ-số-odds&quot;&gt;Video ngắn: Hồi quy Logistic: Ép Đường thẳng vào Sigmoid (0, 1) &amp;amp; Tỷ số Odds&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch06-01a-logistic-sigmoid-odds.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 22 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): đối chiếu đường thẳng OLS vượt biên [0, 1] với đường cong Sigmoid và trượt số giờ học từ 2h → 8h để theo dõi Log-Odds, Odds và xác suất qua môn.&lt;/p&gt;

&lt;h2 id=&quot;4-diễn-giải-hệ-số-tỷ-số-odds-odds-ratios&quot;&gt;4. Diễn giải hệ số: Tỷ số Odds (Odds Ratios)&lt;/h2&gt;

&lt;h3 id=&quot;41-odds-và-xác-suất&quot;&gt;4.1. Odds và xác suất&lt;/h3&gt;

&lt;p&gt;Để diễn giải hồi quy logistic đúng cách, ta cần phân biệt &lt;strong&gt;xác suất (probability)&lt;/strong&gt; với &lt;strong&gt;odds&lt;/strong&gt;. Xác suất được viết là \(p=P(y=1)\), còn odds được định nghĩa bởi \(\text{odds}=\frac{p}{1-p}\). Khi \(p=0.5\) thì odds bằng 1, nghĩa là hai khả năng cân bằng nhau; khi \(p=0.8\) thì odds bằng 4, tức khả năng xảy ra biến cố lớn gấp bốn lần khả năng không xảy ra; còn khi \(p=0.2\) thì odds chỉ bằng 0.25, nghĩa là khả năng không xảy ra biến cố cao hơn nhiều.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/odds_probability_relationship.png&quot; alt=&quot;Odds vs Probability&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Hình minh họa cho thấy mối liên hệ giữa xác suất, odds và &lt;strong&gt;log-odds&lt;/strong&gt;. Ở hình bên trái, khi xác suất tăng từ 0.2 lên 0.5 rồi 0.8, odds thay đổi phi tuyến từ 0.25 lên 1 rồi 4: odds nhỏ hơn 1 ứng với biến cố ít có khả năng xảy ra hơn, còn odds lớn hơn 1 ứng với biến cố dễ xảy ra hơn. Ở hình bên phải, khi lấy log của odds, điểm \(p=0.5\) tương ứng với 0, các xác suất nhỏ hơn 0.5 cho log-odds âm, và các xác suất lớn hơn 0.5 cho log-odds dương. Chính trên thang log-odds này, hồi quy logistic trở lại dạng tuyến tính quen thuộc: \(\text{logit}(p)=\alpha+\beta x\).&lt;/p&gt;

&lt;h3 id=&quot;42-diễn-giải-hệ-số-beta&quot;&gt;4.2. Diễn giải hệ số \(\beta\)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Trên thang log-odds&lt;/strong&gt;:
\(\log\left(\frac{p}{1-p}\right) = \alpha + \beta x\)&lt;/p&gt;

&lt;p&gt;Trên thang log-odds, mỗi khi \(x\) tăng thêm 1 đơn vị thì log-odds tăng thêm \(\beta\) đơn vị.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trên thang odds&lt;/strong&gt;:
\(\text{odds} = e^{\alpha + \beta x}\)&lt;/p&gt;

&lt;p&gt;Khi quay trở lại thang odds, mỗi lần \(x\) tăng 1 đơn vị thì odds được nhân với \(e^\beta\). Đại lượng \(e^\beta\) này là &lt;strong&gt;tỷ số odds (odds ratio)&lt;/strong&gt;, và cũng là cách diễn giải thực tế nhất cho hệ số của hồi quy logistic.&lt;/p&gt;

&lt;h3 id=&quot;43-ví-dụ-cụ-thể-từ-log-odds-sang-xác-suất-dự-đoán&quot;&gt;4.3. Ví dụ cụ thể: Từ log-odds sang xác suất dự đoán&lt;/h3&gt;

&lt;p&gt;Giả sử trung bình hậu nghiệm của mô hình cho phương trình:&lt;/p&gt;

\[\log\left(\frac{p}{1-p}\right) = -0.4 + 1.1x\]

&lt;p&gt;trong đó \(x\) là điểm đánh giá đã được chuẩn hóa. Ta có thể tính lần lượt theo từng giá trị của \(x\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Nếu \(x=0\) thì log-odds bằng \(-0.4\), suy ra odds là \(e^{-0.4}\approx 0.67\), nên xác suất là \(p=\frac{0.67}{1+0.67}\approx 0.40\).&lt;/li&gt;
  &lt;li&gt;Nếu \(x=1\) thì log-odds bằng \(0.7\), suy ra odds là \(e^{0.7}\approx 2.01\), nên xác suất tăng lên khoảng \(0.67\).&lt;/li&gt;
  &lt;li&gt;Nếu \(x=2\) thì log-odds bằng \(1.8\), suy ra odds là \(e^{1.8}\approx 6.05\), nên xác suất tăng lên khoảng \(0.86\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Một nhầm lẫn phổ biến là hiểu \(\beta=1.1\) thành xác suất tăng cố định 1.1 đơn vị hoặc 110 điểm phần trăm. Cách hiểu đúng là: mỗi khi \(x\) tăng thêm 1 đơn vị, &lt;strong&gt;odds&lt;/strong&gt; được nhân với \(e^{1.1}\approx 3\). Vì hồi quy logistic tuyến tính trên thang log-odds nhưng phi tuyến trên thang xác suất, cùng một mức tăng 1 đơn vị của \(x\) tạo ra mức thay đổi xác suất khác nhau tùy điểm xuất phát: từ \(0.40\) lên \(0.67\) là tăng khoảng 27 điểm phần trăm, còn từ \(0.67\) lên \(0.86\) là tăng khoảng 19 điểm phần trăm.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Compute odds ratios
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ODDS RATIO INTERPRETATION&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β (log-odds scale): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Odds Ratio (e^β): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;95% CI: [&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
      &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;97.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Interpretation:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  1 SD increase in x → odds multiply by &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% increase in odds&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% decrease in odds&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Beta (log-odds scale)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;skyblue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β (log-odds scale)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;COEFFICIENT β&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Log-Odds Scale)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Odds ratio
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lightgreen&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Odds Ratio (e^β)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ODDS RATIO&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Multiplicative Effect)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-kiểm-tra-dự-báo-hậu-nghiệm-posterior-predictive-checks&quot;&gt;5. Kiểm tra dự báo hậu nghiệm (Posterior Predictive Checks)&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Posterior predictive
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logistic_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ppc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample_posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Predicted probabilities
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_lower&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_upper&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;97.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sort by x for plotting
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argsort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior mean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fill_between&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_lower&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_upper&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;95% CI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;P(y=1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PREDICTED PROBABILITIES&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;with Uncertainty&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# PPC: Compare observed vs predicted
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ppc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_pred_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Perfect prediction&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted P(y=1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR PREDICTIVE CHECK&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed vs Predicted&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;Hồi quy logistic là lựa chọn tự nhiên khi biến kết quả chỉ có hai trạng thái. Thay vì dùng hồi quy tuyến tính vốn không thể bảo đảm dự đoán nằm trong đoạn \([0,1]\), mô hình sử dụng &lt;strong&gt;hàm liên kết logit&lt;/strong&gt; để nối cấu trúc tuyến tính bên trong với xác suất hợp lệ ở đầu ra. Phương trình cốt lõi có dạng \(\log\left(\frac{p}{1-p}\right)=\alpha+\beta x\), và hệ số nên được diễn giải qua &lt;strong&gt;tỷ số odds&lt;/strong&gt; \(e^\beta\) thay vì theo mức tăng cộng trên \(y\) như ở hồi quy tuyến tính. Trong PyMC, mô hình được triển khai trực tiếp bằng phân phối &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.Bernoulli&lt;/code&gt; kết hợp với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.math.invlogit&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Điểm cốt lõi cần nắm là tư duy của GLM: giữ lại phần dự báo tuyến tính, đồng thời chọn hàm liên kết và phân phối phù hợp để xử lý những biến kết quả không tuân theo giả định Gaussian.&lt;/p&gt;

&lt;p&gt;Bài tiếp theo: &lt;strong&gt;Hồi quy Poisson (Poisson Regression)&lt;/strong&gt; cho dữ liệu đếm.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-chuyển-đổi-chính-xác-giữa-log-odds-odds-và-xác-suất&quot;&gt;Giải thích: Chuyển đổi chính xác giữa Log-Odds, Odds và Xác suất&lt;/h2&gt;

&lt;p&gt;Lỗi phổ biến nhất khi đọc kết quả hồi quy logistic là diễn giải nhầm hệ số \(\beta\) hoặc \(e^\beta\) trực tiếp như mức tăng xác suất. Hãy đi chậm qua 4 bước quy đổi:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính bộ dự báo tuyến tính (log-odds):&lt;/strong&gt; \(\eta = \alpha + \beta x\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lấy mũ để sang tỷ số Odds:&lt;/strong&gt; \(\text{Odds} = e^\eta = \frac{p}{1-p}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuyển sang xác suất bằng hàm sigmoid:&lt;/strong&gt; \(p = \frac{\text{Odds}}{1 + \text{Odds}} = \frac{1}{1 + e^{-\eta}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính mức thay đổi xác suất thực tế:&lt;/strong&gt; So sánh trực tiếp \(p(x+1) - p(x)\) tại điểm quan tâm thay vì chỉ báo cáo \(e^\beta\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-tác-động-của-số-giờ-tự-học-lên-xác-suất-qua-môn&quot;&gt;Ví dụ tính toán làm từng bước: Tác động của số giờ tự học lên xác suất qua môn&lt;/h3&gt;

&lt;p&gt;Giả sử hậu nghiệm cho ra trung bình \(\alpha = -2.0\) và \(\beta = 0.8\) (mỗi giờ tự học thêm tăng log-odds thêm \(0.8\), tức Odds Ratio \(= e^{0.8} \approx 2.226\)). Hãy tính xác suất qua môn tại \(x = 1, 2, 3, 4\) giờ:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Số giờ học \(x\)&lt;/th&gt;
      &lt;th&gt;Log-odds \(\eta = -2.0 + 0.8x\)&lt;/th&gt;
      &lt;th&gt;\(\text{Odds} = e^\eta\)&lt;/th&gt;
      &lt;th&gt;Xác suất \(p = \frac{1}{1+e^{-\eta}}\)&lt;/th&gt;
      &lt;th&gt;Mức tăng \(\Delta p\) so với bước trước&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(x = 1\)&lt;/td&gt;
      &lt;td&gt;\(-1.2\)&lt;/td&gt;
      &lt;td&gt;\(0.301\)&lt;/td&gt;
      &lt;td&gt;\(0.2315\; (23.2\%)\)&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(x = 2\)&lt;/td&gt;
      &lt;td&gt;\(-0.4\)&lt;/td&gt;
      &lt;td&gt;\(0.670\)&lt;/td&gt;
      &lt;td&gt;\(0.4013\; (40.1\%)\)&lt;/td&gt;
      &lt;td&gt;\(+17.0\%\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(x = 3\)&lt;/td&gt;
      &lt;td&gt;\(+0.4\)&lt;/td&gt;
      &lt;td&gt;\(1.492\)&lt;/td&gt;
      &lt;td&gt;\(0.5987\; (59.9\%)\)&lt;/td&gt;
      &lt;td&gt;\(+19.7\%\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(x = 4\)&lt;/td&gt;
      &lt;td&gt;\(+1.2\)&lt;/td&gt;
      &lt;td&gt;\(3.320\)&lt;/td&gt;
      &lt;td&gt;\(0.7685\; (76.9\%)\)&lt;/td&gt;
      &lt;td&gt;\(+17.0\%\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chú ý: tỷ số Odds luôn nhân đúng \(2.226\) lần ở mỗi bước (\(0.670/0.301 \approx 2.226\); \(1.492/0.670 \approx 2.226\)), nhưng mức tăng xác suất \(\Delta p\) lớn nhất quanh vùng \(p \approx 0.5\) và nhỏ dần khi tiến gần 0 hoặc 1 (quy tắc chia 4 của Gelman: độ dốc lớn nhất trên thang xác suất là \(\beta / 4 = 0.8 / 4 = 0.20\)).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Đọc \(\text{OR} = e^{0.8} \approx 2.23\) rồi nói “học thêm 1 giờ làm xác suất qua môn tăng gấp 2.23 lần”. Nếu xác suất ban đầu đã là \(60\%\), nhân \(2.23\) sẽ ra \(134\%\) (vô lý)! Chỉ có &lt;strong&gt;Odds&lt;/strong&gt; nhân \(2.23\) lần, không phải xác suất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Tại \(x = 2.5\) giờ, \(\eta = -2.0 + 0.8(2.5) = 0\), nên \(\text{Odds} = e^0 = 1\) và xác suất qua môn đúng bằng \(p = 0.50\) (50%).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yIYKR4sgzI8&quot;&gt;StatQuest: Logistic Regression&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước&lt;/strong&gt;. Trình bày cách hồi quy logistic dự đoán xác suất cho biến kết quả nhị phân 0/1.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ARfXDSkQf1Y&quot;&gt;Odds and Log(Odds), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Giải thích odds và log-odds, hỗ trợ cách đọc hệ số trên thang logit thay vì thang xác suất.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=F0N4b7K_iYQ&quot;&gt;Statistical Rethinking 2023 - 04 - Categories &amp;amp; Curves&lt;/a&gt; — Richard McElreath, English. Trình bày đường cong logistic trong khuôn khổ mô hình Bayes, kết nối công thức với câu chuyện sinh dữ liệu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 1&lt;/strong&gt;: Sinh dữ liệu nhị phân, khớp mô hình hồi quy logistic và diễn giải tỷ số odds.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 2&lt;/strong&gt;: So sánh dự đoán của hồi quy tuyến tính và hồi quy logistic, đồng thời trực quan hóa sự khác biệt.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 3&lt;/strong&gt;: Xây dựng mô hình hồi quy logistic với nhiều biến dự báo và diễn giải từng hệ số.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 4&lt;/strong&gt;: Áp dụng trên dữ liệu thực để dự đoán tình trạng rời bỏ của khách hàng (0/1) từ các đặc trưng mức độ sử dụng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 5&lt;/strong&gt;: Thực hiện kiểm tra dự báo hậu nghiệm (posterior predictive checks) và tính các chỉ số accuracy, sensitivity, specificity.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., &amp;amp; Hill, J. (2006).&lt;/strong&gt; &lt;em&gt;Data Analysis Using Regression and Multilevel/Hierarchical Models&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 5: Logistic regression&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 10: Big Entropy and the Generalized Linear Model&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter06/06_02_poisson_regression/&quot;&gt;6.2 Poisson Regression&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 5.4: Interaction Effects - Khi Effects Phụ thuộc Nhau</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter05/05_04_interaction_effects/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter05/05_04_interaction_effects</id>
   <content type="html">&lt;p&gt;Hãy thử tưởng tượng một nông dân tưới nước cho hai thửa ruộng hoa tulip: một thửa đặt ngoài trời nắng, một thửa đặt trong nhà tối hoàn toàn. Ở thửa có nắng, thêm nước làm hoa nở rực rỡ; ở thửa tối om, thêm bao nhiêu nước cây vẫn không lớn nổi. Trong thế giới thực, các nguyên nhân hiếm khi hoạt động độc lập như những viên gạch xếp chồng lên nhau — chúng thường &lt;strong&gt;kích hoạt, khuếch đại hoặc triệt tiêu lẫn nhau&lt;/strong&gt;. Hạng tương tác trong hồi quy Bayes chính là cách toán học cho phép bản thân “độ dốc” của một biến trở thành hàm số của bối cảnh.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu hiệu ứng tương tác (interaction effect) là gì và vì sao nhiều hiện tượng thực tế không thể mô tả đầy đủ bằng mô hình cộng đơn giản. Bạn cũng sẽ biết cách diễn giải tương tác theo hiệu ứng có điều kiện — tức tác động của một biến thay đổi tùy theo giá trị của biến khác — thay vì xem mọi hệ số là hằng số cố định.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ ngắn.&lt;/strong&gt; Một chương trình luyện thi có thể giúp học sinh có nền tảng khá tiến bộ rất nhanh, nhưng lại kém hiệu quả hơn ở học sinh mất gốc nếu chưa được bổ sung kiến thức cơ bản. Khi đó, tác động của số giờ học không cố định cho mọi học sinh mà phụ thuộc vào trình độ đầu vào.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Nếu tác động của một biến dự báo thay đổi theo mức của một biến dự báo khác, mô hình cộng đơn giản sẽ bỏ sót điều gì?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-đạo-hàm-riêng-hỗn-hợp-tính-đối-xứng-của-tương-tác-và-phép-dịch-tâm&quot;&gt;Kiến thức cần nhớ: Đạo hàm riêng hỗn hợp, Tính đối xứng của tương tác và Phép dịch tâm&lt;/h2&gt;

&lt;p&gt;Ở góc độ giải tích nhiều biến và thống kê Bayes, hiệu ứng tương tác xoay quanh ba ý niệm cốt lõi:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đạo hàm hỗn hợp và mặt cong uốn xoắn:&lt;/strong&gt; Trong mô hình \(\mu(x_1, x_2) = \alpha + \beta_1 x_1 + \beta_2 x_2 + \beta_3 x_1 x_2\), độ dốc theo \(x_1\) là \(\frac{\partial \mu}{\partial x_1} = \beta_1 + \beta_3 x_2\), còn đạo hàm riêng hỗn hợp là \(\frac{\partial^2 \mu}{\partial x_1 \partial x_2} = \beta_3\). Về mặt hình học, \(\beta_3 \neq 0\) uốn mặt phẳng hồi quy thành một mặt yên ngựa (hyperbolic paraboloid).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính đối xứng tuyệt đối của tương tác:&lt;/strong&gt; Vì \(\frac{\partial^2 \mu}{\partial x_1 \partial x_2} = \frac{\partial^2 \mu}{\partial x_2 \partial x_1} = \beta_3\), dữ liệu không phân biệt “biến nào điều tiết biến nào”. Nếu tác động của giờ học thay đổi theo trình độ nền, thì đồng thời tác động của trình độ nền cũng thay đổi theo số giờ học.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dịch tâm biến (Centering) trước khi nhân tương tác:&lt;/strong&gt; Khi giữ biến gốc chưa dịch tâm, hiệu ứng chính \(\beta_1\) đo độ dốc tại \(x_2 = 0\) (thường vô nghĩa) và tích \(x_1 x_2\) tương quan rất mạnh với chính \(x_1, x_2\) (gây đa cộng tuyến nhân tạo). Dịch tâm \(\tilde x_j = x_j - \bar x_j\) khôi phục ý nghĩa cho mọi hiệu ứng chính và làm MCMC hội tụ nhanh hơn.
    &lt;h2 id=&quot;1-các-yếu-tố-trong-thực-tế-hiếm-khi-chỉ-cộng-dồn-độc-lập&quot;&gt;1. Các yếu tố trong thực tế hiếm khi chỉ cộng dồn độc lập&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mô hình hồi quy cộng (additive model) có dạng:&lt;/p&gt;

\[y = \alpha + \beta_1 x_1 + \beta_2 x_2 + \epsilon\]

&lt;p&gt;Cấu trúc này giả định tác động của \(x_1\) lên \(y\) hoàn toàn giống nhau ở mọi mức của \(x_2\), và ngược lại. Tuy nhiên, trong thực tế nhiều mối quan hệ phụ thuộc lẫn nhau: hiệu quả quảng cáo phụ thuộc vào chất lượng sản phẩm, tác động của chế độ ăn phụ thuộc vào mức độ vận động, hiệu quả của giờ học phụ thuộc vào kiến thức nền tảng và hiệu quả thuốc phụ thuộc vào độ tuổi hay bệnh nền. Để mô tả những tình huống này, ta cần đưa hạng tương tác vào mô hình.&lt;/p&gt;

&lt;h2 id=&quot;2-hiệu-ứng-tương-tác-interaction-effect-là-gì&quot;&gt;2. Hiệu ứng tương tác (Interaction Effect) là gì?&lt;/h2&gt;

&lt;p&gt;Hiệu ứng tương tác xảy ra khi tác động của một biến dự báo lên biến kết quả &lt;strong&gt;thay đổi theo giá trị của một biến dự báo khác&lt;/strong&gt;. Mô hình có tương tác giữa \(x_1\) và \(x_2\) được viết là:&lt;/p&gt;

\[y = \alpha + \beta_1 x_1 + \beta_2 x_2 + \beta_3 (x_1 x_2) + \epsilon\]

&lt;p&gt;Số hạng mới \(\beta_3 (x_1 x_2)\) gọi là &lt;strong&gt;hạng tương tác (interaction term)&lt;/strong&gt;. Khi \(\beta_3\) khác 0 đáng kể, hệ số dốc của \(x_1\) sẽ thay đổi theo giá trị của \(x_2\) (và tương tự, hệ số dốc của \(x_2\) thay đổi theo \(x_1\)).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_no_interaction_parallel_lines.png&quot; alt=&quot;Trường hợp không có interaction: các đường gần song song&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_with_interaction_different_slopes.png&quot; alt=&quot;Trường hợp có interaction: slope thay đổi theo nhóm&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_interaction_model_comparison.png&quot; alt=&quot;So sánh mô hình có và không có interaction&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-phân-biệt-mô-hình-cộng-và-mô-hình-tương-tác-bằng-đồ-thị&quot;&gt;3. Phân biệt mô hình cộng và mô hình tương tác bằng đồ thị&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_additive_model_demo.png&quot; alt=&quot;Mô hình additive với các đường gần song song&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_interactive_model_demo.png&quot; alt=&quot;Mô hình interactive với các slope khác nhau&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Nhìn trực quan trên đồ thị giúp nhận diện ngay sự khác biệt giữa hai mô hình:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình cộng (additive):&lt;/strong&gt; các đường hồi quy giữa các nhóm song song với nhau. Mức nền (hệ số chặn) có thể khác nhau giữa các nhóm, nhưng độ dốc của \(x_1\) là như nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình có tương tác:&lt;/strong&gt; các đường hồi quy có độ dốc khác nhau rõ rệt. Cùng tăng thêm một đơn vị \(x_1\), mức thay đổi của \(y\) mạnh hay yếu còn tùy thuộc vào mức của \(x_2\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;video-ngắn-hiệu-ứng-tương-tác-từ-hai-đường-song-song-đến-tách-dốc&quot;&gt;Video ngắn: Hiệu ứng Tương tác: Từ Hai đường Song song đến Tách dốc&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch05-04a-interaction-slopes-cross.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): kéo hệ số tương tác β₃ từ 0.0 → +1.3 để thấy tác động của nước tưới thay đổi hoàn toàn giữa bóng râm và đủ nắng.&lt;/p&gt;

&lt;h2 id=&quot;4-ba-ví-dụ-thực-tế-về-hiệu-ứng-tương-tác&quot;&gt;4. Ba ví dụ thực tế về hiệu ứng tương tác&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thời gian học và trình độ đầu vào:&lt;/strong&gt; học sinh đã có kiến thức nền tốt có thể tăng điểm rõ rệt khi học thêm 1 giờ mỗi tuần, trong khi học sinh mất gốc có thể cần lấp lỗ hổng cơ bản trước khi giờ học thêm phát huy tác dụng tương đương.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ngân sách quảng cáo và chất lượng sản phẩm:&lt;/strong&gt; tăng chi tiêu quảng cáo mang lại doanh thu bền vững hơn nhiều khi sản phẩm có chất lượng tốt; với sản phẩm kém, quảng cáo mạnh có thể chỉ làm lộ nhược điểm nhanh hơn mà không giữ được khách hàng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phác đồ điều trị và mức độ bệnh:&lt;/strong&gt; một phương pháp điều trị có thể đạt hiệu quả cao ở nhóm bệnh nhẹ nhưng giảm tác dụng ở nhóm bệnh nặng (hoặc ngược lại).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;thử-nghiệm-từ-mô-hình-cộng-đến-mô-hình-có-tương-tác&quot;&gt;Thử nghiệm: từ mô hình cộng đến mô hình có tương tác&lt;/h3&gt;

&lt;p&gt;So sánh ba bước mở rộng: một đường chung \(\to\) hai đường song song \(\to\) hai đường khác độ dốc, và quan sát tổng bình phương phần dư (RSS) thay đổi ra sao.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;confound-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;interaction&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;5-cách-diễn-giải-mô-hình-có-tương-tác&quot;&gt;5. Cách diễn giải mô hình có tương tác&lt;/h2&gt;

&lt;p&gt;Sai lầm phổ biến nhất là đọc \(\beta_1\) như một tác động chung cố định dù mô hình đã chứa hạng tương tác. Đạo hàm riêng theo \(x_1\) cho thấy:&lt;/p&gt;

\[\frac{\partial y}{\partial x_1} = \beta_1 + \beta_3 x_2\]

&lt;p&gt;Như vậy, ảnh hưởng của \(x_1\) không còn là một hằng số mà là một hàm phụ thuộc vào \(x_2\).&lt;/p&gt;

&lt;p&gt;Khi \(x_2\) là biến nhị phân (\(x_2 = 0\) cho nhóm đối chứng và \(x_2 = 1\) cho nhóm can thiệp), tác động của \(x_1\) ở nhóm đối chứng là \(\beta_1\), còn ở nhóm can thiệp là \(\beta_1 + \beta_3\). Hệ số \(\beta_3\) đo chính xác mức chênh lệch về độ dốc giữa hai nhóm.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_conditional_effects_by_group.png&quot; alt=&quot;Conditional effects của x₁ theo từng nhóm x₂&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_interaction_difference_distribution.png&quot; alt=&quot;Interaction như chênh lệch giữa hai conditional effects&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;51-ví-dụ-bằng-con-số&quot;&gt;5.1. Ví dụ bằng con số&lt;/h3&gt;

&lt;p&gt;Giả sử mô hình điểm cuối kỳ có dạng:&lt;/p&gt;

\[\text{Điểm} = 4 + 0.2 \cdot \text{Giờ học} + 1.0 \cdot \text{Nền tảng tốt} + 0.25 \cdot (\text{Giờ học} \times \text{Nền tảng tốt}),\]

&lt;p&gt;trong đó &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Nền tảng tốt = 0&lt;/code&gt; ứng với nhóm mất gốc và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;= 1&lt;/code&gt; ứng với nhóm có kiến thức nền ổn định. Khi đó, mỗi giờ học tăng thêm giúp nhóm mất gốc tăng trung bình &lt;strong&gt;0.2 điểm&lt;/strong&gt;, còn nhóm nền tảng tốt tăng trung bình \(0.2 + 0.25 = 0.45\) điểm.&lt;/p&gt;

&lt;p&gt;Kiểm tra qua bốn trường hợp cụ thể:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Học sinh mất gốc, học 2 giờ: \(4 + 0.2 \times 2 = 4.4\) điểm.&lt;/li&gt;
  &lt;li&gt;Học sinh nền tảng tốt, học 2 giờ: \(4 + 0.2 \times 2 + 1 + 0.25 \times 2 = 5.9\) điểm.&lt;/li&gt;
  &lt;li&gt;Học sinh mất gốc, học 6 giờ: \(4 + 0.2 \times 6 = 5.2\) điểm (tăng 0.8 điểm so với mức 2 giờ).&lt;/li&gt;
  &lt;li&gt;Học sinh nền tảng tốt, học 6 giờ: \(4 + 0.2 \times 6 + 1 + 0.25 \times 6 = 7.7\) điểm (tăng 1.8 điểm so với mức 2 giờ).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mức tăng điểm khi nâng từ 2 lên 6 giờ học khác nhau rõ rệt giữa hai nhóm — đó chính là biểu hiện định lượng của hiệu ứng tương tác.&lt;/p&gt;

&lt;h2 id=&quot;6-tương-tác-giữa-hai-biến-liên-tục&quot;&gt;6. Tương tác giữa hai biến liên tục&lt;/h2&gt;

&lt;p&gt;Hiệu ứng tương tác không chỉ giới hạn ở biến nhị phân mà còn xuất hiện phổ biến giữa hai biến liên tục, chẳng hạn nhiệt độ và độ ẩm cùng ảnh hưởng đến tiêu thụ điện, thu nhập và độ tuổi cùng ảnh hưởng đến chi tiêu, hay thời gian học và chất lượng giấc ngủ cùng ảnh hưởng đến điểm thi.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_interaction_continuous_lines.png&quot; alt=&quot;Các đường hiệu ứng khi cả hai biến đều liên tục&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_continuous_interaction_3d.png&quot; alt=&quot;Góc nhìn 3D của tương tác giữa hai biến liên tục&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_continuous_interaction_contour.png&quot; alt=&quot;Contour plot của tương tác giữa hai biến liên tục&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Với tương tác giữa hai biến liên tục, các đồ thị trực quan như biểu đồ đường đồng mức (contour plot), biểu đồ bề mặt 3D hoặc đồ thị hiệu ứng có điều kiện tại vài mức tiêu biểu của biến kia dễ đọc hơn nhiều so với bảng hệ số thuần túy.&lt;/p&gt;

&lt;h3 id=&quot;giải-thích-chứng-minh-bằng-tay-vì-sao-dịch-tâm-centering-cứu-nguyên-ý-nghĩa-của-hiệu-ứng-chính&quot;&gt;Giải thích: Chứng minh bằng tay vì sao dịch tâm (centering) cứu nguyên ý nghĩa của hiệu ứng chính&lt;/h3&gt;

&lt;p&gt;Giả sử ta mô hình hóa điểm thi theo số giờ học \(x_1\) (trung bình lớp \(\bar x_1 = 5\) giờ) và điểm nền tảng đầu vào \(x_2\) (trung bình lớp \(\bar x_2 = 7\) điểm):&lt;/p&gt;

\[\mu = 1.0 + 0.10\,x_1 + 0.50\,x_2 + 0.05\,x_1 x_2.\]

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cái bẫy khi đọc trực tiếp ở thang gốc:&lt;/strong&gt; Nếu đọc vội \(\beta_1 = 0.10\) là “học thêm 1 giờ tăng 0.10 điểm”, bạn đang mắc sai lầm nghiêm trọng! Con số \(0.10\) chỉ đúng khi \(x_2 = 0\) (học sinh có 0 điểm đầu vào). Tại mức học sinh trung bình của lớp (\(x_2 = 7\)), tác động thực sự của 1 giờ học thêm là:
\(\left.\frac{\partial \mu}{\partial x_1}\right|_{x_2 = 7} = 0.10 + 0.05(7) = 0.45\text{ điểm/giờ}\)
— gấp &lt;strong&gt;4.5 lần&lt;/strong&gt; con số \(0.10\) hiển thị ở bảng hệ số!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đặt biến dịch tâm \(\tilde x_1 = x_1 - 5\) và \(\tilde x_2 = x_2 - 7\)&lt;/strong&gt; (suy ra \(x_1 = \tilde x_1 + 5,\ x_2 = \tilde x_2 + 7\)), thay vào phương trình và khai triển:
\(\begin{aligned}
\mu &amp;amp;= 1.0 + 0.10(\tilde x_1 + 5) + 0.50(\tilde x_2 + 7) + 0.05(\tilde x_1 + 5)(\tilde x_2 + 7) \\
&amp;amp;= (1.0 + 0.50 + 3.50 + 1.75) + (0.10 + 0.35)\tilde x_1 + (0.50 + 0.25)\tilde x_2 + 0.05\,\tilde x_1 \tilde x_2 \\
&amp;amp;= 6.75 + 0.45\,\tilde x_1 + 0.75\,\tilde x_2 + 0.05\,\tilde x_1 \tilde x_2.
\end{aligned}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đọc lại bảng hệ số mới:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Hệ số chặn \(6.75\) là điểm kỳ vọng của học sinh trung bình (học 5 giờ, đầu vào 7 điểm).&lt;/li&gt;
      &lt;li&gt;Hiệu ứng chính \(\tilde\beta_1 = 0.45\) là tác động đúng của 1 giờ học tại mức đầu vào trung bình.&lt;/li&gt;
      &lt;li&gt;Hệ số tương tác \(\beta_3 = 0.05\) &lt;strong&gt;hoàn toàn bất biến&lt;/strong&gt; — chứng tỏ hai mô hình dự đoán giống hệt nhau từng chữ số, nhưng mô hình dịch tâm cho khả năng diễn giải minh bạch hơn hẳn.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;7-khi-nào-nên-cân-nhắc-đưa-hạng-tương-tác-vào-mô-hình&quot;&gt;7. Khi nào nên cân nhắc đưa hạng tương tác vào mô hình?&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Khi kiến thức chuyên môn gợi ý:&lt;/strong&gt; cơ chế thực tế cho thấy tác động của một yếu tố thay đổi theo bối cảnh (như thuốc theo độ tuổi, đào tạo theo trình độ nền hay giá bán theo phân khúc khách hàng).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khi đồ thị phân nhóm cho thấy độ dốc khác nhau:&lt;/strong&gt; các đường xu hướng theo từng nhóm không song song.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khi mô hình cộng để lại phần dư có cấu trúc:&lt;/strong&gt; phần dư thể hiện sự phụ thuộc hệ thống giữa các biến dự báo.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;8-ba-hiểu-lầm-thường-gặp&quot;&gt;8. Ba hiểu lầm thường gặp&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;“Có hạng tương tác thì hiệu ứng chính (main effect) mất ý nghĩa”:&lt;/strong&gt; không đúng. Hiệu ứng chính vẫn có ý nghĩa, nhưng phụ thuộc vào cách mã hóa và dịch tâm biến. Nếu dịch tâm các biến liên tục quanh giá trị trung bình, hệ số chính \(\beta_1\) chính là tác động của \(x_1\) tại mức trung bình của \(x_2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;“Đưa hạng tương tác vào thì có thể bỏ hiệu ứng chính”:&lt;/strong&gt; thông thường luôn nên giữ lại cả các hiệu ứng chính để mô hình duy trì tính nhất quán và khả năng diễn giải.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;“Chỉ cần xem khoảng tin cậy của \(\beta_3\) là đủ”:&lt;/strong&gt; chưa đủ; trực quan hóa hiệu ứng có điều kiện (conditional effects) giúp nắm bắt bản chất tương tác rõ ràng hơn nhiều.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;9-ví-dụ-gần-gũi-tập-luyện-và-chế-độ-ăn&quot;&gt;9. Ví dụ gần gũi: tập luyện và chế độ ăn&lt;/h2&gt;

&lt;p&gt;Xét bài toán giảm cân trong 8 tuần theo số buổi tập mỗi tuần và mức độ tuân thủ chế độ ăn. Nếu chế độ ăn kém, tăng thêm 1 buổi tập có thể chỉ mang lại thay đổi nhỏ; nhưng khi chế độ ăn được kiểm soát tốt, cùng 1 buổi tập thêm có thể tạo khác biệt lớn hơn. Mô hình cộng:&lt;/p&gt;

\[\text{Giảm cân} = \alpha + \beta_1 \cdot \text{Tập luyện} + \beta_2 \cdot \text{Chế độ ăn} + \epsilon\]

&lt;p&gt;sẽ bỏ qua sự cộng hưởng này, trong khi mô hình có tương tác:&lt;/p&gt;

\[\text{Giảm cân} = \alpha + \beta_1 \cdot \text{Tập luyện} + \beta_2 \cdot \text{Chế độ ăn} + \beta_3 \cdot (\text{Tập luyện} \times \text{Chế độ ăn}) + \epsilon\]

&lt;p&gt;cho phép kiểm chứng trực tiếp cơ chế: nếu \(\beta_3 &amp;gt; 0\), hai yếu tố &lt;strong&gt;khuếch đại&lt;/strong&gt; nhau; ngược lại nếu \(\beta_3 &amp;lt; 0\), chúng có xu hướng &lt;strong&gt;bù trừ&lt;/strong&gt; hoặc thay thế một phần cho nhau.&lt;/p&gt;

&lt;h2 id=&quot;10-trình-bày-kết-quả-tương-tác-cho-người-đọc-không-chuyên&quot;&gt;10. Trình bày kết quả tương tác cho người đọc không chuyên&lt;/h2&gt;

&lt;p&gt;Thay vì mở đầu bằng con số kỹ thuật kiểu “hệ số tương tác bằng 0.63”, hãy diễn đạt bằng ngôn ngữ tình huống trước:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Tác động của số giờ học không giống nhau giữa các nhóm học sinh. Ở nhóm có kiến thức nền tốt, tăng thời gian học đi kèm mức cải thiện điểm số mạnh hơn rõ rệt so với nhóm nền tảng yếu.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Sau đó mới bổ sung các con số ước lượng và khoảng bất định tương ứng.&lt;/p&gt;

&lt;h2 id=&quot;11-tổng-kết-chương-5&quot;&gt;11. Tổng kết Chương 5&lt;/h2&gt;

&lt;p&gt;Kết thúc Chương 5, bạn đã nắm bốn trụ cột của hồi quy đa biến: diễn giải hệ số có điều kiện, phân tích cấu trúc nhân quả và biến gây nhiễu bằng DAG, nhận diện và xử lý đa cộng tuyến, cùng cách mô hình hóa hiệu ứng tương tác. Nhờ đó, hồi quy chuyển từ kỹ thuật khớp đường thuần túy thành công cụ suy luận có cấu trúc về cơ chế sinh dữ liệu.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Hiệu ứng tương tác xuất hiện khi tác động của một biến thay đổi theo giá trị của biến khác; khi mô hình có tương tác, cần diễn giải qua hiệu ứng có điều kiện kết hợp biểu đồ trực quan thay vì chỉ đọc từng hệ số riêng lẻ; và tương tác rất phổ biến trong thực tế vì hiệu quả của can thiệp hiếm khi đồng nhất ở mọi bối cảnh.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=3CCkeFShB3U&quot;&gt;GLM Part 6: Interaction effects: How to interpret and identify them&lt;/a&gt; — Simplistics (QuantPsych), English. &lt;strong&gt;xem trước&lt;/strong&gt;. Giải thích bản chất và cách nhận diện hiệu ứng tương tác so với mô hình cộng.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=J8IHdu-oM64&quot;&gt;How to Interpret a Regression with an Interaction Term&lt;/a&gt; — Econometrics, Causality, and Coding with Dr. HK, English. Hướng dẫn chi tiết cách đọc hiệu ứng chính và hạng tương tác từ bảng kết quả hồi quy.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=F0N4b7K_iYQ&quot;&gt;Statistical Rethinking 2023 - 04 - Categories &amp;amp; Curves&lt;/a&gt; — Richard McElreath, English. Minh họa cách mô hình hóa đường cong và khác biệt theo nhóm, mở rộng góc nhìn về tương tác trong mô hình sinh dữ liệu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Hãy nêu một ví dụ thực tế trong đó tác động của một biến phụ thuộc rõ rệt vào giá trị của biến khác.&lt;/li&gt;
  &lt;li&gt;Vì sao các đường hồi quy không song song giữa các nhóm là dấu hiệu gợi ý sự tồn tại của hiệu ứng tương tác?&lt;/li&gt;
  &lt;li&gt;Trong ví dụ giờ học và trình độ đầu vào, hạng tương tác nắm bắt được thông tin gì mà mô hình cộng bỏ sót?&lt;/li&gt;
  &lt;li&gt;Nếu các biến liên tục không được dịch tâm (center), việc diễn giải các hiệu ứng chính trong mô hình có tương tác sẽ gặp khó khăn ở điểm nào?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., &amp;amp; Hill, J. (2006).&lt;/strong&gt; &lt;em&gt;Data Analysis Using Regression and Multilevel/Hierarchical Models&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Chương tiếp theo: &lt;a href=&quot;/contents/vi/chapter06/&quot;&gt;Chương 6: Mô hình Tuyến tính Tổng quát Bayes (GLM)&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 5.3: Multicollinearity - Khi Predictors Tương quan</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter05/05_03_multicollinearity/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter05/05_03_multicollinearity</id>
   <content type="html">&lt;p&gt;Trong cuốn &lt;em&gt;Statistical Rethinking&lt;/em&gt;, Richard McElreath đặt ra một thí nghiệm tưởng tượng rất dí dỏm: giả sử bạn muốn dự đoán chiều cao của một người trưởng thành từ cả &lt;strong&gt;chiều dài chân trái&lt;/strong&gt; lẫn &lt;strong&gt;chiều dài chân phải&lt;/strong&gt;. Đưa riêng từng chân vào mô hình, hệ số nào cũng cực kỳ rõ ràng. Nhưng khi đưa đồng thời cả hai vào cùng một hồi quy, phần mềm bỗng báo cả hai hệ số đều bất định rộng thênh thang — thậm chí một chân có thể mang dấu âm! Dữ liệu không hề lỗi; chỉ là hiếm ai có chân trái dài hơn chân phải 20 cm để mô hình thử “giữ cố định chân phải mà kéo dài chân trái”.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu đa cộng tuyến (multicollinearity) là gì, vì sao nó gây khó khăn cho việc diễn giải từng hệ số hồi quy và trong bối cảnh nào hiện tượng này thực sự đáng lo ngại. Bạn cũng sẽ phân biệt rạch ròi hai mục tiêu khác nhau của hồi quy là &lt;strong&gt;dự đoán&lt;/strong&gt; (prediction) và &lt;strong&gt;diễn giải&lt;/strong&gt; (interpretation).&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ ngắn.&lt;/strong&gt; Khi dự đoán giá nhà từ diện tích và số phòng ngủ, hai biến này thường biến thiên cùng nhau vì nhà rộng hơn thường có nhiều phòng hơn. Mô hình vẫn có thể dự đoán giá tổng thể khá chính xác, nhưng sẽ rất khó trả lời chắc chắn câu hỏi: “giữ nguyên diện tích thì thêm một phòng ngủ làm giá thay đổi bao nhiêu?”.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Khi hai biến dự báo gần như đo lường cùng một đặc trưng, mô hình hồi quy sẽ gặp trở ngại gì trong việc tách riêng ảnh hưởng của từng biến?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ma-trận-thiết-kế-suy-biến-hệ-số-phóng-đại-phương-sai-vif-và-hình-học-hậu-nghiệm&quot;&gt;Kiến thức cần nhớ: Ma trận thiết kế suy biến, Hệ số phóng đại phương sai (VIF) và Hình học hậu nghiệm&lt;/h2&gt;

&lt;p&gt;Bản chất của đa cộng tuyến nằm trọn trong giao điểm giữa đại số tuyến tính và phân phối hậu nghiệm nhiều chiều:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ma trận \(X^\top X\) gần suy biến (Ill-conditioned Design Matrix):&lt;/strong&gt; Trong hồi quy tuyến tính, ma trận hiệp phương sai hậu nghiệm (khi prior yếu) tỷ lệ với \(\sigma^2 (X^\top X)^{-1}\). Khi hai cột của \(X\) gần phụ thuộc tuyến tính, định thức \(\det(X^\top X) \to 0\) khiến các phần tử đường chéo của \((X^\top X)^{-1}\) phình to cực mạnh — đó là lý do phương sai từng hệ số bùng nổ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hệ số phóng đại phương sai (VIF — Variance Inflation Factor):&lt;/strong&gt; Nếu hồi quy biến \(x_j\) theo các biến dự báo còn lại cho hệ số xác định \(R_j^2\), thì phương sai của \(\beta_j\) bị nhân lên đúng một thừa số \(\text{VIF}_j = \frac{1}{1 - R_j^2}\) (độ lệch chuẩn tăng theo \(\sqrt{\text{VIF}_j}\)). Chẳng hạn \(R_j^2 = 0.90\) làm phương sai tăng gấp 10 lần.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hình học dải chéo trong hậu nghiệm Bayes:&lt;/strong&gt; Thay vì che giấu vấn đề bằng một ước lượng điểm bất ổn, phân phối hậu nghiệm đồng thời kéo dài thành một hình elip dẹt nghiêng \(45^\circ\) — thể hiện rõ rằng &lt;em&gt;tổng&lt;/em&gt; \(\beta_1 + \beta_2\) được dữ liệu khóa rất chặt, còn &lt;em&gt;hiệu&lt;/em&gt; \(\beta_1 - \beta_2\) lại trượt tự do dọc theo sống núi.
    &lt;h2 id=&quot;1-đa-cộng-tuyến-multicollinearity-là-gì&quot;&gt;1. Đa cộng tuyến (Multicollinearity) là gì?&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Đa cộng tuyến xảy ra khi hai hoặc nhiều biến dự báo trong cùng một mô hình có tương quan rất cao với nhau. Vì chúng mang thông tin trùng lặp đáng kể, mô hình gặp khó khăn khi phân chia đóng góp riêng cho từng biến. Các ví dụ quen thuộc gồm chiều cao đo bằng cm và inch, diện tích và số phòng ngủ trong cùng một dự án chung cư có thiết kế đồng nhất, hay số giờ học và số bài tập hoàn thành trong một lớp học có kỷ luật cao.&lt;/p&gt;

&lt;p&gt;Điều cần nhấn mạnh là đa cộng tuyến không có nghĩa dữ liệu bị sai; nó chỉ phản ánh việc các biến đầu vào đang chia sẻ quá nhiều thông tin giống nhau.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_multicollinearity_predictor_correlation.png&quot; alt=&quot;Tương quan rất cao giữa hai predictors&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_multicollinearity_both_predict_y.png&quot; alt=&quot;Cả hai predictors đều liên quan mạnh đến outcome&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_multicollinearity_problem_summary.png&quot; alt=&quot;Tóm tắt vì sao multicollinearity làm khó diễn giải&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ba biểu đồ trên minh họa tình huống điển hình: cả hai biến dự báo đều liên quan mạnh đến biến kết quả, nhưng chúng cũng tương quan chặt với nhau nên mô hình khó phân định mức đóng góp riêng của từng biến.&lt;/p&gt;

&lt;h2 id=&quot;2-vì-sao-đa-cộng-tuyến-làm-hệ-số-hồi-quy-khó-diễn-giải&quot;&gt;2. Vì sao đa cộng tuyến làm hệ số hồi quy khó diễn giải?&lt;/h2&gt;

&lt;p&gt;Theo nguyên tắc của hồi quy đa biến, mỗi hệ số phản ánh tác động của một biến khi &lt;strong&gt;giữ các biến còn lại cố định&lt;/strong&gt;. Tuy nhiên, nếu hai biến hầu như luôn tăng giảm đồng thời trong dữ liệu, việc giữ cố định biến này trong khi thay đổi biến kia rất hiếm khi xuất hiện thực tế. Trong ví dụ diện tích và số phòng ngủ, nếu dữ liệu có rất ít cặp căn nhà cùng diện tích nhưng khác số phòng ngủ, mô hình sẽ thiếu thông tin để ước lượng chắc chắn hệ số riêng của từng biến.&lt;/p&gt;

&lt;p&gt;Hệ quả phổ biến là khoảng tin cậy hậu nghiệm (credible interval) của các hệ số mở rộng đáng kể, dấu của hệ số có thể thay đổi bất ngờ và ước lượng trở nên nhạy cảm chỉ với vài quan sát thêm bớt. Bốn hình dưới so sánh phân phối hậu nghiệm khi hai biến dự báo ít tương quan và khi chúng tương quan rất cao.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_low_predictor_correlation.png&quot; alt=&quot;Trường hợp predictors chỉ tương quan nhẹ&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_high_predictor_correlation.png&quot; alt=&quot;Trường hợp predictors tương quan rất cao&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_low_correlation_posterior.png&quot; alt=&quot;Posterior khi predictors ít tương quan&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_high_correlation_posterior.png&quot; alt=&quot;Posterior khi predictors tương quan cao&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;21-ví-dụ-bằng-con-số-mô-hình-tổng-thể-ổn-nhưng-hệ-số-riêng-bất-ổn&quot;&gt;2.1. Ví dụ bằng con số: mô hình tổng thể ổn nhưng hệ số riêng bất ổn&lt;/h3&gt;

&lt;p&gt;Giả sử ta dự đoán giá nhà bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diện tích&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;số phòng ngủ&lt;/code&gt;, với hệ số tương quan giữa hai biến khoảng \(0.92\). Nếu khớp riêng từng mô hình một biến:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Chỉ dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diện tích&lt;/code&gt;: tăng 1 m² đi kèm tăng trung bình &lt;strong&gt;35 triệu đồng&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Chỉ dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;số phòng ngủ&lt;/code&gt;: tăng 1 phòng đi kèm tăng trung bình &lt;strong&gt;700 triệu đồng&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cả hai kết quả đều hợp lý vì mỗi biến đang đại diện cho thông tin chung về quy mô căn nhà. Nhưng khi đưa đồng thời cả hai vào mô hình đa biến, ước lượng có thể trở thành:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diện tích&lt;/code&gt;: khoảng &lt;strong&gt;32 triệu đồng/m²&lt;/strong&gt; với khoảng hậu nghiệm tương đối gọn.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;số phòng ngủ&lt;/code&gt;: khoảng &lt;strong&gt;40 triệu đồng/phòng&lt;/strong&gt; nhưng khoảng hậu nghiệm rất rộng, chẳng hạn từ &lt;strong&gt;-180&lt;/strong&gt; đến &lt;strong&gt;260 triệu đồng&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mô hình không hề dự đoán kém đi; nó chỉ phản ánh trung thực rằng dữ liệu hiện có chưa đủ để tách bạch rõ giá trị riêng của số phòng ngủ sau khi đã cố định diện tích.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-đa-cộng-tuyến-dải-chéo-hậu-nghiệm--tổng-β--β-siêu-ổn-định&quot;&gt;Video ngắn: Đa cộng tuyến: Dải Chéo Hậu nghiệm &amp;amp; Tổng β₁ + β₂ Siêu ổn định&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch05-03a-multicollinearity-ridge.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): kéo tương quan ρ giữa hai biến dự báo từ 0.0 → 0.96: hình elip hậu nghiệm co dẹt thành dải chéo dài dọc đường β₁ + β₂ = 3.0.&lt;/p&gt;

&lt;h2 id=&quot;3-dấu-hiệu-nhận-biết-đa-cộng-tuyến&quot;&gt;3. Dấu hiệu nhận biết đa cộng tuyến&lt;/h2&gt;

&lt;p&gt;Trong thực hành, bạn có thể nhận diện đa cộng tuyến qua bốn dấu hiệu: các biến dự báo có tương quan rất cao trên ma trận tương quan hoặc biểu đồ phân tán; hệ số của một biến thay đổi mạnh khi thêm một biến liên quan khác; khoảng tin cậy của từng hệ số rất rộng dù mô hình tổng thể khớp tốt; hoặc dấu của hệ số trái ngược với trực giác chuyên môn. Ví dụ, nếu một doanh nghiệp luôn tăng giảm đồng thời ngân sách quảng cáo Facebook và Instagram, mô hình tổng thể vẫn dự đoán tốt doanh thu từ tổng chi tiêu quảng cáo nhưng khó tách riêng hiệu quả của từng kênh.&lt;/p&gt;

&lt;h2 id=&quot;4-đa-cộng-tuyến-có-phải-lúc-nào-cũng-là-vấn-đề-nghiêm-trọng&quot;&gt;4. Đa cộng tuyến có phải lúc nào cũng là vấn đề nghiêm trọng?&lt;/h2&gt;

&lt;p&gt;Câu trả lời là &lt;strong&gt;không&lt;/strong&gt; — mức độ ảnh hưởng phụ thuộc trực tiếp vào mục tiêu phân tích:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Khi mục tiêu là dự đoán (prediction):&lt;/strong&gt; đa cộng tuyến thường không gây cản trở lớn, vì tổ hợp thông tin chung của nhóm biến vẫn giúp dự báo chính xác biến kết quả (chẳng hạn dùng nhiều chỉ số tài chính tương quan để dự báo rủi ro tín dụng).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khi mục tiêu là diễn giải (interpretation):&lt;/strong&gt; đa cộng tuyến trở thành rào cản đáng kể, bởi lúc này ta cần xác định biến nào đóng góp bao nhiêu cùng dấu và độ lớn ổn định của từng hệ số.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-ví-dụ-thực-tế-lương-học-vấn-và-kỹ-năng-chuyên-môn&quot;&gt;5. Ví dụ thực tế: lương, học vấn và kỹ năng chuyên môn&lt;/h2&gt;

&lt;p&gt;Giả sử ta giải thích mức lương bằng số năm đi học, bằng cấp cao nhất và điểm đánh giá kỹ năng chuyên môn — ba biến vốn có tương quan mạnh với nhau. Mô hình tổng thể có thể dự đoán lương khá sát, nhưng khó tách bạch riêng phần đóng góp của bằng cấp khi kỹ năng và số năm học cùng biến thiên theo. Cách kết luận trung thực khi đó là:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Nhóm biến phản ánh nền tảng học thuật và chuyên môn liên hệ mạnh với mức lương, nhưng dữ liệu hiện có chưa đủ để tách riêng chính xác đóng góp của từng yếu tố.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;51-hình-dạng-phân-phối-hậu-nghiệm-đồng-thời-trong-thống-kê-bayes&quot;&gt;5.1. Hình dạng phân phối hậu nghiệm đồng thời trong thống kê Bayes&lt;/h3&gt;

&lt;p&gt;Nếu vẽ phân phối hậu nghiệm đồng thời (joint posterior) của hệ số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;số năm đi học&lt;/code&gt; và hệ số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kỹ năng chuyên môn&lt;/code&gt;, các mẫu thường không tụ thành một đám mây tròn mà kéo dài thành một &lt;strong&gt;dải chéo dốc xuống&lt;/strong&gt;. Điều này cho thấy khi mô hình gán trọng số lớn hơn cho học vấn thì phải giảm trọng số của kỹ năng (và ngược lại), vì nhiều tổ hợp hệ số khác nhau cùng giải thích dữ liệu tốt ngang nhau. Do đó, bên cạnh trung bình hậu nghiệm riêng lẻ, cần quan sát cấu trúc tương quan giữa các hệ số trong phân phối hậu nghiệm đồng thời.&lt;/p&gt;

&lt;h2 id=&quot;6-cơ-chế-phía-sau-dải-chéo-trong-phân-phối-hậu-nghiệm&quot;&gt;6. Cơ chế phía sau dải chéo trong phân phối hậu nghiệm&lt;/h2&gt;

&lt;p&gt;Trong góc nhìn Bayes, đa cộng tuyến hiện lên trực tiếp ở mối liên hệ âm giữa hai hệ số trong phân phối hậu nghiệm: tổng đóng góp của cả hai biến được dữ liệu xác định khá chắc chắn, nhưng tỷ lệ phân chia giữa từng biến lại có độ bất định lớn. Nhờ giữ lại toàn bộ phân phối hậu nghiệm thay vì chỉ một ước lượng điểm, phương pháp Bayes giúp ta nhìn thấy ngay sự bất định này thay vì bị đánh lừa bởi một con số duy nhất.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-tăng-tương-quan-làm-phân-phối-hậu-nghiệm-kéo-thành-dải-chéo&quot;&gt;Thử nghiệm: tăng tương quan làm phân phối hậu nghiệm kéo thành dải chéo&lt;/h3&gt;

&lt;p&gt;Tăng hệ số tương quan \(\rho\) giữa hai biến dự báo để quan sát độ lệch chuẩn của \(b_1\) tăng theo \(\sqrt{\text{VIF}}\), \(b_1\) và \(b_2\) tương quan âm mạnh trong khi tổng \(b_1 + b_2\) vẫn ổn định.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;collinear-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;giải-thích-chứng-minh-bằng-tay-vì-sao-beta_1-beta_2-bất-ổn-nhưng-tổng-beta_1--beta_2-lại-siêu-ổn-định&quot;&gt;Giải thích: Chứng minh bằng tay vì sao \(\beta_1, \beta_2\) bất ổn nhưng tổng \(\beta_1 + \beta_2\) lại siêu ổn định&lt;/h3&gt;

&lt;p&gt;Hãy xét mô hình hai biến chuẩn hóa \(x_1, x_2\) có hệ số tương quan \(\rho\), cỡ mẫu \(n = 100\) và nhiễu \(\sigma = 1\). Với tiên nghiệm phẳng, ma trận hiệp phương sai hậu nghiệm của \((b_1, b_2)\) có công thức đóng rất gọn:&lt;/p&gt;

\[\Sigma_{b \mid D} = \frac{\sigma^2}{n(1 - \rho^2)}\begin{pmatrix} 1 &amp;amp; -\rho \\ -\rho &amp;amp; 1 \end{pmatrix}.\]

&lt;p&gt;Thay hai mức tương quan vào để so sánh trực tiếp bằng tay:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Khi \(\rho = 0\) (hai biến độc lập):&lt;/strong&gt; \(\text{VIF} = 1\), nên \(\operatorname{Var}(b_1) = \operatorname{Var}(b_2) = 1/100 = 0.01 \implies \mathrm{SD}(b_1) = 0.100\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khi \(\rho = 0.95\) (đa cộng tuyến mạnh):&lt;/strong&gt; Ta có \(1 - \rho^2 = 1 - 0.9025 = 0.0975\), suy ra \(\text{VIF} = 1/0.0975 \approx 10.26\). Độ lệch chuẩn từng hệ số phình lên:
\(\mathrm{SD}(b_1) = \mathrm{SD}(b_2) = 0.100 \times \sqrt{10.26} \approx 0.320\)
(tăng hơn &lt;strong&gt;3.2 lần&lt;/strong&gt;!), đồng thời hiệp phương sai \(\operatorname{Cov}(b_1, b_2) = -0.95 \times 0.1026 = -0.0974\) (tương quan hậu nghiệm giữa \(b_1\) và \(b_2\) bằng đúng \(-0.95\)!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bây giờ tính phương sai của tổng \(b_1 + b_2\)&lt;/strong&gt; (đại diện cho dự đoán khi \(x_1 \approx x_2\)):
\(\operatorname{Var}(b_1 + b_2) = \operatorname{Var}(b_1) + \operatorname{Var}(b_2) + 2\operatorname{Cov}(b_1, b_2) = \frac{1 + 1 - 2\rho}{100(1-\rho^2)} = \frac{2(1-\rho)}{100(1-\rho)(1+\rho)} = \frac{2}{100(1+\rho)}.\)
Thừa số nguy hiểm \((1 - \rho)\) ở tử và mẫu &lt;strong&gt;tự triệt tiêu hoàn toàn&lt;/strong&gt;! Với \(\rho = 0.95\), ta có \(\operatorname{Var}(b_1 + b_2) = 2/195 \approx 0.01026 \implies \mathrm{SD}(b_1 + b_2) \approx 0.101\) — gần như không hề bị ảnh hưởng bởi đa cộng tuyến!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Phép rút gọn nhỏ này giải thích dứt điểm vì sao đa cộng tuyến làm hỏng bài toán &lt;strong&gt;diễn giải từng hệ số riêng&lt;/strong&gt;, nhưng hầu như không làm hỏng bài toán &lt;strong&gt;dự đoán tổng thể&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;7-các-hướng-xử-lý-đa-cộng-tuyến&quot;&gt;7. Các hướng xử lý đa cộng tuyến&lt;/h2&gt;

&lt;p&gt;Không có giải pháp duy nhất cho mọi trường hợp; cách xử lý phụ thuộc vào câu hỏi nghiên cứu:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giữ một biến đại diện:&lt;/strong&gt; nếu hai biến gần như đo cùng một đại lượng (như diện tích và số phòng ngủ trong tập dữ liệu đồng nhất), có thể chỉ giữ lại biến mang thông tin trực tiếp hơn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gộp thành chỉ số tổng hợp:&lt;/strong&gt; kết hợp các biến cùng đo một khái niệm chung (chẳng hạn tạo chỉ số kinh tế – xã hội từ nhiều biến thu nhập và tài sản).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mở rộng tính đa dạng của dữ liệu:&lt;/strong&gt; thu thập thêm dữ liệu ở những bối cảnh nơi các biến dự báo biến thiên độc lập hơn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sử dụng phân phối tiên nghiệm điều chuẩn (regularizing priors):&lt;/strong&gt; trong thống kê Bayes, phân phối tiên nghiệm thông tin yếu hoặc tiên nghiệm co rút giúp ổn định ước lượng khi dữ liệu không đủ mạnh để tách riêng từng hệ số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thừa nhận giới hạn diễn giải:&lt;/strong&gt; khi dữ liệu chỉ đủ sức trả lời bài toán dự đoán chứ không đủ để phân rạch từng hệ số, nêu rõ giới hạn này là một kết luận khoa học chuẩn mực.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;8-danh-mục-câu-hỏi-kiểm-tra-nhanh&quot;&gt;8. Danh mục câu hỏi kiểm tra nhanh&lt;/h2&gt;

&lt;p&gt;Khi nghi ngờ đa cộng tuyến, hãy lần lượt rà soát: mục tiêu chính là dự đoán hay diễn giải; cặp hoặc nhóm biến nào đang trùng lặp thông tin; nếu bỏ bớt một biến thì chất lượng dự đoán có giảm đáng kể không; nếu giữ cả hai thì khoảng tin cậy còn đủ hẹp để diễn giải không; và liệu gộp thành một khái niệm chung có tự nhiên hơn không.&lt;/p&gt;

&lt;h2 id=&quot;9-ba-hiểu-lầm-phổ-biến&quot;&gt;9. Ba hiểu lầm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;“Hệ số đổi dấu chứng tỏ mô hình bị sai”:&lt;/strong&gt; chưa chắc; đó có thể chỉ là hệ quả của việc phân chia đóng góp giữa hai biến tương quan rất cao.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;“Các biến dự báo không được phép tương quan với nhau”:&lt;/strong&gt; trong dữ liệu thực tế, các biến hầu như luôn có mức độ tương quan nhất định; điều quan trọng là hiểu tác động của nó đến độ bất định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;“Càng thêm nhiều biến mô hình càng tốt”:&lt;/strong&gt; thêm các biến lặp lại thông tin sẵn có thường làm giảm khả năng diễn giải mà ít cải thiện hiệu quả dự báo.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;10-kết-nối-sang-hiệu-ứng-tương-tác-interaction-effects&quot;&gt;10. Kết nối sang hiệu ứng tương tác (Interaction Effects)&lt;/h2&gt;

&lt;p&gt;Cần phân biệt hai khái niệm ở Bài 5.3 và Bài 5.4: &lt;strong&gt;đa cộng tuyến&lt;/strong&gt; hỏi liệu các biến dự báo có đang trùng lặp thông tin với nhau không, còn &lt;strong&gt;hiệu ứng tương tác&lt;/strong&gt; hỏi liệu tác động của một biến dự báo lên kết quả có thay đổi tùy theo giá trị của biến dự báo khác hay không.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Đa cộng tuyến xảy ra khi các biến dự báo chứa thông tin trùng lặp cao, làm phình to bất định của từng hệ số riêng lẻ; hiện tượng này ảnh hưởng mạnh đến mục tiêu diễn giải nhưng thường ít gây hại hơn cho mục tiêu dự đoán; và hướng xử lý phụ thuộc vào mục tiêu cụ thể — từ chọn biến đại diện, gộp biến, dùng tiên nghiệm điều chuẩn đến chấp nhận giới hạn diễn giải của dữ liệu.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=G1WX5GiFSWQ&quot;&gt;Multicollinearity (in Regression Analysis)&lt;/a&gt; — numiqo, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Minh họa cách đa cộng tuyến khiến mô hình khó tách riêng tín hiệu của từng biến, khớp với định nghĩa ở đầu bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=O4jDva9B3fw&quot;&gt;Multicollinearity&lt;/a&gt; — Ben Lambert, English. Giải thích ảnh hưởng của đa cộng tuyến trong hồi quy, bổ trợ cho phần phân biệt giữa dự báo và diễn giải hệ số.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=0SBIXgPVex8&quot;&gt;Variance Inflation Factors: testing for multicollinearity&lt;/a&gt; — Ben Lambert, English. Trình bày hệ số phóng đại phương sai (VIF), hỗ trợ phần chẩn đoán mức độ tương quan giữa các biến dự báo.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao diện tích và số phòng ngủ thường dễ dẫn tới đa cộng tuyến?&lt;/li&gt;
  &lt;li&gt;Hãy nêu một tình huống trong công việc của bạn mà mô hình vẫn dự đoán tốt dù khó diễn giải riêng từng hệ số.&lt;/li&gt;
  &lt;li&gt;Khi hai biến gần như trùng lặp thông tin, bạn sẽ chọn giữ một biến hay gộp cả hai? Giải thích lý do.&lt;/li&gt;
  &lt;li&gt;Trong bài toán phân tích tiền lương, vì sao học vấn và kỹ năng chuyên môn thường gây khó khăn cho việc tách bạch hệ số riêng?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Hill, J., &amp;amp; Vehtari, A. (2020).&lt;/strong&gt; &lt;em&gt;Regression and Other Stories&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter05/05_04_interaction_effects/&quot;&gt;5.4 Interaction Effects&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 5.2: Confounding và DAGs - Causal Inference Basics</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter05/05_02_confounding_dags/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter05/05_02_confounding_dags</id>
   <content type="html">&lt;p&gt;Mùa thu năm 1973, Đại học UC Berkeley đối diện một cáo buộc nghiêm trọng về phân biệt giới tính trong tuyển sinh sau đại học: nhìn vào bảng tổng hợp toàn trường, 44% ứng viên nam trúng tuyển trong khi con số ở nữ chỉ là 35%. Thế nhưng khi nhà thống kê Peter Bickel cùng cộng sự tách số liệu theo từng khoa, một kết quả gây chấn động xuất hiện: ở hầu hết các khoa, tỷ lệ trúng tuyển của nữ thậm chí còn nhỉnh hơn nam! Nguyên nhân là ứng viên nữ nộp nhiều hơn vào các khoa có tỷ lệ chọi khắt khe nhất. Câu chuyện kinh điển ấy là lời nhắc sắc bén nhất về lý do dữ liệu thuần túy không bao giờ tự nói lên quan hệ nhân quả nếu thiếu một &lt;strong&gt;đồ thị nhân quả (DAG)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu hiện tượng gây nhiễu (confounding) là gì và vì sao nó dễ khiến ta rút ra kết luận sai từ dữ liệu quan sát. Bạn cũng sẽ biết cách sử dụng đồ thị nhân quả có hướng không chu trình (DAG) để quyết định biến nào cần điều chỉnh và biến nào không nên đưa vào mô hình — nền tảng cốt lõi của suy luận nhân quả (causal inference).&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ ngắn.&lt;/strong&gt; Một bệnh viện ghi nhận nhóm bệnh nhân được điều trị tích cực có tỷ lệ hồi phục thấp hơn nhóm điều trị chuẩn. Kết luận rằng “điều trị tích cực làm bệnh nặng hơn” có thể hoàn toàn sai nếu các ca vốn nặng hơn ngay từ lúc nhập viện mới được chỉ định điều trị tích cực. Khi đó, mức độ nặng ban đầu của bệnh chính là biến gây nhiễu.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Điều gì có thể xảy ra nếu ta bỏ qua một biến ảnh hưởng đồng thời tới cả biến can thiệp (treatment) lẫn biến kết quả (outcome)?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-mô-hình-cấu-trúc-nhân-quả-toán-tử-do-và-quy-tắc-d-separation&quot;&gt;Kiến thức cần nhớ: Mô hình cấu trúc nhân quả, Toán tử do() và Quy tắc d-separation&lt;/h2&gt;

&lt;p&gt;Suy luận nhân quả hiện đại (theo trường phái Judea Pearl) nâng cấp hồi quy thống kê bằng ba khái niệm nền tảng:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Quan sát \(P(Y \mid X=x)\) khác can thiệp \(P(Y \mid \mathrm{do}(X=x))\):&lt;/strong&gt; Phân phối có điều kiện thông thường chỉ lọc những người &lt;em&gt;tự nhiên&lt;/em&gt; có \(X=x\) (nên bị trộn lẫn với các nguyên nhân chung dẫn họ đến \(X=x\)). Ngược lại, toán tử \(\mathrm{do}(X=x)\) biểu diễn hành động cắt đứt mọi mũi tên đi vào \(X\) và ép \(X=x\) cho toàn bộ quần thể.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ba nguyên tử đồ thị và quy tắc d-separation:&lt;/strong&gt; Mọi dòng thông tin thống kê trong một DAG đều truyền qua ba cấu trúc sơ cấp: &lt;strong&gt;Fork&lt;/strong&gt; (\(X \leftarrow Z \rightarrow Y\), mở sẵn và đóng khi điều chỉnh \(Z\)), &lt;strong&gt;Chain&lt;/strong&gt; (\(X \rightarrow M \rightarrow Y\), mở sẵn và đóng khi điều chỉnh \(M\)), và &lt;strong&gt;Collider&lt;/strong&gt; (\(X \rightarrow C \leftarrow Y\), đóng sẵn nhưng &lt;em&gt;mở ra&lt;/em&gt; khi điều chỉnh \(C\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Công thức điều chỉnh đường cửa sau (Backdoor Adjustment):&lt;/strong&gt; Nếu tập biến \(Z\) chặn mọi đường cửa sau giữa \(X\) và \(Y\) mà không chứa hậu duệ của \(X\), ta tính được phân phối can thiệp thuần túy từ dữ liệu quan sát qua công thức trung bình trọng số:
\(P(Y \mid \mathrm{do}(X=x)) = \sum_z P(Y \mid X=x, Z=z)\,P(Z=z).\)
    &lt;h2 id=&quot;1-tương-quan-khác-quan-hệ-nhân-quả-ở-chỗ-nào&quot;&gt;1. Tương quan khác quan hệ nhân quả ở chỗ nào?&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trong dữ liệu thực tế, hai biến cùng tăng hoặc cùng giảm không đồng nghĩa với việc biến này gây ra biến kia. Ví dụ kinh điển là doanh số kem và số vụ đuối nước đều tăng vào mùa hè: kem không gây đuối nước, mà cả hai cùng chịu tác động từ một nguyên nhân chung là &lt;strong&gt;thời tiết nóng&lt;/strong&gt;. Khi chỉ nhìn vào hệ số tương quan mà bỏ qua cấu trúc sinh dữ liệu phía sau, ta rất dễ nhầm lẫn tương quan thành nhân quả — và hiện tượng gây nhiễu (confounding) là nguyên nhân phổ biến nhất dẫn đến nhầm lẫn này.&lt;/p&gt;

&lt;h2 id=&quot;2-biến-gây-nhiễu-confounder-là-gì&quot;&gt;2. Biến gây nhiễu (Confounder) là gì?&lt;/h2&gt;

&lt;p&gt;Một biến \(Z\) được gọi là &lt;strong&gt;biến gây nhiễu (confounder)&lt;/strong&gt; nếu nó tác động đồng thời lên biến can thiệp \(X\) và biến kết quả \(Y\), đồng thời không nằm trên con đường nhân quả đi từ \(X\) đến \(Y\).&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ví dụ 1 – Cà phê và bệnh tim:&lt;/strong&gt; Nếu quan sát thấy người uống nhiều cà phê có tỷ lệ mắc bệnh tim cao hơn, ta chưa thể vội kết luận cà phê gây bệnh tim. Nếu người chịu áp lực cao vừa uống nhiều cà phê hơn vừa có nguy cơ tim mạch cao hơn, thì &lt;strong&gt;mức độ căng thẳng (stress)&lt;/strong&gt; là biến gây nhiễu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ví dụ 2 – Học thêm và điểm thi:&lt;/strong&gt; Nếu học sinh có học lực yếu thường đi học thêm nhiều hơn, trong khi điểm thi phụ thuộc mạnh vào năng lực ban đầu, thì &lt;strong&gt;trình độ đầu vào&lt;/strong&gt; là biến gây nhiễu khi đánh giá hiệu quả của việc học thêm.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_confounding_dag_overview.png&quot; alt=&quot;Sơ đồ confounding tổng quan&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Điểm cốt lõi là biến gây nhiễu tạo ra một đường liên hệ phi nhân quả giữa \(X\) và \(Y\). Nếu không kiểm soát biến này, mô hình sẽ quy nhầm ảnh hưởng của nó thành tác động của \(X\).&lt;/p&gt;

&lt;h2 id=&quot;3-đồ-thị-nhân-quả-dag-là-gì&quot;&gt;3. Đồ thị nhân quả DAG là gì?&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;DAG&lt;/strong&gt; là viết tắt của &lt;em&gt;Directed Acyclic Graph&lt;/em&gt; (đồ thị có hướng và không có chu trình): các mũi tên có hướng biểu diễn chiều tác động nhân quả giữa các biến và không tạo thành vòng lặp khép kín. DAG giúp trả lời trực tiếp câu hỏi thực hành trước khi chạy hồi quy:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Với câu hỏi nhân quả đang xét, biến nào cần đưa vào mô hình để điều chỉnh và biến nào không nên đưa vào?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;4-ba-cấu-trúc-cơ-bản-trong-dag&quot;&gt;4. Ba cấu trúc cơ bản trong DAG&lt;/h2&gt;

&lt;p&gt;Hầu hết các sơ đồ nhân quả phức tạp đều được ghép từ ba cấu trúc nền tảng sau.&lt;/p&gt;

&lt;h3 id=&quot;41-cấu-trúc-chạc-fork-nguyên-nhân-chung&quot;&gt;4.1. Cấu trúc chạc (Fork): nguyên nhân chung&lt;/h3&gt;

\[Z \rightarrow X,\quad Z \rightarrow Y\]

&lt;p&gt;Đây chính là cấu trúc của hiện tượng gây nhiễu. Ví dụ, độ tuổi ảnh hưởng đến cả mức độ tập luyện lẫn huyết áp. Khi muốn đo tác động của tập luyện lên huyết áp, ta &lt;strong&gt;cần điều chỉnh cho độ tuổi&lt;/strong&gt; để đóng đường liên hệ phi nhân quả này.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_fork_structure.png&quot; alt=&quot;Cấu trúc fork: nguyên nhân chung gây confounding&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;42-cấu-trúc-chuỗi-chain-biến-trung-gian-mediator&quot;&gt;4.2. Cấu trúc chuỗi (Chain): biến trung gian (Mediator)&lt;/h3&gt;

\[X \rightarrow M \rightarrow Y\]

&lt;p&gt;Ở đây \(M\) là &lt;strong&gt;biến trung gian (mediator)&lt;/strong&gt; nằm trên chính con đường tác động từ \(X\) đến \(Y\). Chẳng hạn, tập luyện giúp giảm cân, và giảm cân giúp cải thiện đường huyết. Nếu mục tiêu là ước lượng &lt;strong&gt;tổng hiệu ứng&lt;/strong&gt; (total effect) của tập luyện lên đường huyết, ta &lt;strong&gt;không nên điều chỉnh cho cân nặng&lt;/strong&gt;, vì làm vậy sẽ chặn mất một phần tác động thực sự của tập luyện.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_chain_structure.png&quot; alt=&quot;Cấu trúc chain: mediator nằm trên đường tác động&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_mediation_overview.png&quot; alt=&quot;Tổng quan mediation trong câu chuyện nhân quả&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;43-cấu-trúc-hội-tụ-collider-hệ-quả-chung&quot;&gt;4.3. Cấu trúc hội tụ (Collider): hệ quả chung&lt;/h3&gt;

\[X \rightarrow C \leftarrow Y\]

&lt;p&gt;&lt;strong&gt;Collider&lt;/strong&gt; là biến chịu tác động từ cả \(X\) và \(Y\). Khác với fork, đường qua collider vốn tự đóng; nhưng nếu ta điều kiện hóa (hoặc lọc dữ liệu) theo \(C\), ta sẽ vô tình &lt;strong&gt;mở đường&lt;/strong&gt; và tạo ra tương quan giả giữa \(X\) và \(Y\). Ví dụ, cả năng lực và may mắn đều ảnh hưởng đến khả năng trúng tuyển; trong toàn bộ dân số hai yếu tố này có thể độc lập, nhưng nếu chỉ xét riêng nhóm đã trúng tuyển, người kém may mắn hơn thường phải có năng lực cao hơn, tạo ra tương quan âm giả tạo.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_collider_structure.png&quot; alt=&quot;Cấu trúc collider: điều kiện hóa có thể mở ra tương quan giả&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_collider_bias_overview.png&quot; alt=&quot;Tổng quan collider bias trong sơ đồ nhân quả&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-biến-gây-nhiễu-làm-lệch-hệ-số-và-điều-chỉnh-z-khắc-phục&quot;&gt;Thử nghiệm: biến gây nhiễu làm lệch hệ số và điều chỉnh \(Z\) khắc phục&lt;/h3&gt;

&lt;p&gt;Mô phỏng cấu trúc fork \(Z \rightarrow X, Z \rightarrow Y\): so sánh ước lượng bỏ qua \(Z\), phân tầng theo \(Z\) (nghịch lý Simpson) và hồi quy có điều chỉnh \(Z\).&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;confound-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;fork&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;video-ngắn-ba-cấu-trúc-vàng-của-dag-fork--chain--collider&quot;&gt;Video ngắn: Ba Cấu trúc Vàng của DAG: Fork · Chain · Collider&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch05-02a-dag-fork-chain-collider.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 24 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): trực quan hóa quy tắc kiểm soát Z cho Chạc (Fork), tránh chặn biến trung gian ở Chuỗi (Chain) và cấm mở Collider để không tạo tương quan giả.&lt;/p&gt;

&lt;h2 id=&quot;5-quy-tắc-thực-hành-khi-nào-nên-điều-chỉnh-một-biến&quot;&gt;5. Quy tắc thực hành: khi nào nên điều chỉnh một biến?&lt;/h2&gt;

&lt;p&gt;Nguyên tắc rút gọn cần ghi nhớ là: &lt;strong&gt;nên điều chỉnh cho biến gây nhiễu (confounder)&lt;/strong&gt;, &lt;strong&gt;không điều chỉnh cho biến trung gian (mediator)&lt;/strong&gt; nếu mục tiêu là tổng hiệu ứng, và &lt;strong&gt;không điều chỉnh cho collider&lt;/strong&gt;. Tuy ngắn gọn, quy tắc này chỉ áp dụng chính xác khi ta đã phác thảo rõ cấu trúc nhân quả bằng DAG.&lt;/p&gt;

&lt;h2 id=&quot;6-nghịch-lý-simpson-simpsons-paradox&quot;&gt;6. Nghịch lý Simpson (Simpson’s Paradox)&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_simpsons_paradox_overview.png&quot; alt=&quot;Minh họa nhanh Simpson&apos;s Paradox&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_simpsons_aggregate_bias.png&quot; alt=&quot;Dữ liệu gộp tạo ra kết luận sai về treatment&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_simpsons_stratified_effect.png&quot; alt=&quot;Tách theo severity cho thấy hiệu quả thật của treatment&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nghịch lý Simpson&lt;/strong&gt; xảy ra khi một xu hướng xuất hiện rõ rệt trên dữ liệu gộp, nhưng lại đảo chiều hoàn toàn khi tách dữ liệu theo một biến phân tầng quan trọng. Trong ví dụ y khoa, nhìn gộp toàn bộ bệnh nhân thì điều trị tích cực có tỷ lệ hồi phục thấp hơn, nhưng khi tách riêng nhóm ca nặng và nhóm ca nhẹ thì điều trị tích cực đều cho kết quả tốt hơn ở cả hai nhóm. Nguyên nhân là nhóm điều trị tích cực tiếp nhận tỷ lệ ca nặng cao hơn nhiều, khiến biến “mức độ nặng” làm đảo ngược xu hướng khi gộp chung.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_simpsons_dag_unadjusted.png&quot; alt=&quot;DAG của Simpson&apos;s Paradox khi chưa điều chỉnh confounder&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_simpsons_dag_adjusted.png&quot; alt=&quot;DAG sau khi điều chỉnh severity để lộ causal effect&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;61-bảng-số-minh-họa-nghịch-lý-simpson&quot;&gt;6.1. Bảng số minh họa nghịch lý Simpson&lt;/h3&gt;

&lt;p&gt;Giả sử bệnh viện so sánh hai phác đồ &lt;strong&gt;điều trị tích cực&lt;/strong&gt; và &lt;strong&gt;điều trị chuẩn&lt;/strong&gt; trên hai nhóm &lt;strong&gt;ca nặng&lt;/strong&gt; và &lt;strong&gt;ca nhẹ&lt;/strong&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Nhóm bệnh nhân&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Điều trị tích cực&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Điều trị chuẩn&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Ca nặng&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;24/80 hồi phục = 30%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6/30 hồi phục = 20%&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Ca nhẹ&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;54/60 hồi phục = 90%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;144/180 hồi phục = 80%&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Trong &lt;strong&gt;cả hai nhóm&lt;/strong&gt;, điều trị tích cực đều có tỷ lệ hồi phục cao hơn 10 điểm phần trăm. Tuy nhiên, khi gộp chung toàn bộ bệnh nhân:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Điều trị tích cực: \(78/140 \approx 55.7\%\) hồi phục.&lt;/li&gt;
  &lt;li&gt;Điều trị chuẩn: \(150/210 \approx 71.4\%\) hồi phục.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tỷ lệ gộp bị đảo ngược không phải vì phác đồ tích cực kém hiệu quả, mà vì phần lớn ca nặng được phân bổ vào nhóm này.&lt;/p&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-công-thức-backdoor-adjustment-trên-bảng-nghịch-lý-simpson&quot;&gt;Giải thích: Tính tay công thức Backdoor Adjustment trên bảng Nghịch lý Simpson&lt;/h3&gt;

&lt;p&gt;Ở mục 6.1, số liệu gộp cho thấy điều trị tích cực (\(X=1\)) chỉ đạt tỷ lệ hồi phục \(55.7\%\), kém hơn điều trị chuẩn (\(X=0\)) ở mức \(71.4\%\). Hãy dùng công thức Backdoor Adjustment với biến gây nhiễu mức độ nặng \(Z \in \{\text{nặng}, \text{nhẹ}\}\) để tính hiệu quả &lt;strong&gt;can thiệp thật sự&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính phân phối biên \(P(Z)\) của toàn bộ \(N = 140 + 210 = 350\) bệnh nhân:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Tổng số ca nặng: \(80 + 30 = 110 \implies P(Z=\text{nặng}) = \frac{110}{350} = \frac{11}{35} \approx 31.43\%\).&lt;/li&gt;
      &lt;li&gt;Tổng số ca nhẹ: \(60 + 180 = 240 \implies P(Z=\text{nhẹ}) = \frac{240}{350} = \frac{24}{35} \approx 68.57\%\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính xác suất hồi phục nếu can thiệp cho MỌI bệnh nhân dùng điều trị tích cực (\(\mathrm{do}(X=1)\)):&lt;/strong&gt;
\(P(Y=1 \mid \mathrm{do}(X=1)) = 0.30 \times \frac{11}{35} + 0.90 \times \frac{24}{35} = \frac{3.3 + 21.6}{35} = \frac{24.9}{35} \approx 71.14\%.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính xác suất hồi phục nếu can thiệp cho MỌI bệnh nhân dùng điều trị chuẩn (\(\mathrm{do}(X=0)\)):&lt;/strong&gt;
\(P(Y=1 \mid \mathrm{do}(X=0)) = 0.20 \times \frac{11}{35} + 0.80 \times \frac{24}{35} = \frac{2.2 + 19.2}{35} = \frac{21.4}{35} \approx 61.14\%.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kết luận nhân quả (Average Treatment Effect — ATE):&lt;/strong&gt;
\(\text{ATE} = 71.14\% - 61.14\% = +10.0\%.\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chỉ bằng hai dòng cộng nhân, công thức Backdoor đã lật ngược hoàn toàn con số gộp gây hiểu lầm (\(-15.7\%\)) và trả về đúng lợi ích thật sự (\(+10\%\)) của phác đồ tích cực.&lt;/p&gt;

&lt;h2 id=&quot;7-đường-cửa-sau-backdoor-path-là-gì&quot;&gt;7. Đường cửa sau (Backdoor Path) là gì?&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Đường cửa sau (backdoor path)&lt;/strong&gt; là mọi đường nối phi nhân quả giữa biến can thiệp \(X\) và biến kết quả \(Y\) bắt đầu bằng một mũi tên đi vào \(X\) (thông qua các nguyên nhân chung). Mục tiêu của việc điều chỉnh (adjustment) là chặn toàn bộ các đường cửa sau đang mở mà không chặn đường tác động nhân quả từ \(X\) đến \(Y\) và không vô tình mở ra đường sai mới.&lt;/p&gt;

&lt;p&gt;Bốn hình dưới minh họa các tình huống điển hình: đường cửa sau đơn giản, nhiều đường cửa sau cần chặn cùng lúc, đường cửa sau vốn đã bị collider chặn sẵn và cấu trúc M-bias (nơi điều chỉnh nhầm một collider sẽ mở đường cửa sau).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_backdoor_simple.png&quot; alt=&quot;Ví dụ backdoor path đơn giản&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_backdoor_multiple.png&quot; alt=&quot;Ví dụ có nhiều backdoor paths cần chặn cùng lúc&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_backdoor_blocked_by_collider.png&quot; alt=&quot;Backdoor path bị collider chặn tự nhiên&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_backdoor_m_bias.png&quot; alt=&quot;M-bias: điều chỉnh sai có thể mở backdoor path&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Chẳng hạn, khi đánh giá tác động của học thêm (\(X\)) lên điểm thi (\(Y\)) với năng lực ban đầu (\(Z\)) tác động lên cả hai, đường \(X \leftarrow Z \rightarrow Y\) là một đường cửa sau và sẽ được đóng lại khi ta điều chỉnh cho \(Z\).&lt;/p&gt;

&lt;h2 id=&quot;8-tập-biến-điều-chỉnh-hợp-lệ-và-sai-lệch-khi-điều-chỉnh-nhầm&quot;&gt;8. Tập biến điều chỉnh hợp lệ và sai lệch khi điều chỉnh nhầm&lt;/h2&gt;

&lt;p&gt;Bốn sơ đồ dưới đối chiếu sự khác biệt giữa tập điều chỉnh hợp lệ, tập điều chỉnh chặn nhầm biến trung gian (chỉ còn hiệu ứng trực tiếp), tập điều chỉnh nhầm collider và trường hợp không điều chỉnh.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_adjustment_valid_z1_z2.png&quot; alt=&quot;Adjustment set hợp lệ chặn các backdoor paths cần chặn&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_adjustment_valid_but_mediator.png&quot; alt=&quot;Adjustment set hợp lệ nhưng chỉ còn direct effect&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_adjustment_invalid_collider.png&quot; alt=&quot;Adjustment set sai vì điều chỉnh collider&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_adjustment_invalid_none.png&quot; alt=&quot;Không điều chỉnh khiến backdoor paths vẫn mở&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Một &lt;strong&gt;tập điều chỉnh hợp lệ (valid adjustment set)&lt;/strong&gt; chặn được mọi đường cửa sau đang mở, không mở đường giả mới và không cắt ngang con đường tác động ta muốn đo. Vì vậy, mục tiêu không phải điều chỉnh càng nhiều biến càng tốt, mà là điều chỉnh &lt;strong&gt;đúng biến&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-thực-tế&quot;&gt;Ví dụ thực tế&lt;/h3&gt;

&lt;p&gt;Trong nghiên cứu tác động của tập luyện lên sức khỏe tim mạch, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tuổi&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;thói quen ăn uống&lt;/code&gt; có thể là biến gây nhiễu, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cân nặng hiện tại&lt;/code&gt; có thể là biến trung gian, còn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;số lần nhập viện&lt;/code&gt; có thể là collider nếu nó vừa chịu ảnh hưởng của tình trạng tim mạch vừa liên quan đến mức độ theo dõi y tế. Khi mục tiêu là tổng hiệu ứng của tập luyện, ta cần điều chỉnh cho &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tuổi&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;thói quen ăn uống&lt;/code&gt;, tránh điều chỉnh cho &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cân nặng hiện tại&lt;/code&gt; và tuyệt đối không thêm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;số lần nhập viện&lt;/code&gt; chỉ vì biến này có sẵn trong tập dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;9-thiên-lệch-collider-collider-bias-rủi-ro-của-thói-quen-kiểm-soát-mọi-thứ&quot;&gt;9. Thiên lệch collider (Collider Bias): rủi ro của thói quen “kiểm soát mọi thứ”&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_collider_general_population.png&quot; alt=&quot;Trong dân số chung, hai nguyên nhân của collider có thể độc lập&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_collider_conditioned_sample.png&quot; alt=&quot;Khi condition lên collider, tương quan giả xuất hiện&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Thiên lệch collider thường phát sinh khi phân tích chỉ giới hạn trên một tập mẫu đã qua chọn lọc hoặc khi đưa một hệ quả chung vào mô hình hồi quy. Trong ví dụ tuyển dụng, dù năng lực và may mắn độc lập ở dân số chung, việc chỉ quan sát nhóm trúng tuyển tạo ra tương quan âm giả giữa hai biến này. Bài học thực hành rất rõ: thêm biến vào mô hình không phải lúc nào cũng giúp ước lượng chính xác hơn.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-điều-kiện-hóa-theo-collider-tạo-tương-quan-giả&quot;&gt;Thử nghiệm: điều kiện hóa theo collider tạo tương quan giả&lt;/h3&gt;

&lt;p&gt;\(X\) và \(Y\) độc lập nhưng cùng tác động vào \(C\); chỉ cần lọc theo \(C\) là hai biến xuất hiện tương quan âm giả.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;confound-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;collider&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;10-quy-trình-bốn-bước-khi-làm-việc-với-dag&quot;&gt;10. Quy trình bốn bước khi làm việc với DAG&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Xác định rõ mục tiêu:&lt;/strong&gt; bạn muốn ước lượng tác động nhân quả của \(X\) lên \(Y\) hay chỉ dự đoán \(Y\)? Khi mục tiêu là nhân quả, việc vẽ DAG là bước bắt buộc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Liệt kê các biến liên quan:&lt;/strong&gt; xác định các yếu tố ảnh hưởng đến can thiệp, các yếu tố ảnh hưởng đến kết quả, các biến nằm giữa can thiệp và kết quả, cũng như các hệ quả chung.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vẽ mũi tên theo kiến thức chuyên môn:&lt;/strong&gt; tập trung thể hiện đúng giả định về chiều tác động thực tế trước khi chạy mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chọn tập điều chỉnh (adjustment set):&lt;/strong&gt; giữ các biến cần thiết để chặn đường cửa sau và loại trừ các biến trung gian hoặc collider không phù hợp với câu hỏi nghiên cứu.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;11-công-cụ-tương-tác-để-tự-luyện-dag&quot;&gt;11. Công cụ tương tác để tự luyện DAG&lt;/h2&gt;

&lt;p&gt;Bạn có thể sử dụng công cụ DAG Explorer của trang web để tự vẽ và kiểm tra các cấu trúc trong bài:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;/tools/dag-explorer/standalone.html&quot; target=&quot;_blank&quot;&gt;Mở Interactive DAG Explorer&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Bạn nên thử vẽ ví dụ doanh số kem – đuối nước, ví dụ học thêm – điểm thi, ví dụ tập luyện – giảm cân – sức khỏe, rồi thử đảo chiều mũi tên để biến một confounder thành collider và quan sát sự thay đổi của tập điều chỉnh.&lt;/p&gt;

&lt;h2 id=&quot;12-tổng-kết-bài-học&quot;&gt;12. Tổng kết bài học&lt;/h2&gt;

&lt;p&gt;Hiện tượng gây nhiễu là vấn đề cốt lõi của mọi phân tích hướng đến nguyên nhân – kết quả. Nếu bỏ qua bước tư duy nhân quả, mô hình hồi quy vẫn có thể chạy hội tụ và cho khoảng hậu nghiệm rất hẹp, nhưng kết luận cuối cùng vẫn sai lệch hoàn toàn.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Biến gây nhiễu ảnh hưởng đồng thời tới cả biến can thiệp và biến kết quả nên cần được điều chỉnh để tránh ước lượng sai; DAG giúp tường minh hóa cấu trúc nhân quả trước khi chạy hồi quy; và nguyên tắc chọn biến là điều chỉnh đúng biến gây nhiễu, tránh kiểm soát tùy tiện biến trung gian hay collider.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mBEA7PKDmiY&quot;&gt;Statistical Rethinking 2023 - 05 - Elemental Confounds&lt;/a&gt; — Richard McElreath, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Biểu diễn các cấu trúc gây nhiễu cơ bản bằng đồ thị mũi tên, khớp với phần phân biệt tương quan và nhân quả trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=uanZZLlzKHw&quot;&gt;Statistical Rethinking 2023 - 06 - Good &amp;amp; Bad Controls&lt;/a&gt; — Richard McElreath, English. Phân tích các biến kiểm soát nên dùng và nên tránh, hỗ trợ quy tắc chọn biến điều chỉnh.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=U1S8Rq8IcrY&quot;&gt;4.6 - The Backdoor Adjustment&lt;/a&gt; — Brady Neal - Causal Inference, English. Trình bày tiêu chuẩn điều chỉnh đường cửa sau (backdoor adjustment), củng cố mục 7 và 8.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Trong nghiên cứu hiệu quả của việc học thêm lên điểm thi, những biến nào có thể đóng vai trò biến gây nhiễu?&lt;/li&gt;
  &lt;li&gt;Vì sao không phải lúc nào cũng nên điều chỉnh cho biến trung gian (mediator)?&lt;/li&gt;
  &lt;li&gt;Hãy nêu một ví dụ về collider trong đời sống hoặc công việc của bạn.&lt;/li&gt;
  &lt;li&gt;Nghịch lý Simpson nhắc nhở ta điều gì khi đọc số liệu gộp?&lt;/li&gt;
  &lt;li&gt;Hãy phác thảo một DAG đơn giản cho câu hỏi: “Tập thể dục có giúp ngủ ngon hơn không?”&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Pearl, J. (2009).&lt;/strong&gt; &lt;em&gt;Causality: Models, Reasoning, and Inference&lt;/em&gt; (2nd Edition). Cambridge University Press.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hernan, M. A., &amp;amp; Robins, J. M. (2020).&lt;/strong&gt; &lt;em&gt;Causal Inference: What If&lt;/em&gt;. Chapman &amp;amp; Hall/CRC.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter05/05_03_multicollinearity/&quot;&gt;5.3 Multicollinearity&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 5.1: Multiple Regression - Từ Một đến Nhiều Predictors</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter05/05_01_multiple_predictors/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter05/05_01_multiple_predictors</id>
   <content type="html">&lt;p&gt;Năm 1899, nhà thống kê người Anh Udny Yule đối diện một tranh luận gay gắt về chính sách trợ cấp xã hội: các quận phát nhiều trợ cấp ngoài trại tế bần lại có tỷ lệ nghèo cao hơn. Liệu trợ cấp có làm tăng nghèo đói? Khi Yule lần đầu tiên đưa thêm biến tỷ lệ người cao tuổi và tốc độ tăng dân số vào cùng một phương trình hồi quy, bức tranh đổi khác hoàn toàn. Đó là thời khắc hồi quy đa biến chứng minh sức mạnh thực sự của nó: biến những cuộc tranh cãi cảm tính thành phép so sánh có điều kiện rõ ràng.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu vì sao phần lớn bài toán thực tế không thể giải quyết thỏa đáng chỉ với một biến dự báo (predictor). Bạn cũng sẽ nắm nguyên tắc cốt lõi của hồi quy đa biến (multiple regression): mỗi hệ số phản ánh tác động của một biến khi tất cả các biến dự báo còn lại trong mô hình được giữ cố định. Đây là nền tảng để đọc đúng kết quả hồi quy trong toàn bộ Chương 5.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ ngắn.&lt;/strong&gt; Một công ty muốn dự đoán mức lương của nhân viên. Nếu chỉ dựa vào số năm kinh nghiệm, mô hình sẽ bỏ sót trình độ học vấn, vị trí công việc và khu vực làm việc. Hồi quy đa biến cho phép đưa đồng thời các yếu tố này vào mô hình để so sánh công bằng và sát thực tế hơn.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Nếu hai người có cùng số năm kinh nghiệm nhưng trình độ học vấn khác nhau, một mô hình chỉ có một biến dự báo có nắm bắt được chênh lệch lương giữa họ không?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-siêu-phẳng-tuyến-tính-phép-chiếu-trực-giao-và-thiên-lệch-bỏ-sót-biến&quot;&gt;Kiến thức cần nhớ: Siêu phẳng tuyến tính, Phép chiếu trực giao và Thiên lệch bỏ sót biến&lt;/h2&gt;

&lt;p&gt;Để hiểu sâu sắc cơ chế bên trong hồi quy đa biến ở trình độ đại học, hãy nối bài học này với ba trụ cột toán học:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Siêu phẳng kỳ vọng và đạo hàm riêng:&lt;/strong&gt; Khi có \(k\) biến dự báo, đường thẳng hồi quy trở thành một siêu phẳng \(\mu(x) = \alpha + \sum_{j=1}^k \beta_j x_j\) trong \(\mathbb{R}^{k+1}\). Hệ số \(\beta_j = \partial \mu / \partial x_j\) chính là đạo hàm riêng theo tọa độ \(x_j\) — giải thích vì sao ta luôn phải đọc kèm điều kiện “giữ các biến còn lại cố định”.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phép chiếu trực giao và Định lý Frisch–Waugh–Lovell:&lt;/strong&gt; Trong đại số tuyến tính, ước lượng \(\beta_1\) trong mô hình có cả \(x_1\) và \(x_2\) tương đương với việc lấy &lt;em&gt;phần dư&lt;/em&gt; của \(x_1\) sau khi đã trừ đi phần giải thích được bởi \(x_2\), rồi mới hồi quy \(y\) trên phần dư đó. Nói cách khác, \(\beta_1\) chỉ sử dụng &lt;strong&gt;phần thông tin độc lập&lt;/strong&gt; của \(x_1\) mà \(x_2\) chưa biết.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối hậu nghiệm đồng thời trên không gian vector tham số:&lt;/strong&gt; Trong hồi quy đa biến Bayes, phân phối hậu nghiệm \(p(\alpha, \beta_1, \dots, \beta_k, \sigma \mid X, y)\) chứa cả phương sai riêng của từng hệ số lẫn hiệp phương sai giữa các hệ số — cho ta biết hai biến dự báo có đang “giành nhau” cùng một phần biến thiên của \(y\) hay không.
    &lt;h2 id=&quot;1-vì-sao-một-biến-dự-báo-thường-là-chưa-đủ&quot;&gt;1. Vì sao một biến dự báo thường là chưa đủ?&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ở Chương 4, ta đã làm quen với hồi quy tuyến tính đơn:&lt;/p&gt;

\[y = \alpha + \beta x + \epsilon\]

&lt;p&gt;Mô hình này hữu ích để xây dựng trực giác, nhưng các hiện tượng thực tế hiếm khi chỉ chịu tác động của một yếu tố duy nhất. Điểm thi không chỉ phụ thuộc vào số giờ học mà còn chịu ảnh hưởng từ kiến thức nền tảng, chất lượng giấc ngủ và độ khó đề thi; giá nhà phụ thuộc đồng thời vào diện tích, vị trí, tuổi công trình, số phòng ngủ và hạ tầng; còn cân nặng liên quan đến cả chiều cao, độ tuổi, giới tính, mức độ vận động và chế độ ăn. Ép một bài toán nhiều nguyên nhân vào mô hình một biến không chỉ làm mất thông tin quan trọng mà còn dễ dẫn đến diễn giải sai ý nghĩa của hệ số. Hồi quy đa biến được xây dựng để giải quyết chính giới hạn này.&lt;/p&gt;

&lt;h2 id=&quot;2-cấu-trúc-của-mô-hình-nhiều-biến-dự-báo&quot;&gt;2. Cấu trúc của mô hình nhiều biến dự báo&lt;/h2&gt;

&lt;p&gt;Dạng tổng quát của hồi quy đa biến là:&lt;/p&gt;

\[y = \alpha + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_k x_k + \epsilon\]

&lt;p&gt;Trong đó, \(y\) là biến kết quả (outcome), \(x_1, x_2, \ldots, x_k\) là các biến dự báo (predictors), \(\alpha\) là hệ số chặn (intercept), mỗi \(\beta_j\) là hệ số của biến \(x_j\), và \(\epsilon\) là phần nhiễu ngẫu nhiên quanh xu hướng trung bình.&lt;/p&gt;

&lt;p&gt;Ba biểu đồ dưới đây minh họa cách cùng một biến kết quả thay đổi đồng thời theo nhiều chiều — khi nhìn từng biểu đồ hai chiều ta chỉ thấy một lát cắt riêng lẻ, còn hồi quy đa biến ghép các lát cắt đó thành một bề mặt chung.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_weight_vs_height_colored_by_age.png&quot; alt=&quot;Cân nặng theo chiều cao, tô màu theo tuổi&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_weight_vs_age_colored_by_height.png&quot; alt=&quot;Cân nặng theo tuổi, tô màu theo chiều cao&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_weight_height_age_3d.png&quot; alt=&quot;Góc nhìn 3D của cân nặng theo chiều cao và tuổi&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-nguyên-tắc-cốt-lõi-giữ-các-biến-khác-cố-định&quot;&gt;3. Nguyên tắc cốt lõi: “giữ các biến khác cố định”&lt;/h2&gt;

&lt;p&gt;Trong hồi quy đa biến, hệ số \(\beta_1\) không còn được đọc đơn giản là:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;cứ \(x_1\) tăng thêm 1 đơn vị thì \(y\) tăng thêm \(\beta_1\) đơn vị.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Cách đọc chính xác phải là:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;khi các biến dự báo khác trong mô hình được giữ cố định&lt;/strong&gt;, nếu \(x_1\) tăng thêm 1 đơn vị thì giá trị kỳ vọng của \(y\) thay đổi trung bình \(\beta_1\) đơn vị.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Sự bổ sung điều kiện này làm thay đổi căn bản cách diễn giải mô hình.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-1-lương-kinh-nghiệm-và-học-vấn&quot;&gt;Ví dụ 1: lương, kinh nghiệm và học vấn&lt;/h3&gt;

&lt;p&gt;Xét mô hình:&lt;/p&gt;

\[\text{Lương} = \alpha + \beta_1 \cdot \text{Kinh nghiệm} + \beta_2 \cdot \text{Học vấn} + \epsilon\]

&lt;p&gt;Ở đây, \(\beta_1\) là chênh lệch lương kỳ vọng giữa hai người có &lt;strong&gt;cùng trình độ học vấn&lt;/strong&gt; nhưng hơn kém nhau 1 năm kinh nghiệm; còn \(\beta_2\) là chênh lệch lương kỳ vọng giữa hai người có &lt;strong&gt;cùng số năm kinh nghiệm&lt;/strong&gt; nhưng khác nhau một bậc học vấn.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-2-cân-nặng-chiều-cao-và-tuổi&quot;&gt;Ví dụ 2: cân nặng, chiều cao và tuổi&lt;/h3&gt;

&lt;p&gt;Với mô hình:&lt;/p&gt;

\[\text{Cân nặng} = \alpha + \beta_1 \cdot \text{Chiều cao} + \beta_2 \cdot \text{Tuổi} + \epsilon\]

&lt;p&gt;\(\beta_1\) phản ánh mức chênh lệch cân nặng theo chiều cao giữa những người cùng độ tuổi, còn \(\beta_2\) phản ánh mức chênh lệch theo độ tuổi giữa những người cùng chiều cao.&lt;/p&gt;

&lt;h3 id=&quot;31-ví-dụ-bằng-con-số&quot;&gt;3.1. Ví dụ bằng con số&lt;/h3&gt;

&lt;p&gt;Giả sử mô hình lương ước lượng được là:&lt;/p&gt;

\[\text{Lương} = 8 + 0.6 \cdot \text{Kinh nghiệm} + 2.5 \cdot \text{Sau đại học}.\]

&lt;p&gt;Trong đó &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Kinh nghiệm&lt;/code&gt; tính bằng năm, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Sau đại học&lt;/code&gt; nhận giá trị &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; nếu có bằng sau đại học và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; nếu không, còn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Lương&lt;/code&gt; tính bằng triệu đồng/tháng. Khi đó:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Giữa hai người cùng trình độ học vấn, thêm 1 năm kinh nghiệm tương ứng với mức lương kỳ vọng cao hơn &lt;strong&gt;0.6 triệu đồng/tháng&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Giữa hai người cùng số năm kinh nghiệm, có bằng sau đại học tương ứng với mức lương kỳ vọng cao hơn &lt;strong&gt;2.5 triệu đồng/tháng&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Xét ba cá nhân cụ thể:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Người A&lt;/strong&gt; (5 năm kinh nghiệm, không có bằng sau đại học): \(8 + 0.6 \times 5 + 2.5 \times 0 = 11\) triệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Người B&lt;/strong&gt; (6 năm kinh nghiệm, không có bằng sau đại học): \(8 + 0.6 \times 6 + 2.5 \times 0 = 11.6\) triệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Người C&lt;/strong&gt; (5 năm kinh nghiệm, có bằng sau đại học): \(8 + 0.6 \times 5 + 2.5 \times 1 = 13.5\) triệu.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So sánh A với B cho thấy ý nghĩa của hệ số kinh nghiệm (chênh 0.6 triệu); so sánh A với C cho thấy ý nghĩa của hệ số học vấn (chênh 2.5 triệu).&lt;/p&gt;

&lt;h2 id=&quot;4-vì-sao-hệ-số-thay-đổi-khi-chuyển-từ-hồi-quy-đơn-sang-hồi-quy-đa-biến&quot;&gt;4. Vì sao hệ số thay đổi khi chuyển từ hồi quy đơn sang hồi quy đa biến?&lt;/h2&gt;

&lt;p&gt;Trong hồi quy đơn, một biến dự báo có thể vô tình gánh luôn phần ảnh hưởng của những biến liên quan chưa được đưa vào mô hình. Chẳng hạn, nếu người có học vấn cao hơn thường cũng có nhiều năm kinh nghiệm hơn, mô hình chỉ dùng biến học vấn sẽ gộp cả một phần tác động của kinh nghiệm vào hệ số học vấn. Khi bổ sung biến kinh nghiệm vào mô hình, hệ số học vấn có thể giảm đi — đó không phải dấu hiệu mô hình tệ hơn, mà là dấu hiệu mô hình đang tách bạch rõ hơn hai nguồn ảnh hưởng.&lt;/p&gt;

&lt;p&gt;Nói ngắn gọn, hai mô hình trả lời hai câu hỏi khác nhau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hồi quy đơn:&lt;/strong&gt; Nhìn tổng thể, biến này biến thiên cùng chiều hay ngược chiều với kết quả như thế nào?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hồi quy đa biến:&lt;/strong&gt; Khi giữ cố định các biến khác trong mô hình, biến này còn liên hệ với kết quả ở mức độ nào?&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-công-thức-thiên-lệch-bỏ-sót-biến-omitted-variable-bias&quot;&gt;Giải thích: Tính tay công thức thiên lệch bỏ sót biến (Omitted Variable Bias)&lt;/h3&gt;

&lt;p&gt;Vì sao hệ số của một biến lại thay đổi mạnh khi ta thêm một biến dự báo thứ hai? Không cần suy đoán — công thức đại số sau cho bạn câu trả lời chính xác chỉ bằng một phép nhân và một phép cộng:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giả sử cơ chế sinh dữ liệu thật&lt;/strong&gt; có hai biến đã dịch tâm \(x_1\) (học vấn) và \(x_2\) (kinh nghiệm):
\(y = 2.0\,x_1 + 3.0\,x_2 + \varepsilon,\)
trong đó tác động riêng thật sự của \(x_1\) là \(\beta_1 = 2.0\) và của \(x_2\) là \(\beta_2 = 3.0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giả sử \(x_1\) và \(x_2\) tương quan dương trong tập dữ liệu&lt;/strong&gt;, cụ thể khi hồi quy \(x_2\) theo \(x_1\) ta có độ dốc \(\gamma = 0.5\) (tức \(\mathbb{E}[x_2 \mid x_1] = 0.5\,x_1\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuyện gì xảy ra nếu bạn bỏ sót \(x_2\) và chỉ chạy hồi quy đơn \(y \sim x_1\)?&lt;/strong&gt; Lấy kỳ vọng có điều kiện hai vế theo \(x_1\):
\(\mathbb{E}[y \mid x_1] = 2.0\,x_1 + 3.0\,\mathbb{E}[x_2 \mid x_1] = 2.0\,x_1 + 3.0(0.5\,x_1) = 3.5\,x_1.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đối chiếu kết quả:&lt;/strong&gt; Hồi quy đơn trả về hệ số \(\beta_1^{\text{đơn}} = 3.5\) — bị phóng đại thêm đúng \(\beta_2 \cdot \gamma = 3.0 \times 0.5 = +1.5\) do \(x_1\) đã “gánh hộ” phần ảnh hưởng của \(x_2\). Khi bạn đưa \(x_2\) vào mô hình đa biến, hệ số của \(x_1\) hạ từ \(3.5\) xuống đúng \(2.0\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu \(x_1\) và \(x_2\) không tương quan (\(\gamma = 0\)), thì \(\beta_1^{\text{đơn}} = 2.0 + 3.0(0) = 2.0\) — hệ số không hề đổi. Chính sự tương quan giữa các biến dự báo mới là nguồn gốc làm dịch chuyển hệ số.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-hồi-quy-đa-biến-tại-sao-hệ-số-đổi-dấu-khi-thêm-biến-thứ-2&quot;&gt;Video ngắn: Hồi quy Đa biến: Tại sao Hệ số Đổi dấu khi Thêm biến thứ 2?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch05-01a-omitted-variable-bias.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 17 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): minh họa giá nhà theo số phòng ngủ: đường hồi quy đơn dốc lên giả tạo do bỏ sót diện tích, còn khi giữ diện tích cố định thì độ dốc đảo chiều đúng bản chất.&lt;/p&gt;

&lt;h2 id=&quot;5-ví-dụ-thực-tế-dự-đoán-giá-nhà&quot;&gt;5. Ví dụ thực tế: dự đoán giá nhà&lt;/h2&gt;

&lt;p&gt;Giả sử ta mô hình hóa giá nhà theo diện tích, số phòng ngủ và khoảng cách tới trung tâm:&lt;/p&gt;

\[\text{Giá nhà} = \alpha + \beta_1 \cdot \text{Diện tích} + \beta_2 \cdot \text{Số phòng ngủ} + \beta_3 \cdot \text{Khoảng cách} + \epsilon\]

&lt;p&gt;Mỗi hệ số đều gắn với điều kiện so sánh rõ ràng: \(\beta_1\) so sánh hai căn nhà cùng số phòng ngủ và cùng khoảng cách tới trung tâm nhưng chênh 1 m² diện tích; \(\beta_2\) so sánh hai căn cùng diện tích và vị trí nhưng chênh 1 phòng ngủ; \(\beta_3\) so sánh hai căn cùng diện tích và số phòng ngủ nhưng xa trung tâm hơn 1 km.&lt;/p&gt;

&lt;h3 id=&quot;51-đọc-đúng-hệ-số-số-phòng-ngủ-trong-mô-hình-giá-nhà&quot;&gt;5.1. Đọc đúng hệ số số phòng ngủ trong mô hình giá nhà&lt;/h3&gt;

&lt;p&gt;Giả sử mô hình ước lượng được:&lt;/p&gt;

\[\text{Giá nhà} = 1.2 + 0.035 \cdot \text{Diện tích} + 0.18 \cdot \text{Số phòng ngủ} - 0.25 \cdot \text{Khoảng cách},\]

&lt;p&gt;với giá tính bằng &lt;strong&gt;tỷ đồng&lt;/strong&gt;, diện tích tính bằng &lt;strong&gt;m²&lt;/strong&gt; và khoảng cách tính bằng &lt;strong&gt;km&lt;/strong&gt;. Khi giữ cố định số phòng ngủ và vị trí, căn rộng hơn 10 m² có giá kỳ vọng cao hơn:&lt;/p&gt;

\[0.035 \times 10 = 0.35\ \text{tỷ đồng}.\]

&lt;p&gt;Khi giữ cố định diện tích và vị trí, căn nhiều hơn 1 phòng ngủ có giá kỳ vọng cao hơn:&lt;/p&gt;

\[0.18\ \text{tỷ đồng}.\]

&lt;p&gt;Cần lưu ý rằng con số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.18&lt;/code&gt; chỉ áp dụng khi diện tích và vị trí giữ nguyên (tức chia lại mặt bằng có sẵn thêm một phòng), chứ không phải trong tình huống mở rộng thêm cả diện tích lẫn số phòng ngủ.&lt;/p&gt;

&lt;h2 id=&quot;6-ba-lợi-ích-chính-của-hồi-quy-đa-biến&quot;&gt;6. Ba lợi ích chính của hồi quy đa biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cải thiện độ chính xác dự đoán:&lt;/strong&gt; khi biến kết quả phụ thuộc vào nhiều yếu tố, đưa đủ các biến phù hợp giúp giảm sai số dự báo (ví dụ kết hợp giờ học, điểm nền tảng và tỷ lệ chuyên cần để dự đoán điểm thi).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tách bạch ảnh hưởng công bằng hơn:&lt;/strong&gt; giúp đánh giá đóng góp riêng của từng yếu tố thay vì dồn mọi biến thiên lên một biến đơn lẻ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tạo nền tảng cho tư duy nhân quả:&lt;/strong&gt; dù bản thân hồi quy đa biến chưa tự động chứng minh quan hệ nhân quả, nó là công cụ để điều chỉnh cho các biến gây nhiễu (confounders) sẽ học ở Bài 5.2.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;7-ba-rủi-ro-cần-lưu-ý-khi-đưa-nhiều-biến-vào-mô-hình&quot;&gt;7. Ba rủi ro cần lưu ý khi đưa nhiều biến vào mô hình&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bỏ sót biến quan trọng:&lt;/strong&gt; thiếu biến có liên quan đến cả biến dự báo lẫn kết quả sẽ làm sai lệch các hệ số còn lại.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các biến dự báo quá giống nhau:&lt;/strong&gt; khi hai biến mang thông tin gần như trùng lặp, mô hình khó tách riêng đóng góp của từng biến (chủ đề &lt;strong&gt;đa cộng tuyến&lt;/strong&gt; ở Bài 5.3).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đưa biến vào thiếu cân nhắc:&lt;/strong&gt; không phải cứ kiểm soát càng nhiều biến càng tốt; có những biến cần điều chỉnh nhưng cũng có những biến nếu đưa vào lại gây thiên lệch (chủ đề &lt;strong&gt;confounding và DAGs&lt;/strong&gt; ở Bài 5.2).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;8-nhìn-hồi-quy-đa-biến-như-một-mô-hình-sinh-dữ-liệu&quot;&gt;8. Nhìn hồi quy đa biến như một mô hình sinh dữ liệu&lt;/h2&gt;

&lt;p&gt;Theo tinh thần Bayes, mỗi quan sát mang một tập đặc trưng riêng; các đặc trưng đó kết hợp để tạo nên giá trị kỳ vọng, còn giá trị quan sát thực tế dao động quanh mức kỳ vọng do các yếu tố chưa quan sát được (như sức khỏe hay tâm lý trong ngày thi). Cách nhìn này giúp ta luôn gắn phương trình toán học với cơ chế thực tế.&lt;/p&gt;

&lt;h2 id=&quot;9-cách-diễn-giải-kết-quả-khi-báo-cáo&quot;&gt;9. Cách diễn giải kết quả khi báo cáo&lt;/h2&gt;

&lt;p&gt;Một phát biểu diễn giải chuẩn gồm đủ ba yếu tố: nêu rõ tên biến dự báo, ghi rõ điều kiện “giữ các biến khác cố định” và gắn với đơn vị đo thực tế. Thay vì chỉ viết \(\beta_1 = 0.42\), hãy diễn đạt:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Giữ nguyên trình độ học vấn và vị trí công việc, mỗi năm kinh nghiệm tăng thêm đi kèm mức lương kỳ vọng cao hơn khoảng X triệu đồng.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;10-kết-nối-sang-các-bài-tiếp-theo&quot;&gt;10. Kết nối sang các bài tiếp theo&lt;/h2&gt;

&lt;p&gt;Hồi quy đa biến mở ra ba câu hỏi trọng tâm cho phần còn lại của Chương 5: có biến nào đang gây nhiễu mối quan hệ ta quan tâm không (Bài 5.2), các biến dự báo có trùng lặp thông tin quá mức không (Bài 5.3), và tác động của một biến có thay đổi theo giá trị của biến khác không (Bài 5.4).&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Hồi quy đa biến cho phép mô tả đồng thời nhiều yếu tố tác động lên biến kết quả; mỗi hệ số luôn phải được đọc kèm điều kiện “giữ các biến khác cố định”; và việc hệ số thay đổi khi thêm biến mới thường phản ánh quá trình tách bạch ảnh hưởng rõ hơn chứ không phải lỗi mô hình.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EkAQAi3a4js&quot;&gt;Multiple Regression, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Giải thích từng hệ số là đóng góp có điều kiện khi các biến dự báo khác đã có mặt trong mô hình, khớp với trọng tâm bài học.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mBEA7PKDmiY&quot;&gt;Statistical Rethinking 2023 - 05 - Elemental Confounds&lt;/a&gt; — Richard McElreath, English. Phân tích vì sao thêm một biến làm thay đổi ý nghĩa hệ số của biến kia, bổ trợ cho mục 4.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Covariance and the regression line&lt;/td&gt;
          &lt;td&gt;Regression&lt;/td&gt;
          &lt;td&gt;Probability and Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=ualmyZiPs9w) — Khan Academy, English. Minh họa vai trò của hiệp phương sai trong đường hồi quy, giúp hiểu mối liên hệ giữa các biến dự báo.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Trong bài toán dự đoán giá nhà, vì sao chỉ dùng biến diện tích thường là chưa đủ?&lt;/li&gt;
  &lt;li&gt;Điều kiện “giữ các biến khác cố định” có ý nghĩa cụ thể như thế nào trong ví dụ lương theo kinh nghiệm và học vấn?&lt;/li&gt;
  &lt;li&gt;Hãy nêu một bài toán thực tế trong lĩnh vực của bạn đòi hỏi ít nhất ba biến dự báo.&lt;/li&gt;
  &lt;li&gt;Trong hoàn cảnh nào một hệ số trong hồi quy đơn sẽ khác biệt đáng kể so với hệ số tương ứng trong hồi quy đa biến?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Hill, J., &amp;amp; Vehtari, A. (2020).&lt;/strong&gt; &lt;em&gt;Regression and Other Stories&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter05/05_02_confounding_dags/&quot;&gt;5.2 Confounding và DAGs&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 4.6: Case Study Nâng Cao - Model Checking & Prediction Trên Dataset Phức Tạp</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_06_case_study_complex_dataset/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_06_case_study_complex_dataset</id>
   <content type="html">&lt;p&gt;Khi đối diện một bảng dữ liệu gần 54.000 viên kim cương với hệ số tương quan giữa trọng lượng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; và giá &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; lên tới \(0.922\), cám dỗ lớn nhất của người phân tích là kết luận bài toán đã xong. Thế nhưng thị trường kim cương không vận hành theo đường thẳng: một viên kim cương 2 carat không đắt gấp đôi viên 1 carat, mà đắt gấp nhiều lần vì độ hiếm tăng theo hàm mũ, và chênh lệch giữa hai hạng chất lượng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt; có thể lên tới hàng nghìn đô la. Đây là sân tập thực sự cho quy trình Bayes đa tầng.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ biết cách vận hành đầy đủ một quy trình Bayes trên tập dữ liệu có cấu trúc phức tạp, nơi việc khớp được mô hình mới chỉ là điều kiện cần chứ chưa phải điều kiện đủ. Trọng tâm của bài là rèn luyện năng lực lập luận định lượng: chẩn đoán sai lệch, xác định rõ nguyên nhân cấu trúc và đề xuất can thiệp đúng chỗ thay vì chỉnh sửa theo cảm tính.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ dẫn nhập.&lt;/strong&gt; Trong tập dữ liệu kim cương, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; có tương quan rất cao, nhưng một mô hình tuyến tính đơn giản vẫn có thể sai lệch nghiêm trọng ở đuôi phải của phân phối giá — tức hoạt động ổn ở vùng phổ thông nhưng thất bại ở phân khúc mang giá trị kinh tế cao nhất.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Vì sao một chỉ số tổng hợp rất cao như tương quan trên 0.9 vẫn chưa đủ để kết luận mô hình đáng tin cậy cho bài toán dự đoán thực tế?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-phân-phối-log-normal-độ-bao-phủ-có-điều-kiện-và-gộp-một-phần-partial-pooling&quot;&gt;Kiến thức cần nhớ: Phân phối Log-Normal, Độ bao phủ có điều kiện và Gộp một phần (Partial Pooling)&lt;/h2&gt;

&lt;p&gt;Để làm chủ một bài toán quy mô lớn và phi đồng nhất như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt;, ba công cụ lý thuyết sau đóng vai trò xương sống:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối Log-Normal và hiệu chỉnh bất đẳng thức Jensen:&lt;/strong&gt; Nếu \(\log Y \sim \mathcal{N}(\mu, \sigma^2)\) thì \(Y = e^{\log Y}\) có trung vị là \(e^\mu\), nhưng vì hàm mũ lồi chặt (bất đẳng thức Jensen: \(\mathbb{E}[e^Z] &amp;gt; e^{\mathbb{E}[Z]}\)), kỳ vọng thực sự là \(\mathbb{E}[Y] = \exp(\mu + \sigma^2/2)\). Quên số hạng \(\sigma^2/2\) sẽ tạo ra sai lệch định giá thấp có hệ thống trên thang tiền tệ gốc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh giá có điều kiện (Conditional Calibration) và độ bao phủ ngoài mẫu:&lt;/strong&gt; Một khoảng dự đoán 90% có thể đạt độ bao phủ tổng thể 92% nhờ thừa bao phủ ở 90% dữ liệu phổ thông (kim cương nhỏ), trong khi chỉ bao phủ 72% ở 10% phân khúc cao cấp (kim cương lớn). Chia miền theo dải &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; biến kiểm định tổng thể thành kính hiển vi phát hiện sai lệch cục bộ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình phân cấp và cơ chế co cụm (Partial Pooling / Shrinkage):&lt;/strong&gt; Khi dữ liệu chia thành nhiều nhóm có cỡ mẫu chênh lệch, đặt tiên nghiệm chung \(\alpha_g \sim \mathcal{N}(\alpha_0, \tau_\alpha^2)\) cho phép các nhóm chia sẻ thông tin thống kê. Nhóm nhiều dữ liệu giữ sát trung bình riêng; nhóm ít dữ liệu tự động co nhẹ về trung tâm chung \(\alpha_0\) theo tỷ lệ độ chính xác.
    &lt;h2 id=&quot;1-bối-cảnh-dữ-liệu-vì-sao-diamonds-là-phép-thử-khó&quot;&gt;1. Bối cảnh dữ liệu: vì sao &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; là phép thử khó?&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ta làm việc với tập dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; (trong thư viện &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seaborn&lt;/code&gt;), gồm biến phản hồi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; và nhiều biến mô tả cả kích thước hình học lẫn chất lượng như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;color&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clarity&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;depth&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;table&lt;/code&gt;. Tập dữ liệu này buộc người phân tích đối diện đồng thời với ba lớp phức tạp: mối quan hệ tuy mạnh nhưng không đồng nhất trên toàn miền biến dự báo, cấu trúc phân nhóm mang ý nghĩa thực chất, và hành vi đuôi phải của giá ảnh hưởng trực tiếp tới bài toán định giá.&lt;/p&gt;

&lt;h3 id=&quot;11-trích-đoạn-dữ-liệu-quan-sát&quot;&gt;1.1. Trích đoạn dữ liệu quan sát&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;carat&lt;/th&gt;
      &lt;th&gt;cut&lt;/th&gt;
      &lt;th&gt;color&lt;/th&gt;
      &lt;th&gt;clarity&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;depth&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;table&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;price&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;x&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;y&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;z&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.23&lt;/td&gt;
      &lt;td&gt;Ideal&lt;/td&gt;
      &lt;td&gt;E&lt;/td&gt;
      &lt;td&gt;SI2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;61.5&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;55.0&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;326&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.95&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.98&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.43&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.21&lt;/td&gt;
      &lt;td&gt;Premium&lt;/td&gt;
      &lt;td&gt;E&lt;/td&gt;
      &lt;td&gt;SI1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;59.8&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;61.0&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;326&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.89&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.84&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.31&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.23&lt;/td&gt;
      &lt;td&gt;Good&lt;/td&gt;
      &lt;td&gt;E&lt;/td&gt;
      &lt;td&gt;VS1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;56.9&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;65.0&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;327&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.05&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.07&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.31&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.29&lt;/td&gt;
      &lt;td&gt;Premium&lt;/td&gt;
      &lt;td&gt;I&lt;/td&gt;
      &lt;td&gt;VS2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;62.4&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;58.0&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;334&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.20&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.23&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.63&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.31&lt;/td&gt;
      &lt;td&gt;Good&lt;/td&gt;
      &lt;td&gt;J&lt;/td&gt;
      &lt;td&gt;SI2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;63.3&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;58.0&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;335&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.34&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.35&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.75&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;12-tóm-tắt-định-lượng-ban-đầu&quot;&gt;1.2. Tóm tắt định lượng ban đầu&lt;/h3&gt;

&lt;p&gt;Trên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n = 53,940&lt;/code&gt; quan sát, biến &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; có trung bình khoảng 0.798 và trung vị khoảng 0.70, trong khi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; có trung bình khoảng 3932.8 nhưng trung vị chỉ khoảng 2401 — dấu hiệu rõ rệt của phân phối lệch phải. Tương quan Pearson giữa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; đạt khoảng 0.922, rất mạnh ở mức tổng thể; tuy vậy, chỉ khoảng 3.07% quan sát rơi vào vùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price &amp;gt; 15000&lt;/code&gt;, và chính phân khúc nhỏ này lại là nơi sai lệch mô hình gây tổn thất lớn nhất trong bài toán định giá cao cấp.&lt;/p&gt;

&lt;h2 id=&quot;2-từ-số-liệu-đến-lập-luận-định-lượng&quot;&gt;2. Từ số liệu đến lập luận định lượng&lt;/h2&gt;

&lt;p&gt;Một phân tích chặt chẽ không dừng ở nhận xét định tính như “có vẻ lệch”, mà phải gắn từng kết luận với một thước đo thống kê cụ thể.&lt;/p&gt;

&lt;p&gt;Hệ số tương quan mẫu giữa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; được tính bởi:&lt;/p&gt;

\[r_{xy}=\frac{\sum_{i=1}^{n}(x_i-\bar x)(y_i-\bar y)}{\sqrt{\sum_{i=1}^{n}(x_i-\bar x)^2}\sqrt{\sum_{i=1}^{n}(y_i-\bar y)^2}} \approx 0.922.\]

&lt;p&gt;Con số này chỉ xác nhận rằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; biến thiên đồng pha mạnh theo nghĩa tuyến tính toàn cục. Nó không đảm bảo phần dư phân bố ngẫu nhiên quanh 0, không đảm bảo phương sai sai số đồng nhất và không đảm bảo mô hình dự báo tốt ở đuôi phải. Nói cách khác, tương quan cao cho thấy có tín hiệu mạnh, nhưng chưa chứng minh cấu trúc mô hình sinh dữ liệu là đúng.&lt;/p&gt;

&lt;p&gt;Tương tự, tỷ lệ quan sát ở vùng đuôi phải được định lượng cụ thể:&lt;/p&gt;

\[\hat p_{\text{price}&amp;gt;15000}=\frac{1}{n}\sum_{i=1}^{n}\mathbf 1(y_i&amp;gt;15000)\approx 0.0307.\]

&lt;p&gt;Dù chỉ chiếm khoảng 3% số lượng quan sát, vùng đuôi này lại mang trọng số giá trị rất lớn; do đó một mô hình khớp tốt ở trung tâm nhưng sai ở đuôi vẫn tiềm ẩn rủi ro cao khi dùng cho định giá hoặc quản trị danh mục cao cấp.&lt;/p&gt;

&lt;p&gt;Cuối cùng, để kiểm tra giả định phương sai đồng nhất, ta sử dụng chỉ báo:&lt;/p&gt;

\[\operatorname{corr}(\lvert e_i \rvert,x_i), \qquad e_i=y_i-\hat y_i.\]

&lt;p&gt;Khi độ lớn phần dư tăng theo biến dự báo, giả định dùng chung một mức nhiễu \(\sigma\) cho toàn bộ miền dữ liệu sẽ không còn phù hợp.&lt;/p&gt;

&lt;h2 id=&quot;3-mô-hình-cơ-sở-điểm-chuẩn-cần-thiết-nhưng-chưa-phải-đích-đến&quot;&gt;3. Mô hình cơ sở: điểm chuẩn cần thiết nhưng chưa phải đích đến&lt;/h2&gt;

&lt;p&gt;Ta bắt đầu với mô hình tuyến tính Gaussian cơ sở:&lt;/p&gt;

\[\text{price}_i \sim \mathcal N(\mu_i,\sigma), \qquad \mu_i=\alpha+\beta\,\text{carat}_i.\]

&lt;p&gt;Ta xây dựng mô hình này &lt;strong&gt;không phải vì tin rằng dữ liệu đơn giản đến mức đó, mà vì mọi cải thiện về sau đều cần một mốc chuẩn rõ ràng để đối chiếu&lt;/strong&gt;. Trên tập &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt;, mô hình cơ sở thường nắm bắt khá tốt xu hướng trung bình chung, nhưng sớm bộc lộ ba hạn chế: biên độ sai số tăng mạnh theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, đuôi phải của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; bị nén quá mỏng và sự khác biệt theo nhóm chất lượng (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clarity&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;color&lt;/code&gt;) chưa được mô tả.&lt;/p&gt;

&lt;h2 id=&quot;4-kiểm-tra-dự-báo-hậu-nghiệm-ppc-nhiều-tầng&quot;&gt;4. Kiểm tra dự báo hậu nghiệm (PPC) nhiều tầng&lt;/h2&gt;

&lt;p&gt;Với dữ liệu phức tạp, một phép kiểm tra PPC duy nhất là không đủ. Ta cần chuỗi kiểm tra đi từ toàn cục đến có điều kiện để xác định chính xác mô hình đúng ở đâu và sai ở đâu.&lt;/p&gt;

&lt;p&gt;Ở &lt;strong&gt;tầng toàn cục&lt;/strong&gt;, ta so sánh phân phối dữ liệu quan sát với phân phối dự báo hậu nghiệm để kiểm tra đồng thời vị trí trung tâm, độ phân tán và độ dày vùng đuôi — bước giúp phát hiện sớm các sai lệch thô.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_observed_vs_predicted.png&quot; alt=&quot;So sánh dữ liệu quan sát và posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ở &lt;strong&gt;tầng thống kê mục tiêu&lt;/strong&gt;, ta đối chiếu mô hình qua các đại lượng định lượng cụ thể:&lt;/p&gt;

\[T_1(y)=\bar y,\quad T_2(y)=\operatorname{Var}(y),\quad T_3(y)=Q_{0.95}(y),\quad T_4(y)=\frac{1}{n}\sum_{i=1}^{n}\mathbf 1(y_i&amp;gt;15000).\]

&lt;p&gt;Nếu mô hình tái tạo tốt \(T_1\) nhưng lệch rõ rệt ở \(T_3\) hoặc \(T_4\), kết luận chính xác phải là “mô hình ổn ở trung tâm nhưng yếu ở vùng đuôi” — sự phân biệt mang ý nghĩa quyết định đối với các bài toán định giá phân khúc cao.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_test_stat_mean.png&quot; alt=&quot;PPC cho mean&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_variance_check.png&quot; alt=&quot;PPC cho variance&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ở &lt;strong&gt;tầng có điều kiện theo biến dự báo&lt;/strong&gt;, ta chia &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; thành từng dải giá trị \(B_k\) và kiểm tra riêng thay vì gộp chung:&lt;/p&gt;

\[T_{\text{bin},k}(y)=\operatorname{Var}(y\mid x\in B_k),\qquad T^{(0.95)}_{\text{bin},k}(y)=Q_{0.95}(y\mid x\in B_k).\]

&lt;p&gt;Cách kiểm tra này giúp phát hiện tình huống mô hình khớp tốt ở dải &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; phổ biến nhưng sai lệch có hệ thống ở dải &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; lớn.&lt;/p&gt;

&lt;p&gt;Ở &lt;strong&gt;tầng theo nhóm chất lượng&lt;/strong&gt;, ta kiểm tra khả năng tái tạo trung bình theo từng nhóm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clarity&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;color&lt;/code&gt;:&lt;/p&gt;

\[T_g(y)=\bar y_g.\]

&lt;p&gt;Khi mô hình chỉ dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; không tái hiện được chênh lệch giữa các nhóm này, đó là bằng chứng cho thấy mô hình sinh dữ liệu đang bỏ sót yếu tố cấu trúc quan trọng.&lt;/p&gt;

&lt;h2 id=&quot;5-phân-tích-phần-dư-chẩn-đoán-cơ-chế-sai-lệch&quot;&gt;5. Phân tích phần dư: chẩn đoán cơ chế sai lệch&lt;/h2&gt;

&lt;p&gt;Nếu PPC cung cấp bức tranh ở mức phân phối, thì phân tích phần dư giúp soi sát cơ chế sai lệch. Câu hỏi trọng tâm không phải “phần dư có nhỏ không” mà là “phần dư có còn chứa cấu trúc có hệ thống không”.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_scatter.png&quot; alt=&quot;Dấu hiệu heteroskedasticity trên scatter&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_residuals.png&quot; alt=&quot;Residuals vs fitted: dạng quạt&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonnormal_qq.png&quot; alt=&quot;Q-Q plot khi đuôi residual lệch&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Trên dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt;, hình quạt trên biểu đồ phần dư theo giá trị ước lượng cho thấy độ bất định tăng rõ rệt theo quy mô giá và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, còn độ lệch ở hai đầu biểu đồ Q–Q cho thấy giả định phân phối Chuẩn đơn giản chưa đủ để mô tả vùng đuôi. Hệ quả là khoảng dự đoán ở vùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; cao sẽ bị hẹp hơn thực tế nếu giữ nguyên mô hình cơ sở.&lt;/p&gt;

&lt;h2 id=&quot;6-dự-đoán-cho-ra-quyết-định-và-độ-bao-phủ-ngoài-mẫu&quot;&gt;6. Dự đoán cho ra quyết định và độ bao phủ ngoài mẫu&lt;/h2&gt;

&lt;p&gt;Trong báo cáo dự đoán, cần phân biệt rạch ròi giữa bất định của giá trị trung bình có điều kiện và bất định của một quan sát mới:&lt;/p&gt;

\[p(\mu_*\mid y,x_*) \quad \text{và} \quad p(\tilde y_*\mid y,x_*).\]

&lt;p&gt;Phân phối thứ hai luôn rộng hơn vì bao hàm cả nhiễu cá thể. Dùng khoảng của \(p(\mu_*\mid y,x_*)\) để dự báo giá cho một viên kim cương cụ thể sẽ dẫn đến đánh giá quá lạc quan về độ chính xác.&lt;/p&gt;

&lt;p&gt;Một thước đo thực nghiệm quan trọng khác là &lt;strong&gt;tỷ lệ bao phủ ngoài mẫu&lt;/strong&gt; (out-of-sample coverage):&lt;/p&gt;

\[\text{Coverage}_{90\%}=\frac{1}{m}\sum_{j=1}^{m}\mathbf 1\{y_j^{\text{test}}\in \text{PI}_{90\%}(x_j)\}.\]

&lt;p&gt;Nếu tỷ lệ bao phủ sụt giảm mạnh ở vùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; lớn, đó là bằng chứng trực tiếp cho thấy mô hình chưa đáng tin cậy ở phân khúc giá cao, bất kể các chỉ số tổng thể có vẻ thuận lợi.&lt;/p&gt;

&lt;h2 id=&quot;7-điều-chỉnh-mô-hình-đi-từ-triệu-chứng-đến-can-thiệp&quot;&gt;7. Điều chỉnh mô hình: đi từ triệu chứng đến can thiệp&lt;/h2&gt;

&lt;p&gt;Một quy trình hoàn chỉnh phải chuyển hóa kết quả chẩn đoán thành bước sửa đổi có cơ chế rõ ràng. Mỗi can thiệp chỉ hợp lệ khi trả lời được ba câu hỏi: triệu chứng nào cần xử lý, thành phần toán học nào được thay đổi và tiêu chí hậu kiểm nào xác nhận sự cải thiện là thực chất.&lt;/p&gt;

&lt;p&gt;Trên tập &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt;, ba nhóm triệu chứng xuất hiện đồng thời: đuôi phải của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; dày hơn dự báo Gaussian, biên độ phần dư tăng theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; và có sai lệch theo nhóm chất lượng. Tương ứng với đó là ba hướng can thiệp có cơ sở lý thuyết rõ ràng.&lt;/p&gt;

&lt;h3 id=&quot;71-can-thiệp-1-biến-đổi-log-để-xử-lý-đuôi-phải-và-nhiễu-nhân&quot;&gt;7.1. Can thiệp 1: biến đổi log để xử lý đuôi phải và nhiễu nhân&lt;/h3&gt;

&lt;p&gt;Khi biến giá lệch phải mạnh, giả định nhiễu cộng (additive noise) ở thang đo gốc thường không hợp lý bằng giả định nhiễu nhân (multiplicative noise) — nơi biến động theo tỷ lệ phần trăm ổn định hơn biến động tuyệt đối. Khi đó, mô hình:&lt;/p&gt;

\[\log(\text{price}_i) \sim \mathcal N(\mu_i,\sigma)\]

&lt;p&gt;phản ánh sát hơn cơ chế sinh dữ liệu, giúp phân phối phần dư cân đối hơn, giảm hiện tượng phương sai thay đổi và khắc phục tình trạng khoảng dự đoán quá hẹp ở vùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; lớn.&lt;/p&gt;

&lt;p&gt;Tuy nhiên, khi quy đổi dự báo từ thang log về thang giá gốc, cần lưu ý giá trị kỳ vọng của phân phối log-normal không phải là \(\exp(\mu_*)\) mà là:&lt;/p&gt;

\[\mathbb E[\text{price}_*\mid y,x_*]=\exp\!\left(\mu_*+\frac{\sigma_*^2}{2}\right),\]

&lt;p&gt;trong đó \(\mu_*\) và \(\sigma_*\) là trung bình và độ lệch chuẩn điều kiện trên thang log. Bỏ qua số hạng \(\sigma_*^2/2\) sẽ dẫn đến ước lượng thấp có hệ thống trên thang đo gốc.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_46_intervention_log_transform.png&quot; alt=&quot;Minh họa can thiệp 1: log-transform giảm heteroskedasticity và cải thiện coverage ở vùng carat cao&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;72-can-thiệp-2-mô-hình-hóa-quan-hệ-phi-tuyến-có-kiểm-soát&quot;&gt;7.2. Can thiệp 2: mô hình hóa quan hệ phi tuyến có kiểm soát&lt;/h3&gt;

&lt;p&gt;Nếu phần dư vẫn còn độ cong sau khi ổn định thang đo, vấn đề nằm ở dạng hàm trung bình. Khi đó ta mở rộng hàm tuyến tính:&lt;/p&gt;

\[\mu_i=\alpha+\beta\,\text{carat}_i\]

&lt;p&gt;thành một hàm phi tuyến linh hoạt hơn dựa trên các hàm cơ sở (basis functions như spline):&lt;/p&gt;

\[\mu_i=\alpha+f(\text{carat}_i), \qquad f(\cdot)=\sum_{k=1}^{K} w_k B_k(\cdot),\]

&lt;p&gt;trong đó phân phối tiên nghiệm trên các trọng số \(w_k\) đóng vai trò điều chuẩn để tránh quá khớp. Cách làm này giúp đường trung bình bám sát cả đầu thấp lẫn đầu cao của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, cải thiện đồng bộ kết quả PPC theo từng dải giá trị.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_46_intervention_nonlinear.png&quot; alt=&quot;Minh họa can thiệp 2: mô hình phi tuyến bắt được độ cong của quan hệ carat-price tốt hơn mô hình tuyến tính&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;73-can-thiệp-3-đưa-cấu-trúc-nhóm-vào-mô-hình-bằng-gộp-một-phần-partial-pooling&quot;&gt;7.3. Can thiệp 3: đưa cấu trúc nhóm vào mô hình bằng gộp một phần (partial pooling)&lt;/h3&gt;

&lt;p&gt;Với các biến phân loại như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;color&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clarity&lt;/code&gt;, cách tiếp cận Bayes tự nhiên là dùng mô hình phân cấp (hierarchical model), chẳng hạn cho phép hệ số chặn thay đổi theo nhóm:&lt;/p&gt;

\[\mu_i=\alpha_{g(i)}+f(\text{carat}_i), \qquad \alpha_g\sim\mathcal N(\alpha_0,\tau_\alpha).\]

&lt;p&gt;Cơ chế &lt;strong&gt;gộp một phần&lt;/strong&gt; (partial pooling) dung hòa hai cực đoan: không ép mọi nhóm giống hệt nhau (gộp hoàn toàn — complete pooling), nhưng cũng không để các nhóm ước lượng tách biệt hoàn toàn (không gộp — no pooling). Nhờ đó, các nhóm có ít quan sát được co nhẹ về trung tâm chung một cách có nguyên tắc, giúp giảm phương sai ước lượng và ổn định dự báo ngoài mẫu. Nếu sau bước này PPC theo nhóm vẫn chưa đạt, ta có thể cân nhắc thêm hệ số dốc theo nhóm, tương tác giữa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; và chất lượng hoặc phương sai khác nhau theo phân khúc.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_46_intervention_group_effects.png&quot; alt=&quot;Minh họa can thiệp 3: thêm cấu trúc nhóm giúp calibration theo cut gần dữ liệu quan sát hơn&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-gộp-một-phần-partial-pooling-co-các-nhóm-về-trung-bình-chung&quot;&gt;Thử nghiệm: gộp một phần (partial pooling) co các nhóm về trung bình chung&lt;/h3&gt;

&lt;p&gt;Tăng \(\tau\) để quan sát sự chuyển dịch từ gộp hoàn toàn sang không gộp và đối chiếu với phân phối hậu nghiệm của \(\tau\).&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;pooling-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-hiệu-chỉnh-log-normal-và-công-thức-co-cụm-partial-pooling&quot;&gt;Giải thích: Tính tay hiệu chỉnh Log-Normal và công thức co cụm Partial Pooling&lt;/h3&gt;

&lt;p&gt;Hai công thức cốt lõi ở mục 7.1 và 7.3 sẽ trở nên cực kỳ rõ ràng khi bạn tự thay số kiểm tra bằng tay:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Kiểm chứng hiệu chỉnh Log-Normal (Can thiệp 1):&lt;/strong&gt;
Giả sử mô hình &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(price)&lt;/code&gt; dự đoán cho một viên kim cương cụ thể với phân phối dự báo trên thang log là \(\mathcal{N}(\mu_* = 8.0,\ \sigma_*^2 = 0.4^2)\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Nếu quy đổi ngây thơ bằng \(\exp(\mu_*)\): ta nhận được \(\exp(8.0) \approx 2\,981\) USD (đây thực chất là &lt;strong&gt;trung vị&lt;/strong&gt; dự đoán, không phải giá kỳ vọng).&lt;/li&gt;
  &lt;li&gt;Quy đổi đúng cho &lt;strong&gt;giá kỳ vọng&lt;/strong&gt;:
\(\mathbb{E}[\text{price}_* \mid y, x_*] = \exp\!\left(8.0 + \frac{0.4^2}{2}\right) = \exp(8.08) \approx 3\,229\text{ USD}.\)&lt;/li&gt;
  &lt;li&gt;Mức chênh lệch là \(+248\) USD (tương đương &lt;strong&gt;+8.3%&lt;/strong&gt;) chỉ do độ bất đối xứng của hàm mũ. Khi độ nhiễu \(\sigma_*\) càng lớn, sai lệch do bỏ quên \(\sigma_*^2/2\) càng nghiêm trọng.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Kiểm chứng cơ chế co cụm Partial Pooling (Can thiệp 3):&lt;/strong&gt;
Giả sử trên thang log, trung tâm chung giữa các nhóm chất lượng là \(\alpha_0 = 8.0\) với phương sai giữa các nhóm \(\tau_\alpha^2 = 0.25\) (độ chính xác tiên nghiệm \(1/\tau_\alpha^2 = 4\)), còn nhiễu trong từng nhóm có phương sai \(\sigma^2 = 1.0\). Xét một nhóm hiếm chỉ có \(n_g = 2\) viên kim cương với trung bình mẫu \(\bar y_g = 9.0\) (độ chính xác dữ liệu \(n_g/\sigma^2 = 2\)). Hậu nghiệm của hệ số chặn nhóm \(\alpha_g\) là trung bình trọng số theo độ chính xác:&lt;/p&gt;

\[\hat\alpha_g = \frac{\frac{n_g}{\sigma^2}\bar y_g + \frac{1}{\tau_\alpha^2}\alpha_0}{\frac{n_g}{\sigma^2} + \frac{1}{\tau_\alpha^2}} = \frac{2(9.0) + 4(8.0)}{2 + 4} = \frac{50}{6} \approx 8.33.\]

&lt;p&gt;Thay vì tin tuyệt đối vào trung bình noisy \(9.0\) từ chỉ 2 viên (no pooling), partial pooling kéo ước lượng 2/3 quãng đường về trung tâm chung \(8.0\). Ngược lại, với một nhóm lớn có \(n_g = 200\) viên, trọng số dữ liệu là \(200\) áp đảo hoàn toàn trọng số tiên nghiệm \(4\), nên ước lượng bám sát dữ liệu của chính nhóm đó.&lt;/p&gt;

&lt;h3 id=&quot;74-tiêu-chí-đánh-giá-sau-mỗi-bước-điều-chỉnh&quot;&gt;7.4. Tiêu chí đánh giá sau mỗi bước điều chỉnh&lt;/h3&gt;

&lt;p&gt;Một sửa đổi chỉ được xem là thành công khi vượt qua cùng bộ tiêu chí hậu kiểm (PPC toàn cục, PPC vùng đuôi, PPC theo dải &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, chẩn đoán phần dư và tỷ lệ bao phủ ngoài mẫu) và thỏa mãn đồng thời hai điều kiện: giảm rõ rệt sai lệch ở triệu chứng mục tiêu và không làm suy giảm chất lượng ở những vùng trước đó đã ổn định.&lt;/p&gt;

&lt;p&gt;Trình tự khuyến nghị là đi từ can thiệp ít xâm lấn đến thay đổi cấu trúc sâu: trước hết xử lý thang đo bằng biến đổi log, tiếp theo xử lý độ cong bằng hàm phi tuyến có điều chuẩn, rồi mới bổ sung cấu trúc nhóm phân cấp. Thứ tự này giúp tách bạch nguyên nhân và kiểm chứng rõ hiệu quả của từng bước.&lt;/p&gt;

&lt;h3 id=&quot;75-minh-họa-kết-quả-thử-nghiệm-qua-từng-bước-can-thiệp&quot;&gt;7.5. Minh họa kết quả thử nghiệm qua từng bước can thiệp&lt;/h3&gt;

&lt;p&gt;Bảng sau tóm tắt một vòng thử nghiệm định hướng trên tập dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; (chia tập huấn luyện/kiểm tra theo tỷ lệ 80/20, đánh giá trên cùng bộ tiêu chí):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Mô hình minh họa&lt;/th&gt;
      &lt;th&gt;Tín hiệu cần xử lý&lt;/th&gt;
      &lt;th&gt;Kết quả quan sát&lt;/th&gt;
      &lt;th&gt;Diễn giải&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Baseline: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price ~ carat&lt;/code&gt; (Gaussian)&lt;/td&gt;
      &lt;td&gt;Phương sai thay đổi&lt;/td&gt;
      &lt;td&gt;\(\operatorname{corr}(\lvert e \rvert,\text{carat})\approx 0.579\)&lt;/td&gt;
      &lt;td&gt;Biên độ sai số tăng mạnh theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, bác bỏ giả định nhiễu đồng nhất.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Baseline: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price ~ carat&lt;/code&gt; (Gaussian)&lt;/td&gt;
      &lt;td&gt;Bao phủ ở vùng giá cao&lt;/td&gt;
      &lt;td&gt;Tỷ lệ bao phủ 90% toàn cục khoảng 0.921, nhưng ở nhóm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; cao chỉ khoảng 0.728&lt;/td&gt;
      &lt;td&gt;Khoảng dự đoán có vẻ đạt chuẩn toàn cục nhưng thiếu bao phủ nghiêm trọng ở phân khúc quan trọng nhất.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Can thiệp 1: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(price) ~ carat&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Ổn định phương sai theo biến dự báo&lt;/td&gt;
      &lt;td&gt;\(\operatorname{corr}(\lvert e_{\log} \rvert,\text{carat})\approx 0.269\)&lt;/td&gt;
      &lt;td&gt;Chỉ báo phương sai thay đổi giảm rõ rệt, phù hợp với giả thuyết nhiễu nhân.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Can thiệp 1: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(price) ~ carat&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Bao phủ ở vùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; cao&lt;/td&gt;
      &lt;td&gt;Tỷ lệ bao phủ 90% ở nhóm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; cao tăng lên khoảng 0.850&lt;/td&gt;
      &lt;td&gt;Chất lượng dự báo ở phân khúc lớn được cải thiện đáng kể so với baseline.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Can thiệp 1 (kiểm tra vùng đuôi)&lt;/td&gt;
      &lt;td&gt;Hiệu chuẩn vùng đuôi&lt;/td&gt;
      &lt;td&gt;\(Q_{0.95}\) dự báo hậu nghiệm có xu hướng cao hơn thực tế&lt;/td&gt;
      &lt;td&gt;Biến đổi log khắc phục tình trạng thiếu bao phủ nhưng có thể hiệu chỉnh quá mức ở đuôi, do đó vẫn cần kiểm tra PPC vùng đuôi riêng.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Can thiệp 3 không phân cấp (hiệu ứng cố định thô)&lt;/td&gt;
      &lt;td&gt;Khác biệt theo nhóm chất lượng&lt;/td&gt;
      &lt;td&gt;Một số nhóm hiếm có trung bình dự báo tăng vọt bất thường&lt;/td&gt;
      &lt;td&gt;Minh chứng thực tế cho sự cần thiết của &lt;strong&gt;partial pooling&lt;/strong&gt; thay vì ước lượng nhóm tự do hoàn toàn.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Kết quả cho thấy hiệu ứng của từng can thiệp không mang tính đơn điệu kiểu “càng phức tạp càng tốt”. Một can thiệp tốt phải giải quyết đúng triệu chứng mục tiêu mà không tạo ra biến dạng mới ở tầng kiểm tra khác; vì vậy đánh giá hậu kiểm luôn là bước bắt buộc.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-case-study-giá-kim-cương-loglog--partial-pooling-theo-cấp-cắt&quot;&gt;Video ngắn: Case Study Giá Kim cương: Log–Log &amp;amp; Partial Pooling theo Cấp cắt&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch04-06a-diamonds-log-partial-pooling.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 17 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): biến đổi log(Price) theo log(Carat) giúp đường cong mũ thành đường thẳng sắc nét, kết hợp Partial Pooling co cụm nhẹ các nhóm ít mẫu.&lt;/p&gt;

&lt;h2 id=&quot;8-kết-luận-phương-pháp-luận&quot;&gt;8. Kết luận phương pháp luận&lt;/h2&gt;

&lt;p&gt;Tập dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; cho thấy một bài học quan trọng của mô hình hóa Bayes: chỉ số đẹp ở cấp toàn cục có thể che giấu sai lệch nghiêm trọng ở cấp có điều kiện. Thiếu kiểm tra mô hình theo nhiều tầng, ta rất dễ nhầm lẫn giữa “mô hình bắt được tín hiệu” và “mô hình đủ tin cậy để ra quyết định”. Chu trình đúng luôn là: khớp mô hình, kiểm tra đa tầng, giải thích sai lệch theo cơ chế, điều chỉnh có mục tiêu rồi kiểm định lại.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EkAQAi3a4js&quot;&gt;Multiple Regression, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Giải thích ý nghĩa hệ số hồi quy nhiều biến khi kiểm soát các biến còn lại, phù hợp với cấu trúc đa biến của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yDPJnV9vcHs&quot;&gt;What is a posterior predictive check and why is it useful?&lt;/a&gt; — Ben Lambert, English. Trình bày kiểm tra dự báo hậu nghiệm, bổ trợ cho luận điểm rằng khớp được mô hình chưa phải điều kiện đủ.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Oriol Abril-Pla - Model criticism with ArviZ&lt;/td&gt;
          &lt;td&gt;Pydata London 26](https://www.youtube.com/watch?v=HHPAzNan7Uw) — PyData, English. Hướng dẫn quy trình phê bình mô hình bằng ArviZ, liên kết trực tiếp chẩn đoán lấy mẫu và PPC thành một quy trình thống nhất.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Nếu mô hình tái tạo tốt \(\bar y\) nhưng lệch mạnh ở \(Q_{0.95}(y)\), bạn sẽ đánh giá thế nào về khả năng ứng dụng mô hình cho phân khúc cao cấp?&lt;/li&gt;
  &lt;li&gt;Trong bài toán dự đoán giá trị, vì sao sai số ở đuôi phải thường gây hệ quả nghiêm trọng hơn sai số ở vùng trung tâm?&lt;/li&gt;
  &lt;li&gt;Khi đã đưa biến &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt; vào mô hình nhưng PPC theo nhóm vẫn chưa đạt, bạn sẽ ưu tiên rà soát giả định cấu trúc nào tiếp theo?&lt;/li&gt;
  &lt;li&gt;Vì sao tỷ lệ bao phủ ngoài mẫu tính riêng theo từng dải &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; cung cấp nhiều thông tin hơn tỷ lệ bao phủ gộp toàn tập dữ liệu?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), chapters on model checking.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Regression and Other Stories&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), chapters on posterior predictive checks.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Kết thúc Chapter 4. Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter05/&quot;&gt;Chapter 5 - Multiple Predictors và Causal Thinking&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 4.5: Case Study Model Checking & Prediction - Đi Trọn Workflow Trên Một Dataset</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_05_case_study_model_checking_prediction/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_05_case_study_model_checking_prediction</id>
   <content type="html">&lt;p&gt;Lý thuyết kiểm tra mô hình chỉ thực sự sống dậy khi ta đặt nó lên một tập dữ liệu có thật. Tập dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; ghi lại 244 bàn ăn trong một nhà hàng thoạt nhìn cực kỳ hiền lành: hóa đơn càng cao, tiền boa càng cao. Thế nhưng chỉ cần đi trọn vẹn sáu bước của quy trình Bayes, ta sẽ chứng kiến một bài học kinh điển: một đường thẳng Gaussian có thể ước lượng rất chuẩn mức tiền boa trung bình 3 đô la, nhưng lại gán xác suất cho tiền boa âm ở bàn nhỏ và đánh giá quá thấp rủi ro biến động ở bàn lớn.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ thực hành trọn vẹn một quy trình hồi quy Bayes trên tập dữ liệu cụ thể: xây dựng mô hình, đánh giá chất lượng lấy mẫu, kiểm tra mô hình bằng dự báo hậu nghiệm (PPC), phân tích phần dư, báo cáo dự đoán kèm đúng loại bất định và đề xuất điều chỉnh mô hình dựa trên bằng chứng định lượng.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ ngắn.&lt;/strong&gt; Khi dự đoán tiền boa (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt;) từ tổng hóa đơn (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;) tại nhà hàng, một mô hình tuyến tính có thể cho hệ số dốc rất rõ ràng. Tuy nhiên, câu hỏi thực tế là: mô hình đó có tái tạo được đặc trưng của dữ liệu thực tế và đưa ra khoảng dự đoán đáng tin cậy cho các bàn ăn mới hay không?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Nếu phân phối hậu nghiệm cho hệ số dốc dương rõ rệt nhưng PPC thất bại ở vùng hóa đơn lớn, bạn nên rút ra kết luận gì?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-phương-sai-giải-thích-được-thống-kê-đuôi-và-nhiễu-cộng-vs-nhiễu-nhân&quot;&gt;Kiến thức cần nhớ: Phương sai giải thích được, Thống kê đuôi và Nhiễu cộng vs. Nhiễu nhân&lt;/h2&gt;

&lt;p&gt;Để đọc hiểu trọn vẹn nghiên cứu tình huống &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;, cần nắm chắc ba khái niệm cầu nối giữa thống kê mô tả và mô hình hóa Bayes:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tương quan tuyến tính và phần phương sai chưa giải thích (\(1 - R^2\)):&lt;/strong&gt; Hệ số tương quan \(r_{xy} \approx 0.676\) kéo theo \(R^2 \approx 0.46\), nghĩa là hơn một nửa (54%) biến thiên của tiền boa nằm ngoài đường thẳng theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;. Điều này báo trước rằng việc mô hình hóa phần nhiễu \(\sigma\) và kiểm tra cấu trúc phần dư quan trọng không kém việc ước lượng hệ số dốc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hành vi vùng đuôi (Tail Behavior) và thống kê chỉ thị:&lt;/strong&gt; Trung bình mẫu rất “dễ chiều” — ngay cả mô hình sai phân phối vẫn thường tái tạo đúng trung bình. Các thống kê đuôi như phân vị 95% \(Q_{0.95}(y)\) hay tỷ lệ vượt ngưỡng \(\frac{1}{n}\sum \mathbf{1}(y_i &amp;gt; 6)\) mới là phép thử sắc bén để phát hiện sự bất đối xứng và đuôi dày.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhiễu cộng (Additive Noise) so với nhiễu nhân (Multiplicative Noise):&lt;/strong&gt; Trong dữ liệu tài chính và dịch vụ, sai số thường tỷ lệ với quy mô giao dịch (ví dụ tiền boa dao động quanh 15% hóa đơn, lệch \(\pm 5\%\)). Nhiễu cộng \(y = \mu + \varepsilon\) giữ biên độ cố định theo đô la nên dễ sinh giá trị âm ở hóa đơn nhỏ và quá hẹp ở hóa đơn lớn; chuyển sang thang log \(\log y \sim \mathcal{N}(\mu_{\log}, \sigma_{\log}^2)\) chuyển nhiễu nhân thành nhiễu cộng đồng phương sai.
    &lt;h2 id=&quot;1-giới-thiệu-tập-dữ-liệu-tips&quot;&gt;1. Giới thiệu tập dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ta sử dụng tập dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; (từ thư viện &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seaborn&lt;/code&gt;), trong đó mỗi dòng tương ứng với một bàn ăn, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; là tổng hóa đơn và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt; là tiền boa. Mục tiêu chính là mô hình hóa và dự đoán &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt; theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;; mục tiêu quan trọng không kém là kiểm tra xem mô hình tuyến tính Gaussian cơ sở có đủ phù hợp hay không thay vì mặc nhiên tin vào hệ số dốc.&lt;/p&gt;

&lt;p&gt;Tập dữ liệu này đủ gọn để dễ quan sát trực giác, đồng thời đủ thực tế để bộc lộ các vấn đề kinh điển trong kiểm tra mô hình: khả năng phi tuyến nhẹ, phương sai tăng theo quy mô hóa đơn và hành vi vùng đuôi không hoàn toàn phù hợp với phân phối Chuẩn đơn giản.&lt;/p&gt;

&lt;h3 id=&quot;11-trích-đoạn-dữ-liệu&quot;&gt;1.1. Trích đoạn dữ liệu&lt;/h3&gt;

&lt;p&gt;Bảng dưới trình bày 5 dòng đầu của tập dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;total_bill&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;tip&lt;/th&gt;
      &lt;th&gt;sex&lt;/th&gt;
      &lt;th&gt;smoker&lt;/th&gt;
      &lt;th&gt;day&lt;/th&gt;
      &lt;th&gt;time&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;size&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;16.99&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1.01&lt;/td&gt;
      &lt;td&gt;Female&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Sun&lt;/td&gt;
      &lt;td&gt;Dinner&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;10.34&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1.66&lt;/td&gt;
      &lt;td&gt;Male&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Sun&lt;/td&gt;
      &lt;td&gt;Dinner&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;21.01&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.50&lt;/td&gt;
      &lt;td&gt;Male&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Sun&lt;/td&gt;
      &lt;td&gt;Dinner&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;23.68&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.31&lt;/td&gt;
      &lt;td&gt;Male&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Sun&lt;/td&gt;
      &lt;td&gt;Dinner&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;24.59&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.61&lt;/td&gt;
      &lt;td&gt;Female&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Sun&lt;/td&gt;
      &lt;td&gt;Dinner&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;12-tóm-tắt-dữ-liệu-trước-khi-mô-hình-hóa&quot;&gt;1.2. Tóm tắt dữ liệu trước khi mô hình hóa&lt;/h3&gt;

&lt;p&gt;Trên toàn bộ 244 quan sát:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;: trung bình khoảng 19.79, độ lệch chuẩn khoảng 8.90, nhỏ nhất 3.07, lớn nhất 50.81.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt;: trung bình khoảng 3.00, độ lệch chuẩn khoảng 1.38, nhỏ nhất 1.00, lớn nhất 10.00.&lt;/li&gt;
  &lt;li&gt;Tương quan tuyến tính giữa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt; đạt khoảng 0.676 (dương, mức trung bình đến khá).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Một điểm đáng lưu ý cho bước kiểm tra phía sau: chỉ khoảng 2.9% quan sát có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip &amp;gt; 6&lt;/code&gt;, nhưng đây lại là vùng phản ánh hành vi đuôi phải (tail behavior) — nơi mô hình tuyến tính Gaussian thường dễ sai lệch:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Vì sao tỷ lệ 2.9% vẫn quan trọng?&lt;/strong&gt; Các trường hợp ở đuôi phải thường gắn với những giao dịch có giá trị lớn; dù ít gặp, chúng quyết định độ chính xác của dự báo trong các kịch bản rủi ro hoặc doanh thu cao.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vì sao mô hình Gaussian cơ sở dễ lệch ở đuôi?&lt;/strong&gt; Mô hình giả định sai số đối xứng và dùng một độ lệch chuẩn nhiễu \(\sigma\) cố định cho mọi mức hóa đơn. Trong dữ liệu dịch vụ, độ phân tán tiền boa thường tăng theo mức hóa đơn, khiến đuôi phải dày hơn so với dự báo của phân phối Chuẩn đồng phương sai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hệ quả nếu bỏ qua vùng đuôi:&lt;/strong&gt; mô hình có thể khớp tốt giá trị trung bình nhưng đánh giá thấp xác suất xuất hiện tiền boa cao, khiến khoảng dự đoán ở vùng hóa đơn lớn bị hẹp hơn thực tế.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cách kiểm tra trong PPC:&lt;/strong&gt; bên cạnh trung bình và phương sai, cần bổ sung các thống kê kiểm tra vùng đuôi như:&lt;/li&gt;
&lt;/ul&gt;

\[T_1(y)=\frac{1}{n}\sum_{i=1}^{n}\mathbf 1(y_i&amp;gt;6),\quad T_2(y)=\max(y),\quad T_3(y)=Q_{0.95}(y).\]

&lt;p&gt;Nếu giá trị quan sát \(T(y_{obs})\) rơi ra rìa hoặc nằm ngoài phân phối mô phỏng \(T(y_{rep})\), đó là bằng chứng cho thấy mô hình chưa tái hiện tốt hành vi vùng đuôi.&lt;/p&gt;

&lt;h3 id=&quot;13-cơ-sở-định-lượng-cho-các-nhận-định-ban-đầu&quot;&gt;1.3. Cơ sở định lượng cho các nhận định ban đầu&lt;/h3&gt;

&lt;p&gt;Để tránh đánh giá cảm tính, ta gắn mỗi nhận định với công thức thống kê cụ thể. Hệ số tương quan Pearson giữa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt; là:&lt;/p&gt;

\[r_{xy}=\frac{\sum_{i=1}^{n}(x_i-\bar x)(y_i-\bar y)}{\sqrt{\sum_{i=1}^{n}(x_i-\bar x)^2}\sqrt{\sum_{i=1}^{n}(y_i-\bar y)^2}}.\]

&lt;p&gt;Giá trị \(r_{xy}\approx 0.676\) cho thấy hai điều rõ ràng: chiều hướng dương (hóa đơn cao hơn đi kèm tiền boa có xu hướng cao hơn) và cường độ ở mức vừa đến khá. Trong hồi quy tuyến tính một biến, hệ số xác định thỏa mãn:&lt;/p&gt;

\[R^2 \approx r_{xy}^2.\]

&lt;p&gt;Với \(r_{xy}\approx 0.676\), ta có \(R^2\approx 0.46\) — nghĩa là đường thẳng đơn giản mới giải thích khoảng 46% biến thiên của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt;. Tỷ lệ quan sát ở vùng đuôi phải (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip &amp;gt; 6&lt;/code&gt;) được định nghĩa bởi:&lt;/p&gt;

\[\hat p_{\text{tip}&amp;gt;6}=\frac{1}{n}\sum_{i=1}^{n}\mathbf 1(y_i&amp;gt;6)\approx 0.029.\]

&lt;p&gt;Cuối cùng, để phát hiện sớm hiện tượng phương sai thay đổi (heteroskedasticity), ta tính tương quan giữa độ lớn phần dư và biến dự báo:&lt;/p&gt;

\[\operatorname{corr}(|e_i|,x_i), \quad e_i=y_i-\hat y_i.\]

&lt;p&gt;Nếu chỉ số này dương đáng kể, biên độ sai số tăng theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; và giả định nhiễu đồng nhất cần được xem xét lại.&lt;/p&gt;

&lt;h2 id=&quot;2-bước-1--xây-dựng-và-khớp-mô-hình-cơ-sở&quot;&gt;2. Bước 1 – Xây dựng và khớp mô hình cơ sở&lt;/h2&gt;

&lt;p&gt;Mô hình cơ sở (baseline) có dạng:&lt;/p&gt;

\[\text{tip}_i \sim \mathcal{N}(\mu_i, \sigma), \quad \mu_i = \alpha + \beta\,x_i,\]

&lt;p&gt;trong đó \(x_i\) là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; đã chuẩn hóa. Cơ chế sinh dữ liệu ở đây giả định mỗi bàn ăn có mức tiền boa kỳ vọng tuyến tính theo hóa đơn, dao động quanh đường trung bình với một độ nhiễu chung \(\sigma\), cùng phân phối tiên nghiệm thông tin yếu nhằm tránh quá khớp ở vùng hóa đơn rất lớn. Kết quả ước lượng sẽ cho hệ số dốc dương rõ rệt, nhưng ta chỉ coi đây là điểm xuất phát để tiến hành kiểm định.&lt;/p&gt;

&lt;h2 id=&quot;3-bước-2--kiểm-tra-chẩn-đoán-bộ-lấy-mẫu&quot;&gt;3. Bước 2 – Kiểm tra chẩn đoán bộ lấy mẫu&lt;/h2&gt;

&lt;p&gt;Trước khi diễn giải bất kỳ tham số nào, cần xác nhận quá trình lấy mẫu MCMC đạt yêu cầu: trace plot trộn đều giữa các chuỗi, \(\hat{R}\) tiệm cận 1.00 cho các tham số chính, ESS đủ lớn để ước lượng ổn định cả vùng đuôi và không có cảnh báo divergence có hệ thống. Mọi kết quả PPC phía sau chỉ có ý nghĩa khi các mẫu hậu nghiệm đã thực sự đáng tin cậy.&lt;/p&gt;

&lt;h2 id=&quot;4-bước-3--kiểm-tra-dự-báo-hậu-nghiệm-ppc&quot;&gt;4. Bước 3 – Kiểm tra dự báo hậu nghiệm (PPC)&lt;/h2&gt;

&lt;p&gt;Dựa trên phân phối dự báo hậu nghiệm từ Bài 4.4:&lt;/p&gt;

\[p(\tilde y \mid y)=\int p(\tilde y \mid \theta)\,p(\theta\mid y)\,d\theta,\]

&lt;p&gt;ta kiểm tra xem dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt; mô phỏng từ mô hình cơ sở có khớp với dữ liệu thực tế ở cả vùng trung tâm lẫn vùng đuôi hay không.&lt;/p&gt;

&lt;h3 id=&quot;41-đối-chiếu-phân-phối-tổng-thể&quot;&gt;4.1. Đối chiếu phân phối tổng thể&lt;/h3&gt;

&lt;p&gt;So sánh dữ liệu quan sát &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; với dữ liệu mô phỏng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y_rep&lt;/code&gt; để kiểm tra độ trùng khớp của đường mật độ, khả năng tái tạo đuôi phải (tiền boa cao) và miền giá trị cực tiểu/cực đại.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_observed_vs_predicted.png&quot; alt=&quot;Hình 2 - So sánh quan sát và posterior predictive trên toàn phân phối&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;42-đối-chiếu-trung-bình-phương-sai-và-thống-kê-đuôi&quot;&gt;4.2. Đối chiếu trung bình, phương sai và thống kê đuôi&lt;/h3&gt;

&lt;p&gt;Tính các thống kê như trung bình, phương sai và tỷ lệ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip &amp;gt; 6&lt;/code&gt; trên cả dữ liệu thực và các tập dữ liệu mô phỏng. Nếu giá trị thực tế nằm quá xa so với phân phối mô phỏng, mô hình đang thiếu một phần cấu trúc quan trọng.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_test_stat_mean.png&quot; alt=&quot;Hình 3 - Kiểm tra mean bằng posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_variance_check.png&quot; alt=&quot;Hình 4 - Kiểm tra variance bằng posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Với tập dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;, mô hình cơ sở thường tái tạo trung bình tổng thể khá tốt nhưng dễ lệch về phương sai ở vùng hóa đơn lớn — dấu hiệu sớm của hiện tượng phương sai thay đổi.&lt;/p&gt;

&lt;h3 id=&quot;43-đối-chiếu-mối-quan-hệ-giữa-total_bill-và-tip&quot;&gt;4.3. Đối chiếu mối quan hệ giữa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;Vẽ nhiều tập dự báo hậu nghiệm chồng lên biểu đồ phân tán thực tế giúp quan sát xem mô hình có dự đoán lệch ở vùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; lớn hay không và độ rộng phân tán có mở rộng theo hóa đơn hay không. Đây thường là nơi phát hiện sớm nhất dấu hiệu phi tuyến hoặc phương sai thay đổi.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_distribution_at_x5.png&quot; alt=&quot;Hình 5 - So sánh quan hệ predictor-response giữa dữ liệu thật và mẫu posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;5-bước-4--phân-tích-phần-dư-để-tìm-sai-lệch-có-hệ-thống&quot;&gt;5. Bước 4 – Phân tích phần dư để tìm sai lệch có hệ thống&lt;/h2&gt;

&lt;p&gt;Xét phần dư hậu nghiệm:&lt;/p&gt;

\[r_i = y_i - \mathbb{E}[\tilde y_i \mid y].\]

&lt;p&gt;Ta kiểm tra ba biểu đồ cơ bản: phần dư theo giá trị ước lượng, phần dư theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; và biểu đồ Q–Q. Các tín hiệu cần chú ý gồm: mẫu hình cong gợi ý quan hệ phi tuyến, dạng hình quạt gợi ý phương sai thay đổi, và đuôi lệch mạnh trên biểu đồ Q–Q gợi ý giả định phân phối Chuẩn quá hẹp. Trên tập &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;, biên độ phần dư thường có xu hướng mở rộng khi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; tăng, cho thấy giả định đồng phương sai chưa thật sự phù hợp.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_residual_distribution.png&quot; alt=&quot;Hình 6 - Residual distribution: quan sát so với posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_residuals.png&quot; alt=&quot;Hình 7 - Residuals vs fitted để nhận diện pattern hệ thống&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-case-study-tiền-tip-vì-sao-nhiễu-cộng-sụp-đổ-ở-hai-đầu-hóa-đơn&quot;&gt;Video ngắn: Case Study Tiền Tip: Vì sao Nhiễu Cộng sụp đổ ở Hai đầu Hóa đơn?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch04-05a-tips-additive-vs-log.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 17 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): mô hình Normal cộng dự báo tiền tip âm ở hóa đơn $5, trong khi chuyển sang log(tip) giữ tiền tip luôn dương và mở rộng dải dự báo theo tỷ lệ hóa đơn.&lt;/p&gt;

&lt;h2 id=&quot;6-bước-5--dự-đoán-cho-trường-hợp-cụ-thể&quot;&gt;6. Bước 5 – Dự đoán cho trường hợp cụ thể&lt;/h2&gt;

&lt;p&gt;Giả sử cần dự đoán tiền boa cho một bàn ăn mới có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill = 40&lt;/code&gt;. Cần tách bạch và báo cáo rõ hai loại khoảng bất định:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng hậu nghiệm cho tiền boa trung bình&lt;/strong&gt; tại mức hóa đơn 40 (ví dụ: khoảng 5.8 đến 6.5).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng dự đoán (prediction interval) cho một bàn ăn cụ thể&lt;/strong&gt; (ví dụ: khoảng 3.8 đến 8.7).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Khoảng thứ hai rộng hơn đáng kể vì gộp thêm độ nhiễu cá thể của bàn ăn mới. Khi ứng dụng vào thực tế, nếu mục tiêu là lập kế hoạch doanh thu trung bình thì dùng khoảng của trung bình; nếu mục tiêu là đánh giá biến động hoặc rủi ro của từng giao dịch cụ thể thì phải dùng khoảng dự đoán.&lt;/p&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-sự-sụp-đổ-của-mô-hình-nhiễu-cộng-ở-hai-đầu-hóa-đơn&quot;&gt;Giải thích: Tính tay sự sụp đổ của mô hình nhiễu cộng ở hai đầu hóa đơn&lt;/h3&gt;

&lt;p&gt;Hãy đặt hai mô hình — tuyến tính Gaussian nhiễu cộng và mô hình tỷ lệ log-normal — lên cùng hai bàn ăn thực tế để thấy sự khác biệt bằng con số cụ thể:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình cơ sở nhiễu cộng:&lt;/strong&gt; Giả sử hậu nghiệm tập trung quanh \(\hat\mu = 0.92 + 0.105\,x\) với độ lệch chuẩn nhiễu cố định \(\sigma = 1.02\) USD.
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Tại bàn nhỏ (\(x = 10\) USD):&lt;/strong&gt; Trung bình dự đoán \(\hat\mu = 0.92 + 1.05 = 1.97\) USD. Khoảng dự đoán 95% xấp xỉ \(1.97 \pm 1.96(1.02) = [-0.03,\ 3.97]\) USD. Mô hình cho phép &lt;strong&gt;tiền boa âm&lt;/strong&gt; — điều bất khả thi về mặt vật lý!&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tại bàn lớn (\(x = 40\) USD):&lt;/strong&gt; Trung bình dự đoán \(\hat\mu = 0.92 + 4.20 = 5.12\) USD. Khoảng dự đoán 95% là \(5.12 \pm 2.00 = [3.12,\ 7.12]\) USD (biên độ chỉ \(\pm 2.00\) USD). Trong khi đó, khách ăn 40 USD boa trong khoảng 10%–25% sẽ trải rộng từ \(4.00\) đến \(10.00\) USD — mô hình cơ sở đã cắt mất phần đuôi trên.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình nhiễu nhân trên thang log:&lt;/strong&gt; Xét \(\log(\text{tip}) \sim \mathcal{N}(\log(0.15\,x),\ 0.25^2)\) (tương ứng tiền boa trung vị 15% hóa đơn, độ phân tán tương đối khoảng 25%).
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Tại bàn nhỏ (\(x = 10\) USD):&lt;/strong&gt; Trung vị \(1.50\) USD; khoảng 95% là \(1.50 \times e^{\pm 1.96(0.25)} = 1.50 \times [0.613,\ 1.632] = [0.92,\ 2.45]\) USD — hoàn toàn dương và chặt chẽ.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tại bàn lớn (\(x = 40\) USD):&lt;/strong&gt; Trung vị \(6.00\) USD; khoảng 95% là \(6.00 \times [0.613,\ 1.632] = [3.68,\ 9.79]\) USD — tự động giãn rộng tương xứng với quy mô hóa đơn.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chỉ cần so sánh hai phép nhân trên, bạn thấy ngay vì sao PPC ở vùng đuôi lại thúc đẩy ta chuyển sang mô hình log hoặc heteroskedastic.&lt;/p&gt;

&lt;h2 id=&quot;7-bước-6--điều-chỉnh-mô-hình-dựa-trên-bằng-chứng-chẩn-đoán&quot;&gt;7. Bước 6 – Điều chỉnh mô hình dựa trên bằng chứng chẩn đoán&lt;/h2&gt;

&lt;p&gt;Khi PPC và phần dư chỉ ra rằng mô hình tuyến tính cơ sở dự đoán thiếu ở đuôi phải và có phương sai tăng theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;, ta có ba hướng điều chỉnh có cơ sở:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Biến đổi log cho biến phản hồi, chẳng hạn mô hình hóa \(\log(\text{tip})\).&lt;/li&gt;
  &lt;li&gt;Mô hình hóa độ nhiễu \(\sigma\) thay đổi theo biến dự báo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Bổ sung thành phần phi tuyến nhẹ (như spline hoặc đa thức bậc thấp).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nguyên tắc cốt lõi là mọi chỉnh sửa đều phải xuất phát trực tiếp từ dấu hiệu sai lệch mà PPC và phân tích phần dư chỉ ra, thay vì thử nghiệm cảm tính.&lt;/p&gt;

&lt;h3 id=&quot;71-so-sánh-ba-phương-án-mô-hình&quot;&gt;7.1. So sánh ba phương án mô hình&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Phương án&lt;/th&gt;
      &lt;th&gt;Vấn đề xử lý chính&lt;/th&gt;
      &lt;th&gt;Ưu điểm&lt;/th&gt;
      &lt;th&gt;Hạn chế cần lưu ý&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Tuyến tính Gaussian cơ sở&lt;/td&gt;
      &lt;td&gt;Làm mốc tham chiếu ban đầu&lt;/td&gt;
      &lt;td&gt;Đơn giản, dễ diễn giải&lt;/td&gt;
      &lt;td&gt;Dễ lệch ở vùng đuôi và khi phương sai thay đổi&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Log-tip Gaussian&lt;/td&gt;
      &lt;td&gt;Thu gọn đuôi phải, ổn định phương sai&lt;/td&gt;
      &lt;td&gt;Thường cải thiện PPC vùng đuôi&lt;/td&gt;
      &lt;td&gt;Cần cẩn thận khi quy đổi ngược về đơn vị gốc&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Heteroskedastic Gaussian&lt;/td&gt;
      &lt;td&gt;Cho phép \(\sigma\) thay đổi theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Khoảng dự đoán trung thực hơn ở hóa đơn lớn&lt;/td&gt;
      &lt;td&gt;Tăng số tham số và chi phí kiểm tra mô hình&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Cả ba phương án cần được đối chiếu trên cùng một bộ tiêu chí PPC và phân tích phần dư trước khi chọn mô hình phù hợp nhất.&lt;/p&gt;

&lt;h2 id=&quot;8-tổng-kết-quy-trình-thực-hành&quot;&gt;8. Tổng kết quy trình thực hành&lt;/h2&gt;

&lt;p&gt;Trên tập dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;, ta đã đi trọn sáu bước của quy trình hồi quy Bayes: (1) xây dựng và khớp mô hình cơ sở, (2) kiểm tra chẩn đoán bộ lấy mẫu, (3) chạy PPC nhiều góc độ, (4) phân tích phần dư, (5) báo cáo dự đoán đúng loại bất định và (6) đề xuất sửa đổi mô hình dựa trên bằng chứng.&lt;/p&gt;

&lt;h3 id=&quot;81-danh-mục-kiểm-tra-dùng-lại-cho-các-bài-toán-khác&quot;&gt;8.1. Danh mục kiểm tra dùng lại cho các bài toán khác&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Khảo sát cấu trúc dữ liệu và vùng đuôi trước khi mô hình hóa.&lt;/li&gt;
  &lt;li&gt;Xác nhận các chỉ số hội tụ MCMC đạt ngưỡng tối thiểu.&lt;/li&gt;
  &lt;li&gt;Thực hiện PPC ở ba tầng: phân phối tổng thể, thống kê mục tiêu và quan hệ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x -&amp;gt; y&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Kiểm tra mẫu hình có hệ thống trên phần dư thay vì chỉ nhìn trung bình.&lt;/li&gt;
  &lt;li&gt;Báo cáo rõ ràng khoảng trung bình và khoảng dự đoán cá thể.&lt;/li&gt;
  &lt;li&gt;Chỉ điều chỉnh mô hình khi có tín hiệu sai lệch cụ thể từ bước kiểm tra.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;9-những-sai-lầm-thường-gặp&quot;&gt;9. Những sai lầm thường gặp&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Dừng lại khi thấy hệ số dốc dương:&lt;/strong&gt; hệ số dốc có ý nghĩa thống kê không đảm bảo mô hình tái tạo tốt dữ liệu trên toàn miền giá trị.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhầm lẫn hai loại khoảng bất định:&lt;/strong&gt; dùng khoảng của giá trị trung bình để nói về một bàn ăn cụ thể sẽ tạo ra mức độ chắc chắn giả tạo.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sửa mô hình theo cảm tính:&lt;/strong&gt; áp dụng các phép biến đổi tùy hứng mà không gắn với bằng chứng từ PPC hay phần dư sẽ làm mất tính kỷ luật khoa học.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không nêu rõ phạm vi tin cậy:&lt;/strong&gt; một mô hình có thể hoạt động tốt ở vùng hóa đơn trung bình nhưng kém ổn định ở vùng hóa đơn rất lớn; cần nêu rõ giới hạn này khi báo cáo.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;10-điểm-cốt-lõi-cần-giữ-lại&quot;&gt;10. Điểm cốt lõi cần giữ lại&lt;/h2&gt;

&lt;p&gt;Một quy trình làm việc Bayes hoàn chỉnh luôn vận hành theo vòng lặp: &lt;strong&gt;mô hình hóa \(\to\) kiểm tra \(\to\) dự đoán \(\to\) điều chỉnh&lt;/strong&gt;. Ngay cả với một tập dữ liệu gọn như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;, việc đi đủ vòng lặp này là điều kiện cần để đưa ra kết luận có trách nhiệm.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yDPJnV9vcHs&quot;&gt;What is a posterior predictive check and why is it useful?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Nêu rõ câu hỏi trung tâm của kiểm tra dự báo hậu nghiệm trước khi áp dụng lên dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=fpS0NjqNHn8&quot;&gt;L4: Interpretable Linear Regressions (State of Bayes Lecture Series)&lt;/a&gt; — PyMC Labs, English. Minh họa cách xây dựng và diễn giải hồi quy Bayes, hỗ trợ phần thiết lập mô hình của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=iMdtTCX2Q70&quot;&gt;Simple Linear Regression:  Checking Assumptions with Residual Plots&lt;/a&gt; — jbstatistics, English. Hướng dẫn đọc biểu đồ phần dư để kiểm tra giả định mô hình, bổ trợ cho mục 5.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Với tập dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;, ngoài trung bình và phương sai, bạn sẽ chọn thêm thống kê nào cho PPC và vì sao?&lt;/li&gt;
  &lt;li&gt;Nếu biểu đồ phần dư theo giá trị ước lượng tạo hình chữ U, bạn sẽ ưu tiên điều chỉnh mô hình theo hướng nào trước?&lt;/li&gt;
  &lt;li&gt;Vì sao khoảng dự đoán cho một bàn ăn mới luôn rộng hơn khoảng hậu nghiệm của mức tiền boa trung bình?&lt;/li&gt;
  &lt;li&gt;Nếu mô hình dự đoán tốt ở vùng hóa đơn trung bình nhưng lệch ở vùng đuôi phải, điều đó ảnh hưởng ra sao đến quyết định kinh doanh?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), chapters on model checking.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Regression and Other Stories&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), chapters on posterior predictive checks.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter04/04_06_case_study_complex_dataset/&quot;&gt;Bài 4.6 - Case Study Nâng Cao trên Dataset Phức Tạp&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 4.4: Model Checking và Prediction - Đảm bảo Model Tốt</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_04_model_checking_prediction/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_04_model_checking_prediction</id>
   <content type="html">&lt;p&gt;Một cỗ máy MCMC có thể chạy trơn tru, cho \(\hat{R} = 1.00\), số mẫu hiệu dụng lên tới hàng nghìn và khoảng tin cậy 95% của hệ số dốc hẹp như sợi chỉ — nhưng mô hình đó vẫn có thể &lt;strong&gt;sai hoàn toàn&lt;/strong&gt;. Lý do rất đơn giản: định lý Bayes chỉ trả lời chính xác &lt;em&gt;trong phạm vi thế giới giả định của mô hình bạn viết ra&lt;/em&gt;. Muốn biết thế giới giả định ấy có giống thế giới thực hay không, ta phải cho mô hình tự sinh lại dữ liệu và đặt dữ liệu giả lập ấy cạnh dữ liệu thật — bước phê bình mô hình mà George Box gọi là linh hồn của vòng lặp khoa học.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu rằng việc khớp mô hình (fitting) mới chỉ là nửa đầu của quy trình hồi quy Bayes. Nửa còn lại là kiểm tra xem mô hình có mô tả dữ liệu một cách hợp lý hay không, đồng thời sử dụng phân phối hậu nghiệm để dự đoán dữ liệu mới kèm đầy đủ mức độ bất định. Trọng tâm của bài là kỹ thuật &lt;strong&gt;kiểm tra dự báo hậu nghiệm&lt;/strong&gt; (posterior predictive check — PPC) và phân tích phần dư.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ ngắn.&lt;/strong&gt; Một đường hồi quy có thể trông khớp mắt trên biểu đồ phân tán, nhưng nếu dữ liệu giả lập từ mô hình không giống dữ liệu thực tế thì mô hình vẫn đang có vấn đề. Kiểm tra mô hình là cách chủ động chất vấn giả định của chính mình thay vì mặc nhiên tin vào kết quả sau khi chạy xong thuật toán.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Vì sao một phân phối hậu nghiệm “trông gọn đẹp” vẫn chưa đủ cơ sở để kết luận mô hình là tốt?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-tích-phân-dự-báo-hậu-nghiệm-thống-kê-kiểm-tra-và-giải-phẫu-phần-dư&quot;&gt;Kiến thức cần nhớ: Tích phân dự báo hậu nghiệm, Thống kê kiểm tra và Giải phẫu phần dư&lt;/h2&gt;

&lt;p&gt;Bước kiểm tra mô hình (model checking) và dự đoán trong thống kê Bayes dựa trên ba khái niệm then chốt:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối dự báo hậu nghiệm (Posterior Predictive Distribution):&lt;/strong&gt; Tích phân \(p(\tilde y \mid y) = \int p(\tilde y \mid \theta)p(\theta \mid y)\,d\theta\) gộp đồng thời bất định tham số \(p(\theta \mid y)\) và nhiễu sinh dữ liệu \(p(\tilde y \mid \theta)\). Trong thực hành, nó đóng hai vai trò: dự đoán cho quan sát mới ngoài mẫu và tạo tập dữ liệu tái lập \(y_{\text{rep}}\) để kiểm tra mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thống kê kiểm tra \(T(y)\) và giá trị \(p\) dự báo hậu nghiệm (Bayesian \(p\)-value):&lt;/strong&gt; Thay vì chỉ nhìn mắt thường, ta chọn một hàm thống kê \(T(y)\) phản ánh khía cạnh quan tâm (trung bình, phương sai, cực đại, độ lệch) rồi đo tỷ lệ mẫu mô phỏng vượt quá giá trị quan sát: \(p_B = P(T(y_{\text{rep}}) \ge T(y_{\text{obs}}) \mid y)\). Nếu \(p_B\) quá gần 0 hoặc 1 (chẳng hạn \(&amp;lt;0.05\) hoặc \(&amp;gt;0.95\)), mô hình đang bỏ sót đặc trưng đó của dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giải phẫu phần dư (Residual Diagnostics):&lt;/strong&gt; Phần dư \(e_i = y_i - \mathbb{E}[\tilde y_i \mid y]\) là “dấu vân tay” của những gì mô hình chưa giải thích được. Hình cong tố cáo quan hệ phi tuyến; hình quạt tố cáo phương sai thay đổi (heteroskedasticity); biểu đồ Q–Q cong chữ S ở hai đầu tố cáo sai số đuôi dày (heavy tails).
    &lt;h2 id=&quot;1-khớp-dữ-liệu-tốt-chưa-đồng-nghĩa-với-mô-hình-tốt&quot;&gt;1. Khớp dữ liệu tốt chưa đồng nghĩa với mô hình tốt&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nhiều người học hồi quy thường dừng lại ngay sau khi ước lượng hệ số dốc và đọc khoảng tin cậy. Tuy nhiên, một quy trình Bayes đầy đủ đòi hỏi ta phải đặt thêm ba câu hỏi quan trọng: mô hình có tái tạo được đặc trưng của dữ liệu quan sát không, phần dư (residual) có còn chứa quy luật có hệ thống nào không, và dự đoán cho dữ liệu mới có hợp lý trong thực tế hay không.&lt;/p&gt;

&lt;p&gt;Nhà thống kê George Box có câu nói nổi tiếng:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“All models are wrong, but some are useful.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Mục tiêu của việc kiểm tra không phải là tìm ra một mô hình “hoàn hảo tuyệt đối”, mà là xác nhận mô hình đủ hữu ích, phản ánh trung thực mức độ bất định và không bỏ sót những cấu trúc quan trọng của dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;2-phân-phối-dự-báo-hậu-nghiệm-posterior-predictive-distribution-là-gì&quot;&gt;2. Phân phối dự báo hậu nghiệm (Posterior Predictive Distribution) là gì?&lt;/h2&gt;

&lt;p&gt;Khi đã có phân phối hậu nghiệm \(p(\theta \mid y)\) của các tham số, ta có thể mô phỏng dữ liệu mới \(\tilde y\) từ mô hình thông qua phân phối dự báo hậu nghiệm:&lt;/p&gt;

\[p(\tilde y \mid y) = \int p(\tilde y \mid \theta)\,p(\theta \mid y)\,d\theta.\]

&lt;p&gt;Công thức này là cầu nối trực tiếp giữa suy luận tham số và dự đoán dữ liệu tương lai (hoặc dữ liệu tái tạo từ chính mô hình):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\tilde y\) là dữ liệu mới hoặc dữ liệu mô phỏng cần dự đoán.&lt;/li&gt;
  &lt;li&gt;\(\theta\) là vector tham số của mô hình.&lt;/li&gt;
  &lt;li&gt;\(p(\theta \mid y)\) thể hiện mức độ hợp lý của từng giá trị tham số sau khi đã quan sát dữ liệu \(y\).&lt;/li&gt;
  &lt;li&gt;\(p(\tilde y \mid \theta)\) là cơ chế sinh dữ liệu mới khi cố định tham số ở \(\theta\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nói cách khác, tích phân trên là một phép trung bình có trọng số trên mọi khả năng của tham số, trong đó trọng số chính là phân phối hậu nghiệm \(p(\theta \mid y)\): &lt;strong&gt;những bộ tham số phù hợp với dữ liệu hơn sẽ đóng góp trọng số lớn hơn vào dự đoán cuối cùng&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Trong thực hành MCMC, tích phân này được xấp xỉ trực tiếp bằng trung bình trên các mẫu hậu nghiệm:&lt;/p&gt;

\[p(\tilde y \mid y) \approx \frac{1}{S}\sum_{s=1}^{S} p(\tilde y \mid \theta^{(s)}), \quad \theta^{(s)} \sim p(\theta \mid y).\]

&lt;p&gt;Ta chỉ cần rút nhiều mẫu \(\theta^{(s)}\) từ phân phối hậu nghiệm, ứng với mỗi mẫu sinh ra một tập dữ liệu mới \(\tilde y^{(s)}\), rồi tổng hợp lại để thu được phân phối dự báo hậu nghiệm.&lt;/p&gt;

&lt;h2 id=&quot;3-kiểm-tra-dự-báo-hậu-nghiệm-posterior-predictive-check--ppc&quot;&gt;3. Kiểm tra dự báo hậu nghiệm (Posterior Predictive Check — PPC)&lt;/h2&gt;

&lt;p&gt;PPC đặt ra một câu hỏi thực tế:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Nếu mô hình của ta mô tả đúng quá trình sinh dữ liệu, liệu dữ liệu giả lập từ mô hình có mang những đặc trưng giống dữ liệu quan sát hay không?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Quy trình gồm ba bước: rút nhiều bộ tham số từ phân phối hậu nghiệm, sinh dữ liệu giả lập từ từng bộ tham số đó và đối chiếu dữ liệu giả lập với dữ liệu thực tế. Nếu dữ liệu giả lập tái hiện được hình dạng phân phối, độ phân tán và các quy luật chính của dữ liệu quan sát, ta có cơ sở vững chắc hơn để tin tưởng mô hình.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_summary.png&quot; alt=&quot;Tóm tắt workflow của posterior predictive check&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;31-ví-dụ-minh-họa-hệ-số-dốc-rõ-rệt-nhưng-mô-hình-vẫn-sai-cấu-trúc&quot;&gt;3.1. Ví dụ minh họa: hệ số dốc rõ rệt nhưng mô hình vẫn sai cấu trúc&lt;/h3&gt;

&lt;p&gt;Giả sử ta mô hình hóa mối quan hệ giữa số giờ học và điểm thi bằng một đường thẳng. Phân phối hậu nghiệm của hệ số dốc có thể rất rõ ràng: dương, khoảng tin cậy hẹp và xác suất \(\beta &amp;gt; 0\) gần bằng 1.&lt;/p&gt;

&lt;p&gt;Tuy nhiên, giả sử trên thực tế mối quan hệ đó có tính bão hòa: học thêm giúp điểm tăng nhanh ở giai đoạn đầu nhưng tăng chậm dần khi số giờ học đã cao (đường cong lõm xuống). Khi đó, mô hình đường thẳng sẽ bộc lộ ba dấu hiệu sai lệch:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;PPC sinh ra nhiều điểm dự đoán cao bất hợp lý ở vùng số giờ học lớn.&lt;/li&gt;
  &lt;li&gt;Phần dư ở vùng giữa có xu hướng dương, còn phần dư ở hai đầu (học rất ít hoặc rất nhiều) có xu hướng âm, tạo thành mẫu hình cong rõ rệt.&lt;/li&gt;
  &lt;li&gt;Đường dự đoán trung bình có vẻ khớp tổng thể nhưng sai lệch có hệ thống tại những vùng giá trị \(x\) quan trọng.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ví dụ này cho thấy phân phối hậu nghiệm của tham số có thể rất “chắc chắn” chỉ vì mô hình đang khớp chặt vào một giả định cấu trúc sai. PPC và phân tích phần dư giúp phát hiện chính những sai lệch dạng này.&lt;/p&gt;

&lt;h2 id=&quot;4-cần-kiểm-tra-những-khía-cạnh-nào-trong-ppc&quot;&gt;4. Cần kiểm tra những khía cạnh nào trong PPC?&lt;/h2&gt;

&lt;p&gt;Không có một phép kiểm tra đơn lẻ nào đủ cho mọi bài toán; ta nên đánh giá mô hình từ nhiều góc độ:&lt;/p&gt;

&lt;h3 id=&quot;41-phân-phối-tổng-thể&quot;&gt;4.1. Phân phối tổng thể&lt;/h3&gt;

&lt;p&gt;So sánh biểu đồ tần suất hoặc đường mật độ của dữ liệu giả lập với dữ liệu thực tế để xem hình dạng tổng thể có tương đồng không.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_distribution_at_x5.png&quot; alt=&quot;So sánh phân phối posterior predictive tại một giá trị x đại diện&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;42-trung-bình-độ-phân-tán-và-vùng-đuôi&quot;&gt;4.2. Trung bình, độ phân tán và vùng đuôi&lt;/h3&gt;

&lt;p&gt;Kiểm tra xem mô hình có tái hiện được giá trị trung bình, phương sai, giá trị cực tiểu/cực đại và hành vi vùng đuôi (tail behavior) của dữ liệu quan sát hay không.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_test_stat_mean.png&quot; alt=&quot;Kiểm tra mean của dữ liệu quan sát trong posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_variance_check.png&quot; alt=&quot;Kiểm tra variance của dữ liệu quan sát trong posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;43-mối-quan-hệ-giữa-biến-dự-báo-và-biến-phản-hồi&quot;&gt;4.3. Mối quan hệ giữa biến dự báo và biến phản hồi&lt;/h3&gt;

&lt;p&gt;Trong hồi quy, điều cốt yếu là kiểm tra xem mô hình có tái hiện đúng xu hướng và độ rộng phân tán giữa biến dự báo \(x\) và biến phản hồi \(y\) trên toàn miền dữ liệu hay không.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_observed_vs_predicted.png&quot; alt=&quot;So sánh dữ liệu quan sát với các mẫu posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;44-thống-kê-đặc-thù-theo-bài-toán&quot;&gt;4.4. Thống kê đặc thù theo bài toán&lt;/h3&gt;

&lt;p&gt;Tùy lĩnh vực, bạn nên bổ sung các đại lượng kiểm tra riêng như tỷ lệ điểm ngoại lai (outlier), độ lệch, độ bất đối xứng hoặc tỷ lệ quan sát vượt một ngưỡng quan trọng.&lt;/p&gt;

&lt;h2 id=&quot;5-phân-tích-phần-dư-residual-analysis&quot;&gt;5. Phân tích phần dư (Residual Analysis)&lt;/h2&gt;

&lt;p&gt;Ngay cả trong hồi quy Bayes, phần dư vẫn là công cụ chẩn đoán sắc bén. Ta thường kiểm tra biểu đồ phần dư theo giá trị ước lượng (residual vs. fitted), phần dư theo biến dự báo, phân phối phần dư và biểu đồ Q–Q để phát hiện phương sai thay đổi (heteroskedasticity), quan hệ phi tuyến (nonlinearity) hoặc sai số có đuôi dày.&lt;/p&gt;

&lt;p&gt;Bốn tình huống điển hình dưới đây giúp bạn nhận diện nhanh các dạng sai lệch: mô hình phù hợp, mô hình bỏ sót quan hệ phi tuyến, mô hình có phương sai tăng theo \(x\) và mô hình có phần dư đuôi dày.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_residual_distribution.png&quot; alt=&quot;Residual distribution: quan sát vs posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ở biểu đồ phân tán dữ liệu gốc, bốn kịch bản này có dạng như sau:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_good_model_scatter.png&quot; alt=&quot;Scatter plot của mô hình tốt&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonlinearity_scatter.png&quot; alt=&quot;Scatter plot khi quan hệ thật là phi tuyến&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_scatter.png&quot; alt=&quot;Scatter plot khi phương sai tăng theo x&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonnormal_scatter.png&quot; alt=&quot;Scatter plot khi residual có đuôi dày&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Trên biểu đồ phần dư theo giá trị ước lượng, mô hình phù hợp sẽ cho phần dư phân bố ngẫu nhiên quanh mức 0, không tạo thành hình cong hay hình quạt:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_good_model_residuals.png&quot; alt=&quot;Residuals vs fitted của mô hình tốt&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonlinearity_residuals.png&quot; alt=&quot;Residuals vs fitted cho dấu hiệu phi tuyến&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_residuals.png&quot; alt=&quot;Residuals vs fitted cho dấu hiệu heteroskedasticity&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonnormal_residuals.png&quot; alt=&quot;Residuals vs fitted với residual nặng đuôi&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Biểu đồ Q–Q cho phép đối chiếu phân phối phần dư với giả định phân phối Chuẩn:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_good_model_qq.png&quot; alt=&quot;Q-Q plot của residual trong mô hình tốt&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonlinearity_qq.png&quot; alt=&quot;Q-Q plot khi mô hình bỏ sót phi tuyến&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_qq.png&quot; alt=&quot;Q-Q plot khi có heteroskedasticity&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonnormal_qq.png&quot; alt=&quot;Q-Q plot khi residual có đuôi dày&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Khi phần dư xuất hiện mẫu hình có hệ thống, mô hình nhiều khả năng đang bỏ sót yếu tố phi tuyến, hiệu ứng tương tác (interaction), phương sai thay đổi hoặc một biến giải thích quan trọng.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-chẩn-đoán-phần-dư--ppc-phát-hiện-phi-tuyến-chữ-u-và-hình-phễu&quot;&gt;Video ngắn: Chẩn đoán Phần dư &amp;amp; PPC: Phát hiện Phi tuyến (Chữ U) và Hình Phễu&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch04-04a-residual-ppc-diagnostics.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 18 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): dù đường thẳng khớp R² = 0.85, đồ thị phần dư vẫn vạch trần rõ xu hướng cong chữ U (thiếu bậc x²) và hình phễu loe rộng (nhiễu thay đổi theo X).&lt;/p&gt;

&lt;h2 id=&quot;6-dự-đoán-bayes-khác-gì-dự-đoán-điểm&quot;&gt;6. Dự đoán Bayes khác gì dự đoán điểm?&lt;/h2&gt;

&lt;p&gt;Thay vì chỉ trả về một giá trị trung bình duy nhất như hồi quy cổ điển, dự đoán Bayes giữ lại đầy đủ cả bất định của tham số lẫn độ nhiễu của quan sát mới. Nhờ đó, ta không chỉ nêu con số dự đoán (chẳng hạn 72) mà còn chỉ rõ khoảng giá trị hợp lý và mức độ tin cậy đi kèm — thông tin thiết thực hơn nhiều cho việc ra quyết định.&lt;/p&gt;

&lt;h2 id=&quot;7-khoảng-dự-đoán-và-hai-nguồn-bất-định&quot;&gt;7. Khoảng dự đoán và hai nguồn bất định&lt;/h2&gt;

&lt;p&gt;Một dự đoán Bayes luôn bao gồm hai tầng bất định:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bất định tham số:&lt;/strong&gt; ta chưa biết giá trị chính xác của \(\alpha, \beta, \sigma\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bất định của quan sát mới:&lt;/strong&gt; ngay cả khi biết chính xác tham số, từng quan sát thực tế vẫn dao động quanh đường trung bình với độ lệch chuẩn \(\sigma\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Vì vậy, &lt;strong&gt;khoảng dự đoán&lt;/strong&gt; (prediction interval) cho một quan sát mới luôn rộng hơn khoảng hậu nghiệm của giá trị trung bình (mean response).&lt;/p&gt;

&lt;h3 id=&quot;71-ví-dụ-ngắn-tránh-nhầm-lẫn-hai-loại-khoảng&quot;&gt;7.1. Ví dụ ngắn tránh nhầm lẫn hai loại khoảng&lt;/h3&gt;

&lt;p&gt;Giả sử với nhóm học sinh học 6 giờ, mô hình cho:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Khoảng hậu nghiệm cho điểm trung bình (mean score): từ 7.4 đến 8.2.&lt;/li&gt;
  &lt;li&gt;Khoảng dự đoán cho một học sinh cụ thể mới: từ 6.0 đến 9.3.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Khoảng thứ nhất trả lời câu hỏi về điểm trung bình của cả nhóm học sinh cùng học 6 giờ; khoảng thứ hai trả lời câu hỏi về khoảng điểm khả dĩ của một cá nhân cụ thể. Dùng nhầm khoảng thứ nhất để dự báo cho một cá nhân sẽ tạo ra cảm giác chắc chắn quá mức so với thực tế.&lt;/p&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-bayesian-p-value-và-phân-tách-hai-nguồn-phương-sai-dự-đoán&quot;&gt;Giải thích: Tính tay Bayesian \(p\)-value và phân tách hai nguồn phương sai dự đoán&lt;/h3&gt;

&lt;p&gt;Hãy tự kiểm chứng hai phép tính cốt lõi của kiểm tra mô hình và dự đoán bằng những con số nhỏ gọn:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Tự tính Bayesian \(p\)-value cho độ phân tán:&lt;/strong&gt;
Giả sử trên tập dữ liệu thực tế, bạn đo được độ lệch chuẩn mẫu là \(T(y_{\text{obs}}) = 4.2\). Bạn rút \(S = 10\) tập dữ liệu giả lập \(y_{\text{rep}}^{(1)}, \dots, y_{\text{rep}}^{(10)}\) từ phân phối dự báo hậu nghiệm và tính được 10 độ lệch chuẩn mô phỏng:&lt;/p&gt;

\[\{2.8,\ 3.0,\ 3.1,\ 3.3,\ 3.4,\ 3.5,\ 3.6,\ 3.7,\ 3.9,\ 4.3\}.\]

&lt;p&gt;Đếm số giá trị \(\ge 4.2\): chỉ có đúng 1 trên 10 tập (\(4.3\)), nên \(p_B = 1/10 = 0.10\) (nếu chạy \(S=1000\) tập và chỉ có 12 tập vượt quá \(4.2\) thì \(p_B = 0.012\)). Khi \(p_B\) rất nhỏ như vậy, dữ liệu thực phân tán rộng hơn nhiều so với điều mô hình giả định — ta cần xem lại giả định nhiễu hoặc bổ sung biến giải thích.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Tự phân tách phương sai của \(\mu_{\text{new}}\) và \(y_{\text{new}}\):&lt;/strong&gt;
Giả sử tại mức 6 giờ học, bất định đường trung bình có \(\mathrm{SD}(\mu_{\text{new}} \mid y) = 0.30\) (tức phương sai \(0.30^2 = 0.09\)), còn độ nhiễu cá thể quanh đường hồi quy là \(\sigma = 0.80\) (phương sai \(0.80^2 = 0.64\)). Theo quy tắc cộng phương sai của hai nguồn bất định độc lập:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cho điểm trung bình nhóm:&lt;/strong&gt; \(\mathrm{SD}(\mu_{\text{new}} \mid y) = 0.30 \implies\) khoảng 95% rộng \(\pm 1.96(0.30) \approx \pm 0.59\) điểm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cho một học sinh cụ thể:&lt;/strong&gt; \(\operatorname{Var}(y_{\text{new}} \mid y) = 0.09 + 0.64 = 0.73 \implies \mathrm{SD}(y_{\text{new}} \mid y) = \sqrt{0.73} \approx 0.854 \implies\) khoảng 95% rộng \(\pm 1.96(0.854) \approx \pm 1.67\) điểm.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ngay cả khi ta thu thập 100.000 học sinh để phương sai đường trung bình giảm từ \(0.09\) về gần \(0\), độ lệch chuẩn dự đoán cho một học sinh mới vẫn bị chặn dưới bởi \(\sigma = 0.80\).&lt;/p&gt;

&lt;h2 id=&quot;8-kiểm-tra-mô-hình-không-phải-phép-thử-nhị-phân&quot;&gt;8. Kiểm tra mô hình không phải phép thử nhị phân&lt;/h2&gt;

&lt;p&gt;Đừng nhìn việc kiểm tra mô hình theo lối trắng–đen “hoàn hảo hoặc loại bỏ”. Mục đích thực sự là xác định mô hình đang lệch ở đâu, mức độ lệch ra sao và sai lệch đó có ảnh hưởng đến câu hỏi thực tế mà ta cần giải quyết hay không. Một mô hình hơi lệch ở vùng đuôi vẫn có thể dùng tốt nếu mục tiêu chỉ là ước lượng xu hướng trung bình; nhưng nếu bài toán liên quan đến quản trị rủi ro cực trị, chính sai lệch ở đuôi lại là vấn đề nghiêm trọng cần khắc phục.&lt;/p&gt;

&lt;h2 id=&quot;9-cần-làm-gì-khi-mô-hình-không-vượt-qua-kiểm-tra&quot;&gt;9. Cần làm gì khi mô hình không vượt qua kiểm tra?&lt;/h2&gt;

&lt;p&gt;Thay vì phản ứng máy móc bằng cách tăng số mẫu MCMC, hãy rà soát mô hình theo ba hướng chính:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cấu trúc mô hình sinh dữ liệu:&lt;/strong&gt; có quan hệ phi tuyến, hiệu ứng tương tác hay cấu trúc phân nhóm/phân cấp (hierarchical structure) nào bị bỏ sót không?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối tiên nghiệm:&lt;/strong&gt; tiên nghiệm có quá rộng, quá hẹp hoặc tạo ra dự báo tiên nghiệm thiếu hợp lý không?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đặc điểm dữ liệu:&lt;/strong&gt; dữ liệu có điểm ngoại lai, sai số đo lường, biến giải thích bị thiếu hoặc phương sai thay đổi đáng kể không?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Chẩn đoán tốt chính là cơ sở trực tiếp cho bước sửa đổi mô hình (model revision) đúng hướng.&lt;/p&gt;

&lt;h2 id=&quot;10-quy-trình-khép-kín-của-hồi-quy-bayes&quot;&gt;10. Quy trình khép kín của hồi quy Bayes&lt;/h2&gt;

&lt;p&gt;Chương 4 xây dựng một quy trình làm việc hoàn chỉnh gồm bảy bước liên kết chặt chẽ: xác định quá trình sinh dữ liệu, chọn phân phối tiên nghiệm có nguyên tắc, suy luận phân phối hậu nghiệm, kiểm tra chẩn đoán hội tụ của bộ lấy mẫu, kiểm tra mô hình bằng PPC và phân tích phần dư, tạo dự đoán kèm bất định, rồi điều chỉnh mô hình khi cần thiết. Khi thực hiện đầy đủ bảy bước này, hồi quy trở thành một quy trình mô hình hóa khoa học thay vì chỉ là thao tác gọi hàm.&lt;/p&gt;

&lt;h2 id=&quot;11-những-sai-lầm-phổ-biến&quot;&gt;11. Những sai lầm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tin vào phân phối hậu nghiệm mà không kiểm tra mô hình:&lt;/strong&gt; hậu nghiệm chỉ có giá trị khi mô hình tạo ra nó mô tả dữ liệu một cách hợp lý.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chỉ đánh giá độ khớp trên dữ liệu huấn luyện:&lt;/strong&gt; chất lượng thực sự của mô hình thể hiện rõ nhất ở khả năng dự đoán dữ liệu mới.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chỉ kiểm tra một tiêu chí PPC duy nhất:&lt;/strong&gt; một mô hình có thể khớp tốt giá trị trung bình nhưng sai lệch nghiêm trọng về phương sai hoặc vùng đuôi; cần kiểm tra trên nhiều thống kê khác nhau.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;12-tổng-kết-bài-học&quot;&gt;12. Tổng kết bài học&lt;/h2&gt;

&lt;p&gt;Hồi quy Bayes không dừng lại ở việc lấy được phân phối hậu nghiệm của tham số. Giá trị thực tiễn của mô hình nằm ở khả năng tái tạo đặc trưng dữ liệu và đưa ra dự đoán trung thực về bất định. Thiếu bước kiểm tra và dự đoán, quy trình hồi quy Bayes mới chỉ hoàn thành một nửa.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Kiểm tra dự báo hậu nghiệm (PPC) đánh giá xem mô hình có sinh ra dữ liệu giống dữ liệu thực tế hay không; phân tích phần dư và khoảng dự đoán giúp thẩm định tính hữu ích thực sự của mô hình; và một quy trình Bayes hoàn chỉnh luôn bao gồm kiểm tra, dự đoán và điều chỉnh mô hình khi phát hiện sai lệch.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yDPJnV9vcHs&quot;&gt;What is a posterior predictive check and why is it useful?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Giải thích bản chất của kiểm tra dự báo hậu nghiệm và lý do cần kiểm tra khả năng tái tạo dữ liệu, khớp với trọng tâm của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=okjYjClSjOg&quot;&gt;Quantile-Quantile Plots (QQ plots), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Hướng dẫn đọc biểu đồ Q–Q, hỗ trợ phần đối chiếu phân phối phần dư với giả định Chuẩn.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Residual plots&lt;/td&gt;
          &lt;td&gt;Exploring bivariate numerical data&lt;/td&gt;
          &lt;td&gt;AP Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=VamMrPZ-8fc) — Khan Academy, English. Minh họa cách dùng biểu đồ phần dư phát hiện cấu trúc còn sót, bổ trợ cho mục phân tích phần dư.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao một mô hình đã chạy hội tụ nhưng chưa qua kiểm tra PPC thì chưa nên tin dùng hoàn toàn?&lt;/li&gt;
  &lt;li&gt;Sự khác nhau giữa bất định của giá trị trung bình dự đoán và bất định của một quan sát mới là gì?&lt;/li&gt;
  &lt;li&gt;Hãy nêu ba đặc trưng bạn có thể so sánh giữa dữ liệu thực tế và dữ liệu mô phỏng từ phân phối dự báo hậu nghiệm.&lt;/li&gt;
  &lt;li&gt;Nếu biểu đồ phần dư xuất hiện dạng cong rõ rệt, bạn sẽ nghi ngờ giả định nào của mô hình đang bị vi phạm?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), chapters on model checking.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Regression and Other Stories&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), chapters on posterior predictive checks.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter04/04_05_case_study_model_checking_prediction/&quot;&gt;Bài 4.5 - Case Study Model Checking &amp;amp; Prediction&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 4.3: Posterior Inference với PyMC - Từ Theory đến Practice</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_03_posterior_inference_pymc/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_03_posterior_inference_pymc</id>
   <content type="html">&lt;p&gt;Trước khi các ngôn ngữ lập trình xác suất (Probabilistic Programming Languages — PPL) như Stan và PyMC ra đời, việc triển khai một mô hình Bayes phi liên hợp đồng nghĩa với việc tự viết hàng trăm dòng mã tính hàm log-hợp lý, tự đạo hàm bằng tay và tự chỉnh bước nhảy Metropolis. Ngày nay, bạn chỉ cần viết đúng bốn dòng mô tả quá trình sinh dữ liệu — và phần mềm sẽ tự động biên dịch đồ thị tính toán, lấy đạo hàm chính xác và chạy NUTS song song nhiều chuỗi. Hiểu những gì diễn ra bên dưới bốn dòng mã đó là ranh giới giữa người &lt;em&gt;gõ lệnh&lt;/em&gt; và người &lt;em&gt;làm thống kê Bayes&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ biết cách chuyển một mô hình hồi quy tuyến tính Bayes từ công thức trên giấy thành mã nguồn chạy được trong PyMC. Bạn cũng sẽ nắm được quy trình thực hành chuẩn: chuẩn hóa dữ liệu, khai báo phân phối tiên nghiệm và hàm hợp lý, lấy mẫu phân phối hậu nghiệm bằng MCMC, kiểm tra các chỉ số chẩn đoán và diễn giải kết quả.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ ngắn.&lt;/strong&gt; Sau khi đã xác định quá trình sinh dữ liệu và chọn phân phối tiên nghiệm hợp lý, bước tiếp theo là triển khai mô hình trong PyMC để suy luận phân phối hậu nghiệm cho hệ số chặn, hệ số dốc và độ nhiễu. PyMC không thay bạn tư duy về mô hình, mà giúp thực thi tính toán một cách nhất quán và hiệu quả.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Khi PyMC đã chạy xong và trả về mẫu hậu nghiệm, vì sao ta vẫn phải kiểm tra các chỉ số chẩn đoán trước khi diễn giải kết quả?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-lập-trình-xác-suất-vi-phân-tự-động-và-sai-số-monte-carlo&quot;&gt;Kiến thức cần nhớ: Lập trình xác suất, Vi phân tự động và Sai số Monte Carlo&lt;/h2&gt;

&lt;p&gt;Bài học này nối liền lý thuyết xác suất trên giấy với thực hành tính toán hiện đại qua ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đồ thị xác suất và Ngôn ngữ lập trình xác suất (PPL):&lt;/strong&gt; Mỗi khối &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;with pm.Model()&lt;/code&gt; thực chất đang xây dựng một đồ thị có hướng không chu trình (DAG) biểu diễn phân phối đồng thời \(p(y, \theta) = p(y \mid \theta)p(\theta)\). Tách bạch &lt;em&gt;đặc tả mô hình&lt;/em&gt; khỏi &lt;em&gt;thuật toán suy luận&lt;/em&gt; giúp bạn thay đổi giả định phân phối chỉ bằng một dòng lệnh mà không phải viết lại bộ lấy mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vi phân tự động (Reverse-mode Automatic Differentiation):&lt;/strong&gt; Bộ lấy mẫu NUTS cần gradient \(\nabla_\theta \log p(\theta \mid y)\) tại mỗi bước leapfrog. PyMC (thông qua PyTensor) tính đạo hàm này chính xác đến sai số dấu phẩy động bằng quy tắc dây chuyền trên đồ thị tính toán, thay vì xấp xỉ sai phân hữu hạn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sai số chuẩn Monte Carlo (MCSE) và biến đổi thang đo:&lt;/strong&gt; Vì MCMC trả về tập mẫu hữu hạn có tự tương quan, trung bình mẫu luôn mang sai số mô phỏng \(\text{MCSE} = \mathrm{SD}(\theta \mid D)/\sqrt{\text{ESS}}\). Hiểu MCSE giúp bạn biết chính xác bao nhiêu mẫu là đủ thay vì đoán mò số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;draws&lt;/code&gt;.
    &lt;h2 id=&quot;1-từ-mô-hình-trên-giấy-sang-mã-nguồn&quot;&gt;1. Từ mô hình trên giấy sang mã nguồn&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ở hai bài 4.1 và 4.2, ta đã nắm được ba nền tảng: quá trình sinh dữ liệu, cách chọn phân phối tiên nghiệm và trực giác về hồi quy Bayes. Bài này tập trung vào bước triển khai thực hành: dịch mô hình thống kê thành mã nguồn PyMC theo một quy trình rõ ràng — chuẩn bị và chuẩn hóa dữ liệu, khai báo tiên nghiệm, khai báo hàm hợp lý, chạy bộ lấy mẫu, kiểm tra chẩn đoán rồi mới diễn giải phân phối hậu nghiệm.&lt;/p&gt;

&lt;h2 id=&quot;2-vì-sao-cần-mcmc-khi-công-thức-dạng-đóng-không-còn-tồn-tại&quot;&gt;2. Vì sao cần MCMC? Khi công thức dạng đóng không còn tồn tại&lt;/h2&gt;

&lt;h3 id=&quot;21-từ-mô-hình-liên-hợp-sang-mô-hình-không-liên-hợp&quot;&gt;2.1. Từ mô hình liên hợp sang mô hình không liên hợp&lt;/h3&gt;

&lt;p&gt;Ở Chương 2, ta đã làm quen với các &lt;strong&gt;phân phối tiên nghiệm liên hợp (conjugate priors)&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Beta–Binomial:&lt;/strong&gt; tiên nghiệm Beta + hàm hợp lý Binomial \(\to\) hậu nghiệm Beta.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gamma–Poisson:&lt;/strong&gt; tiên nghiệm Gamma + hàm hợp lý Poisson \(\to\) hậu nghiệm Gamma.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Normal–Normal:&lt;/strong&gt; tiên nghiệm Normal + hàm hợp lý Normal \(\to\) hậu nghiệm Normal.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Với những cặp liên hợp này, phân phối hậu nghiệm có &lt;strong&gt;công thức dạng đóng (closed-form)&lt;/strong&gt;, ví dụ:&lt;/p&gt;

\[\theta \mid D \sim \text{Beta}(\alpha_0 + k, \beta_0 + n - k)\]

&lt;p&gt;Ta chỉ cần thay số trực tiếp vào công thức mà không cần mô phỏng hay lấy mẫu.&lt;/p&gt;

&lt;h3 id=&quot;22-hồi-quy-bayes-không-còn-công-thức-giải-tích-đơn-giản&quot;&gt;2.2. Hồi quy Bayes không còn công thức giải tích đơn giản&lt;/h3&gt;

&lt;p&gt;Xét một mô hình hồi quy tuyến tính Bayes tiêu chuẩn:&lt;/p&gt;

\[\begin{aligned}
\beta_0 &amp;amp;\sim \mathcal{N}(5, 5) \\
\beta_1 &amp;amp;\sim \mathcal{N}(2, 5) \\
\sigma &amp;amp;\sim \text{HalfNormal}(2) \\
y_i &amp;amp;\sim \mathcal{N}(\beta_0 + \beta_1 x_i, \sigma^2)
\end{aligned}\]

&lt;p&gt;Trong mô hình này:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Ba tham số (\(\beta_0, \beta_1, \sigma\)) phải được cập nhật đồng thời.&lt;/li&gt;
  &lt;li&gt;Tổ hợp tiên nghiệm Normal và HalfNormal không liên hợp với hàm hợp lý.&lt;/li&gt;
  &lt;li&gt;Phân phối hậu nghiệm đồng thời 3 chiều không có công thức dạng đóng:&lt;/li&gt;
&lt;/ul&gt;

\[p(\beta_0, \beta_1, \sigma \mid D) = \frac{p(D \mid \beta_0, \beta_1, \sigma) \cdot p(\beta_0) \cdot p(\beta_1) \cdot p(\sigma)}{p(D)}\]

&lt;p&gt;với hằng số chuẩn hóa là tích phân 3 chiều:&lt;/p&gt;

\[p(D) = \iiint p(D \mid \beta_0, \beta_1, \sigma) \cdot p(\beta_0) \cdot p(\beta_1) \cdot p(\sigma) \, d\beta_0 \, d\beta_1 \, d\sigma.\]

&lt;p&gt;Tích phân này không thể tính bằng công thức giải tích thông thường.&lt;/p&gt;

&lt;h3 id=&quot;23-mcmc-lấy-mẫu-thay-vì-tính-tích-phân-trực-tiếp&quot;&gt;2.3. MCMC: lấy mẫu thay vì tính tích phân trực tiếp&lt;/h3&gt;

&lt;p&gt;Khi không có công thức dạng đóng, ta sử dụng &lt;strong&gt;MCMC (Markov Chain Monte Carlo)&lt;/strong&gt; để rút mẫu trực tiếp từ phân phối hậu nghiệm.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ý tưởng cốt lõi:&lt;/strong&gt; Thay vì giải tích phân nhiều chiều, ta rút một tập mẫu đại diện từ phân phối hậu nghiệm — tương tự như khảo sát một mẫu đại diện gồm vài nghìn người thay vì hỏi toàn bộ hàng triệu dân.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Quy trình MCMC gồm bốn bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Khởi tạo tại một điểm trong không gian tham số.&lt;/li&gt;
  &lt;li&gt;Dịch chuyển sang điểm mới theo quy tắc xác suất ưu tiên vùng mật độ hậu nghiệm cao.&lt;/li&gt;
  &lt;li&gt;Lặp lại hàng nghìn lần để tạo thành chuỗi mẫu.&lt;/li&gt;
  &lt;li&gt;Dùng tập mẫu thu được để xấp xỉ phân phối hậu nghiệm.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ minh họa trong PyMC:&lt;/strong&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Thay vì tính công thức phức tạp:
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;complicated_integral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(...)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ❌ Không tính được!
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Ta lấy mẫu:
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Khai báo priors
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beta_0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta_0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta_1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Likelihood
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# MCMC: lấy 2000 mẫu từ posterior
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ← ĐÂY LÀ MCMC!
&lt;/span&gt;    
&lt;span class=&quot;c1&quot;&gt;# Kết quả: trace chứa 2000 bộ (β₀, β₁, σ) từ posterior
# Mỗi bộ là một &quot;thế giới có thể&quot; phù hợp với data
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Mẫu kết quả thu được từ MCMC:&lt;/strong&gt;&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Mẫu&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(\beta_0\)&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(\beta_1\)&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(\sigma\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6.8&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.6&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6.5&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.5&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;…&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;…&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;…&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;…&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2000&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6.9&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.0&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.7&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Từ 2000 bộ mẫu này, ta dễ dàng tính các đại lượng suy luận:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Trung bình hậu nghiệm:&lt;/strong&gt; trung bình cộng của các mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng tin cậy hậu nghiệm 95%:&lt;/strong&gt; lấy phân vị 2.5% và 97.5% của tập mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất \(\beta_1 &amp;gt; 0\):&lt;/strong&gt; tỷ lệ số mẫu có giá trị \(\beta_1 &amp;gt; 0\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;24-so-sánh-phương-pháp-liên-hợp-và-mcmc&quot;&gt;2.4. So sánh phương pháp liên hợp và MCMC&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Tiêu chí&lt;/th&gt;
      &lt;th&gt;Tiên nghiệm liên hợp&lt;/th&gt;
      &lt;th&gt;MCMC (Hồi quy)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Tiên nghiệm&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Beta, Gamma, Normal đơn giản&lt;/td&gt;
      &lt;td&gt;Linh hoạt cho nhiều phân phối khác nhau&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Hàm hợp lý&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Binomial, Poisson, Normal tương thích&lt;/td&gt;
      &lt;td&gt;Normal hoặc các mô hình nhiều tham số&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Hậu nghiệm&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Có công thức dạng đóng&lt;/td&gt;
      &lt;td&gt;Không có công thức dạng đóng&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Cách tính&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Thay số trực tiếp vào công thức&lt;/td&gt;
      &lt;td&gt;Lấy mẫu mô phỏng bằng MCMC&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Bản chất kết quả&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Phân phối giải tích chính xác&lt;/td&gt;
      &lt;td&gt;Xấp xỉ số hội tụ về phân phối đúng&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Ví dụ&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Beta(17, 103)&lt;/td&gt;
      &lt;td&gt;2000 bộ mẫu (\(\beta_0, \beta_1, \sigma\))&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Thời gian chạy&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Dưới 1 giây&lt;/td&gt;
      &lt;td&gt;Vài giây đến vài chục giây&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Độ chính xác&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Chính xác giải tích (100%)&lt;/td&gt;
      &lt;td&gt;Sai số Monte Carlo rất nhỏ khi đủ mẫu&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;25-pymc-tự-động-hóa-phần-tính-toán-của-mcmc&quot;&gt;2.5. PyMC tự động hóa phần tính toán của MCMC&lt;/h3&gt;

&lt;p&gt;Một ưu điểm thực tế của PyMC là bạn không cần tự lập trình lại các thuật toán như Metropolis–Hastings, Gibbs sampling, HMC hay NUTS. Thay vào đó, bạn chỉ cần tập trung vào bốn việc: khai báo mô hình (tiên nghiệm và hàm hợp lý), gọi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.sample()&lt;/code&gt;, kiểm tra các chỉ số chẩn đoán (\(\hat{R}\), ESS) và diễn giải kết quả. PyMC sẽ tự động chọn bộ lấy mẫu phù hợp (thường là NUTS), điều chỉnh tham số trong giai đoạn làm nóng (warm-up), chạy song song nhiều chuỗi và cảnh báo nếu phát hiện vấn đề hội tụ.&lt;/p&gt;

&lt;h3 id=&quot;26-khi-nào-dùng-công-thức-dạng-đóng-khi-nào-dùng-mcmc&quot;&gt;2.6. Khi nào dùng công thức dạng đóng, khi nào dùng MCMC?&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Tình huống&lt;/th&gt;
      &lt;th&gt;Phương pháp phù hợp&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Mô hình liên hợp, ít tham số&lt;/td&gt;
      &lt;td&gt;Công thức dạng đóng&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mô hình không liên hợp hoặc nhiều tham số&lt;/td&gt;
      &lt;td&gt;MCMC&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Hồi quy từ 3 tham số trở lên&lt;/td&gt;
      &lt;td&gt;MCMC (PyMC)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mô hình phân cấp (Hierarchical models)&lt;/td&gt;
      &lt;td&gt;MCMC&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mô hình hỗn hợp (Mixture models)&lt;/td&gt;
      &lt;td&gt;MCMC&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Nguyên tắc thực hành:&lt;/strong&gt; Khi phân phối hậu nghiệm không thể tính gọn bằng công thức dạng đóng, hãy sử dụng MCMC.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;3-cấu-trúc-một-mô-hình-hồi-quy-bayes-tối-giản-trong-pymc&quot;&gt;3. Cấu trúc một mô hình hồi quy Bayes tối giản trong PyMC&lt;/h2&gt;

&lt;p&gt;Khi viết mã trong PyMC, hãy bám sát thứ tự của mô hình thống kê: khai báo tiên nghiệm cho \(\alpha\), \(\beta\), \(\sigma\), rồi khai báo hàm hợp lý:&lt;/p&gt;

\[y_i \sim \mathcal{N}(\alpha + \beta x_i,\sigma).\]

&lt;p&gt;Mã nguồn cần phản ánh đúng cấu trúc của mô hình toán học, thay vì thay đổi mô hình chỉ để chiều theo cú pháp thư viện.&lt;/p&gt;

&lt;h3 id=&quot;31-ví-dụ-tối-giản-chạy-được-bằng-pymc&quot;&gt;3.1. Ví dụ tối giản chạy được bằng PyMC&lt;/h3&gt;

&lt;p&gt;Xét một tập dữ liệu nhỏ về chiều cao và cân nặng:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;height&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;150&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;155&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;160&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;165&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;170&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;175&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;180&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;185&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;54&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;57&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;62&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;66&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;76&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;82&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;height&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reg_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;draws&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;target_accept&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Từng khối lệnh trong đoạn mã ánh xạ trực tiếp sang mô hình thống kê:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alpha&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;beta&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sigma&lt;/code&gt; là phân phối tiên nghiệm của ba tham số cốt lõi.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mu = alpha + beta * x_z&lt;/code&gt; biểu diễn xu hướng trung bình tuyến tính.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y_obs = pm.Normal(...)&lt;/code&gt; là hàm hợp lý mô tả cách dữ liệu dao động quanh đường trung bình.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.sample(...)&lt;/code&gt; thực hiện lấy mẫu từ phân phối hậu nghiệm thay vì tìm một ước lượng điểm duy nhất.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Giữ được sự tương ứng một-một giữa công thức trên giấy và mã nguồn là dấu hiệu cho thấy bạn đang triển khai mô hình đúng hướng.&lt;/p&gt;

&lt;h2 id=&quot;4-vì-sao-nên-chuẩn-hóa-dữ-liệu-trước-khi-lấy-mẫu&quot;&gt;4. Vì sao nên chuẩn hóa dữ liệu trước khi lấy mẫu?&lt;/h2&gt;

&lt;p&gt;Chuẩn hóa biến trước khi chạy hồi quy Bayes mang lại bốn lợi ích đồng thời: phân phối tiên nghiệm dễ chọn hơn, hệ số chặn dễ diễn giải hơn, bộ lấy mẫu hội tụ ổn định hơn và phân phối hậu nghiệm ít bị méo do sự chênh lệch đơn vị đo giữa các biến. Vì vậy, chuẩn hóa thường là bước tiền xử lý nên thực hiện trong thực hành.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-vì-sao-pymc-cần-chuẩn-hóa-dữ-liệu-thung-lũng-dẹt-vs-hình-tròn-mượt&quot;&gt;Video ngắn: Vì sao PyMC cần Chuẩn hóa Dữ liệu? Thung lũng Dẹt vs Hình tròn Mượt&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch04-03a-pymc-standardize-geometry.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): so sánh hình học hậu nghiệm bị kéo dẹt trước khi chuẩn hóa (làm bộ lấy mẫu zig-zag chậm) với hình tròn trực giao giúp NUTS chạy nhanh với ESS cao.&lt;/p&gt;

&lt;h2 id=&quot;5-sau-khi-lấy-mẫu-cần-đọc-gì-đầu-tiên&quot;&gt;5. Sau khi lấy mẫu, cần đọc gì đầu tiên?&lt;/h2&gt;

&lt;p&gt;Người mới thường xem ngay trung bình hậu nghiệm và khoảng tin cậy, nhưng thứ cần kiểm tra đầu tiên phải là các &lt;strong&gt;chỉ số chẩn đoán (diagnostics)&lt;/strong&gt;: đồ thị vệt mẫu (trace plot) có trộn đều không, \(\hat{R}\) có gần 1 không, số mẫu hiệu dụng (ESS) có đủ lớn không, và bộ lấy mẫu có phát sinh cảnh báo (như divergence) hay không. Nếu các chỉ số này chưa đạt, mọi diễn giải thống kê phía sau chỉ nên xem là tạm thời.&lt;/p&gt;

&lt;h2 id=&quot;6-diễn-giải-phân-phối-hậu-nghiệm-trong-hồi-quy&quot;&gt;6. Diễn giải phân phối hậu nghiệm trong hồi quy&lt;/h2&gt;

&lt;p&gt;Khi quá trình lấy mẫu đã đạt yêu cầu chẩn đoán, ta bắt đầu diễn giải từng tham số:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hệ số chặn \(\alpha\):&lt;/strong&gt; với dữ liệu đã chuẩn hóa hoặc dịch tâm, \(\alpha\) biểu thị giá trị trung bình của \(y\) tại mức trung tâm của \(x\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hệ số dốc \(\beta\):&lt;/strong&gt; phân phối hậu nghiệm của \(\beta\) cho biết chiều hướng (dương hay âm), độ lớn và mức độ bất định của mối quan hệ; đồng thời cho phép tính trực tiếp các xác suất như \(P(\beta &amp;gt; 0 \mid D)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ nhiễu \(\sigma\):&lt;/strong&gt; cho biết mức độ phân tán của dữ liệu quanh đường hồi quy, phản ánh phần biến thiên mà mô hình chưa giải thích được.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;61-ví-dụ-cập-nhật-từ-tiên-nghiệm-sang-hậu-nghiệm&quot;&gt;6.1. Ví dụ: cập nhật từ tiên nghiệm sang hậu nghiệm&lt;/h3&gt;

&lt;p&gt;Giả sử sau khi khớp một mô hình hồi quy tuyến tính một biến bằng PyMC, ta thu được các kết quả sau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tiên nghiệm:&lt;/strong&gt; \(\alpha\sim\mathcal N(60,20),\;\beta\sim\mathcal N(0,2),\;\sigma\sim\text{HalfNormal}(5)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tóm tắt hậu nghiệm:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;
\[\alpha\mid D\approx \mathcal N(63.2,\,1.1^2)\]
      &lt;/li&gt;
      &lt;li&gt;
\[\beta\mid D\approx \mathcal N(0.78,\,0.09^2)\]
      &lt;/li&gt;
      &lt;li&gt;\(\sigma\mid D\) có trung bình hậu nghiệm khoảng \(2.4\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Từ kết quả trên, có thể rút ra ba nhận xét: dữ liệu đã kéo hệ số chặn từ vùng tiên nghiệm quanh 60 lên khoảng 63.2; hệ số dốc dương rõ rệt với độ lệch chuẩn nhỏ (0.09); và độ nhiễu còn lại quanh đường hồi quy khoảng 2.4 đơn vị của biến phản hồi.&lt;/p&gt;

&lt;p&gt;Nếu tính khoảng hậu nghiệm xấp xỉ 95% cho hệ số dốc theo phân phối Chuẩn:&lt;/p&gt;

\[0.78\pm 1.96\times 0.09\Rightarrow [0.604,\;0.956].\]

&lt;p&gt;Khoảng này nằm hoàn toàn phía trên 0, cho thấy bằng chứng hậu nghiệm ủng hộ rõ rệt mối quan hệ dương.&lt;/p&gt;

&lt;h3 id=&quot;giải-thích-kiểm-tra-độ-chính-xác-mcse-và-quy-đổi-ngược-hệ-số-về-thang-đo-gốc&quot;&gt;Giải thích: Kiểm tra độ chính xác MCSE và quy đổi ngược hệ số về thang đo gốc&lt;/h3&gt;

&lt;p&gt;Sau khi PyMC in ra bảng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;az.summary&lt;/code&gt;, hai phép tính tay ngắn gọn sau sẽ giúp bạn kiểm soát hoàn toàn chất lượng và ý nghĩa thực tế của kết quả:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đo sai số mô phỏng bằng MCSE:&lt;/strong&gt; Trong ví dụ ở mục 6.1, giả sử hậu nghiệm của hệ số dốc có trung bình \(\bar\beta = 0.78\), độ lệch chuẩn \(\mathrm{SD} = 0.09\) và số mẫu hiệu dụng \(\text{ESS} = 900\). Sai số chuẩn Monte Carlo của ước lượng trung bình là:
\(\text{MCSE} = \frac{\mathrm{SD}}{\sqrt{\text{ESS}}} = \frac{0.09}{\sqrt{900}} = \frac{0.09}{30} = 0.003.\)
Con số \(0.003\) nhỏ hơn 30 lần so với độ bất định thống kê thật (\(0.09\)), nghĩa là chữ số thập phân thứ hai của \(0.78\) đã rất ổn định. Ngược lại, nếu \(\text{ESS} = 25\) thì \(\text{MCSE} = 0.09/5 = 0.018\) (chiếm tới 20% độ lệch chuẩn) — khi đó bạn cần chạy thêm mẫu hoặc kiểm tra lại mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy đổi ngược hệ số từ thang chuẩn hóa về thang gốc:&lt;/strong&gt; Với 8 điểm dữ liệu chiều cao–cân nặng ở mục 3.1, ta có \(\bar x = 167.5\text{ cm},\ s_x \approx 11.46\text{ cm}\) và \(\bar y = 64.625\text{ kg},\ s_y \approx 10.56\text{ kg}\). Nếu một mẫu hậu nghiệm trên thang chuẩn hóa là \((\alpha_z, \beta_z, \sigma_z) = (0.00,\ 0.98,\ 0.15)\), thì trên thang đo gốc:
    &lt;ul&gt;
      &lt;li&gt;Hệ số dốc: \(\beta_{\text{gốc}} = \beta_z \cdot \frac{s_y}{s_x} = 0.98 \times \frac{10.56}{11.46} \approx 0.903\text{ kg/cm}\).&lt;/li&gt;
      &lt;li&gt;Độ nhiễu: \(\sigma_{\text{gốc}} = \sigma_z \cdot s_y = 0.15 \times 10.56 \approx 1.58\text{ kg}\).&lt;/li&gt;
      &lt;li&gt;Hệ số chặn tại mốc chiều cao trung bình \(167.5\text{ cm}\) là \(\bar y + \alpha_z s_y = 64.625\text{ kg}\) (có ý nghĩa thực tế trực tiếp, thay vì tại \(0\text{ cm}\)).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Luôn quy đổi từng mẫu hậu nghiệm trước rồi mới lấy trung bình và khoảng tin cậy HDI trên thang gốc để giữ trọn vẹn cấu trúc bất định.&lt;/p&gt;

&lt;h2 id=&quot;7-chuyển-từ-suy-luận-tham-số-sang-dự-đoán&quot;&gt;7. Chuyển từ suy luận tham số sang dự đoán&lt;/h2&gt;

&lt;p&gt;Hồi quy Bayes không dừng lại ở việc ước lượng hệ số dốc, mà còn cung cấp dự đoán kèm mức độ bất định cho các quan sát mới. Khi đã có các mẫu rút từ phân phối hậu nghiệm (posterior draws), việc tính phân phối dự báo hậu nghiệm (posterior predictive) trong PyMC diễn ra rất trực tiếp.&lt;/p&gt;

&lt;h3 id=&quot;71-ví-dụ-minh-họa-dự-đoán-cân-nặng-cho-người-cao-175-cm&quot;&gt;7.1. Ví dụ minh họa: dự đoán cân nặng cho người cao 175 cm&lt;/h3&gt;

&lt;p&gt;Với mô hình ở mục 3.1, ta rút các mẫu hậu nghiệm và lan truyền bất định sang dự đoán tại chiều cao 175 cm:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;extract&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;group&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;alpha_draws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_draws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sigma_draws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x_new_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;175&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;mu_new_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_draws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_draws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_new_z&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_new_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_new_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma_draws&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;mu_new&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_new_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_new&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_new_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Hai biến thu được trả lời hai câu hỏi khác nhau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mu_new&lt;/code&gt; biểu diễn phân phối cho &lt;strong&gt;giá trị trung bình dự đoán&lt;/strong&gt; của nhóm người cao 175 cm.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y_new&lt;/code&gt; biểu diễn phân phối cho &lt;strong&gt;một quan sát mới&lt;/strong&gt; — tức cân nặng của một cá nhân cụ thể cao 175 cm.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Giả sử sau khi tóm tắt mẫu, trung bình của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mu_new&lt;/code&gt; vào khoảng 71 kg với khoảng 89% từ 69 đến 73 kg, còn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y_new&lt;/code&gt; có khoảng dự đoán 89% rộng hơn, từ 63 đến 79 kg. Kết quả này phản ánh đúng tinh thần Bayes: mô hình khá chắc chắn về xu hướng trung bình tại chiều cao 175 cm, nhưng vẫn ghi nhận đầy đủ độ phân tán khi dự đoán cho một cá nhân riêng lẻ.&lt;/p&gt;

&lt;h2 id=&quot;8-quy-trình-thực-hành-tối-thiểu-với-pymc&quot;&gt;8. Quy trình thực hành tối thiểu với PyMC&lt;/h2&gt;

&lt;p&gt;Bạn có thể tổ chức quy trình làm việc thành ba giai đoạn nối tiếp nhau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Trước khi chạy:&lt;/strong&gt; kiểm tra xem biến có cần chuẩn hóa không, phân phối tiên nghiệm có hợp lý theo thang đo dữ liệu không và quá trình sinh dữ liệu đã được viết rõ ràng chưa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trong khi chạy:&lt;/strong&gt; theo dõi xem bộ lấy mẫu có phát sinh cảnh báo hay không và giai đoạn khởi động (warm-up) đã đủ dài chưa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sau khi chạy:&lt;/strong&gt; kiểm tra trace plot, \(\hat{R}\) và ESS trước; sau đó mới diễn giải phân phối hậu nghiệm của tham số và kiểm tra phân phối dự báo hậu nghiệm.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;ghi-chú-về-bối-cảnh-biết-trước-và-chưa-biết-phương-sai-nhiễu&quot;&gt;Ghi chú về bối cảnh biết trước và chưa biết phương sai nhiễu&lt;/h3&gt;

&lt;p&gt;Trong thực hành với PyMC, ta thường suy luận đồng thời \(\sigma\), nên khoảng tin cậy hậu nghiệm của hệ số dốc đã tự động phản ánh bất định về nhiễu. Nếu cố định trước \(\sigma\) trong một bài toán đặc thù, khoảng ước lượng của hệ số dốc sẽ hẹp hơn. Do đó, khi báo cáo kết quả, cần nêu rõ \(\sigma\) được ước lượng hay được cố định.&lt;/p&gt;

&lt;h2 id=&quot;9-những-lỗi-thường-gặp-khi-mới-dùng-pymc&quot;&gt;9. Những lỗi thường gặp khi mới dùng PyMC&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem PyMC như hộp đen:&lt;/strong&gt; nếu không nắm vững mô hình thống kê phía sau, bạn sẽ khó đánh giá ý nghĩa của tiên nghiệm, không hiểu cảnh báo của bộ lấy mẫu và khó nhận ra khi nào kết quả hậu nghiệm không đáng tin cậy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chỉ báo cáo trung bình hậu nghiệm:&lt;/strong&gt; một con số trung bình không đủ để truyền đạt kết quả Bayes; cần trình bày thêm khoảng bất định, xác suất vượt ngưỡng, hình dạng phân phối và bất định dự đoán.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bỏ qua bước kiểm tra mô hình:&lt;/strong&gt; khớp xong mô hình mới là một nửa công việc. Bài tiếp theo sẽ trình bày chi tiết về kiểm tra dự báo hậu nghiệm, phân tích phần dư và đánh giá chất lượng dự đoán.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;10-tổng-kết-bài-học&quot;&gt;10. Tổng kết bài học&lt;/h2&gt;

&lt;p&gt;Mục tiêu của bài này không phải là ghi nhớ thuộc lòng từng hàm của PyMC, mà là thấy được sự liền mạch giữa tư duy mô hình hóa và mã nguồn triển khai. PyMC chỉ là công cụ tính toán; phần quyết định chất lượng phân tích vẫn nằm ở cấu trúc mô hình, phân phối tiên nghiệm, chẩn đoán hội tụ và cách diễn giải kết quả.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; PyMC cho phép triển khai hồi quy Bayes theo đúng cấu trúc tiên nghiệm + hàm hợp lý + hậu nghiệm; sau khi lấy mẫu, chẩn đoán hội tụ luôn phải được kiểm tra trước khi diễn giải tham số; và giá trị đầy đủ của suy luận hậu nghiệm nằm ở cả việc ước lượng tham số lẫn tạo dự đoán có kèm bất định.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jrU0UBr2z3k&quot;&gt;[114] Getting Started with PyMC (Chris Fonnesbeck)&lt;/a&gt; — Data Umbrella, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Hướng dẫn khai báo mô hình và lấy mẫu trong PyMC, khớp với bước chuyển từ mô hình trên giấy sang mã nguồn trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=fpS0NjqNHn8&quot;&gt;L4: Interpretable Linear Regressions (State of Bayes Lecture Series)&lt;/a&gt; — PyMC Labs, English. Trình bày hồi quy tuyến tính trong PyMC và cách diễn giải hệ số, bổ trợ cho quy trình chuẩn hóa, tiên nghiệm và hàm hợp lý.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=911d4A1U0BE&quot;&gt;Chris Fonnesbeck - Probabilistic Python: An Introduction to Bayesian Modeling with PyMC&lt;/a&gt; — PyData, English. Bài giới thiệu đầy đủ hơn về mô hình hóa Bayes với PyMC, bao gồm cả đặt tiên nghiệm và kiểm tra sau lấy mẫu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Hãy liệt kê 5 bước tối thiểu trong một quy trình hồi quy Bayes với PyMC.&lt;/li&gt;
  &lt;li&gt;Vì sao chuẩn hóa dữ liệu hỗ trợ đồng thời cho cả việc chọn phân phối tiên nghiệm lẫn quá trình lấy mẫu?&lt;/li&gt;
  &lt;li&gt;Nếu phân phối hậu nghiệm của hệ số dốc trông hợp lý nhưng chỉ số \(\hat{R}\) chưa đạt yêu cầu, bạn cần xử lý thế nào?&lt;/li&gt;
  &lt;li&gt;Trong hồi quy Bayes, vì sao bước dự đoán có vai trò quan trọng không kém bước ước lượng tham số?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;PyMC Documentation.&lt;/li&gt;
  &lt;li&gt;ArviZ Documentation.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 4-5.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter04/04_04_model_checking_prediction/&quot;&gt;4.4 Model Checking và Prediction - Đảm bảo Model Tốt&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 4.2b: Phương pháp MCMC - Lý thuyết Toán học</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_02b_mcmc_theory/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_02b_mcmc_theory</id>
   <content type="html">&lt;p&gt;Mùa xuân năm 1953 tại phòng thí nghiệm Los Alamos, nhóm năm nhà khoa học Nicholas Metropolis, Arianna Rosenbluth, Marshall Rosenbluth, Augusta Teller và Edward Teller đứng trước một bài toán hóc búa của vật lý thống kê: tính giá trị trung bình của một tích phân nhiều trăm chiều mô tả vị trí các phân tử chất lỏng. Tính trực tiếp trên lưới là bất khả thi — số ô lưới vượt xa số nguyên tử trong vũ trụ. Giải pháp của họ đã thay đổi cả lịch sử thống kê hiện đại: thay vì đi khắp không gian để tính tích phân, hãy thiết kế một &lt;strong&gt;chuyến đi ngẫu nhiên có luật lệ&lt;/strong&gt; sao cho thời gian hạt dừng lại ở mỗi vùng tỷ lệ đúng với mật độ xác suất của vùng đó.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ nắm vững cơ sở toán học giải thích &lt;strong&gt;vì sao MCMC hoạt động&lt;/strong&gt;. Cụ thể, bạn sẽ hiểu bốn nội dung chính: (1) nguyên lý Monte Carlo — dùng lấy mẫu để xấp xỉ tích phân, (2) thuật toán Metropolis–Hastings — cơ chế đề xuất, chấp nhận/bác bỏ và điều kiện hội tụ, (3) lấy mẫu Gibbs (Gibbs sampling) — cập nhật lần lượt từng tham số theo phân phối có điều kiện, và (4) các chỉ số chẩn đoán hội tụ \(\hat{R}\) (R-hat) và ESS.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Vì sao ta không lấy mẫu ngẫu nhiên trực tiếp từ phân phối hậu nghiệm mà phải xây dựng một chuỗi Markov để tiến dần về phân phối đó?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-tích-phân-nhiều-chiều-chuỗi-markov-và-động-lực-học-hamilton&quot;&gt;Kiến thức cần nhớ: Tích phân nhiều chiều, Chuỗi Markov và Động lực học Hamilton&lt;/h2&gt;

&lt;p&gt;MCMC là điểm giao nhau đẹp đẽ của ba nhánh toán học kinh điển mà sinh viên đại học đã từng chạm qua từng mảnh riêng lẻ:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết tích phân và phương pháp Monte Carlo:&lt;/strong&gt; Mọi câu hỏi suy luận Bayes (trung bình, phương sai, khoảng tin cậy, xác suất vượt ngưỡng) đều quy về tích phân \(\mathbb{E}[g(\theta)\mid D] = \int g(\theta)p(\theta\mid D)\,d\theta\). Khi số chiều \(d\) tăng, phương pháp lưới số bùng nổ theo \(O(K^d)\) (&lt;em&gt;lời nguyền số chiều&lt;/em&gt;), trong khi sai số Monte Carlo chỉ phụ thuộc vào cỡ mẫu hiệu dụng \(O(1/\sqrt{\text{ESS}})\), độc lập với \(d\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết chuỗi Markov và điều kiện cân bằng chi tiết:&lt;/strong&gt; Một quá trình ngẫu nhiên chỉ phụ thuộc trạng thái hiện tại sẽ hội tụ về phân phối dừng duy nhất \(\pi(\theta)\) nếu thỏa tính bất khả quy, không tuần hoàn và hồi quy dương. Điều kiện &lt;strong&gt;cân bằng chi tiết&lt;/strong&gt; \(\pi(\theta)T(\theta \to \theta&apos;) = \pi(\theta&apos;)T(\theta&apos; \to \theta)\) là chiếc chìa khóa đại số bảo đảm \(\pi\) chính là phân phối dừng mà không cần biết hằng số chuẩn hóa \(p(D)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cơ học giải tích và hình học vi phân (HMC/NUTS):&lt;/strong&gt; Ở số chiều cao, bước đi ngẫu nhiên (Metropolis) hầu như luôn đâm ra ngoài vùng xác suất cao (&lt;em&gt;typical set&lt;/em&gt;). Hamiltonian Monte Carlo mượn phương trình Hamilton từ vật lý cổ điển, dùng gradient \(-\nabla \log p(\theta\mid D)\) như lực hấp dẫn để trượt dọc theo các đường đồng mức mật độ cao.
    &lt;h2 id=&quot;1-từ-bài-toán-suy-luận-bayes-đến-những-tích-phân-khó-tính&quot;&gt;1. Từ bài toán suy luận Bayes đến những tích phân khó tính&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;11-công-thức-bayes-mới-chỉ-là-điểm-khởi-đầu&quot;&gt;1.1. Công thức Bayes mới chỉ là điểm khởi đầu&lt;/h3&gt;

&lt;p&gt;Khi có dữ liệu \(D\) và cần suy luận về tham số \(\theta\), định lý Bayes cho ta:&lt;/p&gt;

\[p(\theta \mid D) = \frac{p(D \mid \theta) \cdot p(\theta)}{p(D)}.\]

&lt;p&gt;Tuy nhiên, để rút ra kết luận cụ thể từ phân phối hậu nghiệm này, ta cần trả lời các câu hỏi định lượng như:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Câu hỏi 1 – Giá trị kỳ vọng là bao nhiêu?&lt;/strong&gt; Muốn tìm trung bình hậu nghiệm của \(\theta\), ta cần tính:&lt;/li&gt;
&lt;/ul&gt;

\[\mathbb{E}[\theta \mid D] = \int \theta \cdot p(\theta \mid D) \, d\theta.\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Câu hỏi 2 – Khoảng giá trị nào chứa 95% khối lượng xác suất?&lt;/strong&gt; Ta cần tìm hai ngưỡng \(a\) và \(b\) thỏa mãn:&lt;/li&gt;
&lt;/ul&gt;

\[\int_a^b p(\theta \mid D) \, d\theta = 0.95.\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Câu hỏi 3 – Xác suất để \(\theta\) vượt ngưỡng \(c\) là bao nhiêu?&lt;/strong&gt; Ví dụ, xác suất hệ số dốc dương (\(\theta &amp;gt; 0\)):&lt;/li&gt;
&lt;/ul&gt;

\[p(\theta &amp;gt; c \mid D) = \int_c^\infty p(\theta \mid D) \, d\theta.\]

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Nhận xét:&lt;/strong&gt; Mọi câu hỏi suy luận cơ bản trong thống kê Bayes đều quy về việc tính &lt;strong&gt;tích phân&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;12-nút-thắt-nằm-ở-mẫu-số-pd&quot;&gt;1.2. Nút thắt nằm ở mẫu số \(p(D)\)&lt;/h3&gt;

&lt;p&gt;Xét lại công thức Bayes:&lt;/p&gt;

\[p(\theta \mid D) = \frac{p(D \mid \theta) \cdot p(\theta)}{p(D)}.\]

&lt;p&gt;Phần tử số gồm hàm hợp lý \(p(D \mid \theta)\) (do mô hình xác định) và phân phối tiên nghiệm \(p(\theta)\) (do ta lựa chọn), nên có thể tính được tại bất kỳ điểm \(\theta\) nào. Khó khăn nằm ở mẫu số \(p(D)\) — hằng số chuẩn hóa là tích phân trên toàn bộ không gian tham số:&lt;/p&gt;

\[p(D) = \int p(D \mid \theta) \cdot p(\theta) \, d\theta.\]

&lt;p&gt;&lt;strong&gt;Ví dụ cụ thể:&lt;/strong&gt; Trong bài toán hồi quy tuyến tính với 3 tham số \(\theta = (\beta_0, \beta_1, \sigma)\) và \(n = 100\) điểm dữ liệu, \(p(D)\) là một tích phân &lt;strong&gt;3 chiều&lt;/strong&gt; theo ba tham số chưa biết:&lt;/p&gt;

\[p(D) = \iiint \prod_{i=1}^{100} \mathcal{N}(y_i \mid \beta_0 + \beta_1 x_i, \sigma^2) \cdot \mathcal{N}(\beta_0) \cdot \mathcal{N}(\beta_1) \cdot \text{HalfNormal}(\sigma) \, d\beta_0 \, d\beta_1 \, d\sigma.\]

&lt;p&gt;Ngay cả ở 3 chiều, khi phân phối tiên nghiệm không liên hợp với hàm hợp lý, tích phân này đã không có nghiệm giải tích dạng đóng; và khi mô hình mở rộng lên hàng chục hoặc hàng trăm tham số, việc tính tích phân trực tiếp bằng phương pháp lưới số cũng trở nên bất khả thi.&lt;/p&gt;

&lt;h3 id=&quot;13-nguyên-lý-monte-carlo-xấp-xỉ-tích-phân-bằng-lấy-mẫu&quot;&gt;1.3. Nguyên lý Monte Carlo: xấp xỉ tích phân bằng lấy mẫu&lt;/h3&gt;

&lt;p&gt;Thay vì tính tích phân giải tích, phương pháp &lt;strong&gt;Monte Carlo&lt;/strong&gt; xấp xỉ các đại lượng kỳ vọng thông qua lấy mẫu. Nếu ta có thể rút được \(S\) mẫu \(\theta^{(1)}, \theta^{(2)}, \ldots, \theta^{(S)}\) từ phân phối hậu nghiệm \(p(\theta \mid D)\), thì:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Trung bình mẫu&lt;/strong&gt; \(\bar{\theta} = \frac{1}{S}\sum_{s=1}^{S} \theta^{(s)}\) sẽ hội tụ về \(\mathbb{E}[\theta \mid D]\) khi \(S\) đủ lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các phân vị mẫu&lt;/strong&gt; sẽ xấp xỉ các khoảng tin cậy hậu nghiệm (credible intervals).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cơ sở của phương pháp này là &lt;strong&gt;Luật Số Lớn&lt;/strong&gt;:&lt;/p&gt;

\[\frac{1}{S}\sum_{s=1}^{S} g(\theta^{(s)}) \xrightarrow{p} \mathbb{E}[g(\theta) \mid D] \quad \text{khi } S \to \infty.\]

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Tóm tắt bước 1:&lt;/strong&gt; Thay vì tính trực tiếp tích phân, ta lấy mẫu từ phân phối hậu nghiệm rồi tính các đại lượng thống kê trên tập mẫu đó.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;14-bài-toán-mới-làm-sao-lấy-mẫu-khi-chưa-biết-ptheta-mid-d&quot;&gt;1.4. Bài toán mới: làm sao lấy mẫu khi chưa biết \(p(\theta \mid D)\)?&lt;/h3&gt;

&lt;p&gt;Đến đây xuất hiện một vòng lặp: muốn xấp xỉ tích phân, ta cần mẫu từ phân phối hậu nghiệm; nhưng chính vì không tính được \(p(D)\) nên ta không có biểu thức chuẩn hóa của \(p(\theta \mid D)\) để lấy mẫu trực tiếp.&lt;/p&gt;

&lt;p&gt;Giải pháp là xây dựng một &lt;strong&gt;chuỗi các điểm&lt;/strong&gt; \(\theta^{(0)}, \theta^{(1)}, \theta^{(2)}, \ldots\) bắt đầu từ một vị trí khởi tạo bất kỳ và dịch chuyển dần theo quy tắc xác suất, sao cho sau đủ nhiều bước, phân phối của các điểm \(\theta^{(t)}\) trùng khớp với phân phối hậu nghiệm. Đó chính là ý tưởng cốt lõi của &lt;strong&gt;Markov Chain Monte Carlo (MCMC)&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-xây-dựng-chuỗi-markov-hội-tụ-về-phân-phối-hậu-nghiệm&quot;&gt;2. Xây dựng chuỗi Markov hội tụ về phân phối hậu nghiệm&lt;/h2&gt;

&lt;h3 id=&quot;21-chuỗi-markov-hoạt-động-như-thế-nào&quot;&gt;2.1. Chuỗi Markov hoạt động như thế nào?&lt;/h3&gt;

&lt;p&gt;Có thể hình dung không gian tham số như một địa hình đồi núi, trong đó độ cao tại mỗi điểm tương ứng với mật độ xác suất hậu nghiệm. Ta không biết trước đỉnh núi nằm ở đâu, nhưng tại mỗi bước có thể so sánh độ cao giữa vị trí hiện tại và một vị trí đề xuất lân cận: nếu điểm mới cao hơn thì di chuyển tới đó, còn nếu thấp hơn thì vẫn có một xác suất nhất định để bước tới hoặc ở lại. Lặp lại quá trình này hàng nghìn lần, chuỗi sẽ dành phần lớn thời gian ở những vùng có xác suất cao theo đúng tỷ lệ mật độ của phân phối mục tiêu.&lt;/p&gt;

&lt;p&gt;Về mặt toán học, &lt;strong&gt;chuỗi Markov&lt;/strong&gt; là dãy biến ngẫu nhiên \(\theta^{(0)}, \theta^{(1)}, \theta^{(2)}, \ldots\) có tính chất không nhớ — trạng thái kế tiếp chỉ phụ thuộc vào trạng thái hiện tại:&lt;/p&gt;

\[p(\theta^{(t)} \mid \theta^{(t-1)}, \theta^{(t-2)}, \ldots) = p(\theta^{(t)} \mid \theta^{(t-1)}).\]

&lt;h3 id=&quot;22-phân-phối-dừng-và-định-lý-ergodic&quot;&gt;2.2. Phân phối dừng và định lý Ergodic&lt;/h3&gt;

&lt;p&gt;Nếu được thiết kế phù hợp và chạy đủ lâu, chuỗi Markov sẽ quên đi vị trí khởi tạo ban đầu và hội tụ về một phân phối giới hạn \(\pi(\theta)\), gọi là &lt;strong&gt;phân phối dừng&lt;/strong&gt; (stationary distribution), thỏa mãn:&lt;/p&gt;

\[\pi(\theta&apos;) = \int p(\theta&apos; \mid \theta) \pi(\theta) \, d\theta.\]

&lt;p&gt;Theo &lt;strong&gt;Định lý Ergodic&lt;/strong&gt;, nếu chuỗi Markov đồng thời thỏa mãn ba điều kiện:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bất khả quy (Irreducible):&lt;/strong&gt; từ mọi vùng có xác suất dương đều có thể đi tới mọi vùng khác.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không tuần hoàn (Aperiodic):&lt;/strong&gt; chuỗi không bị mắc kẹt trong các chu kỳ lặp cố định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hồi quy dương (Positive recurrent):&lt;/strong&gt; thời gian trung bình để quay lại một vùng là hữu hạn.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;thì chuỗi có phân phối dừng duy nhất \(\pi(\theta)\), và phân phối của \(\theta^{(t)}\) hội tụ về \(\pi(\theta)\) bất kể điểm khởi tạo.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ý tưởng cốt lõi của MCMC:&lt;/strong&gt; Thiết kế quy tắc chuyển trạng thái của chuỗi Markov sao cho phân phối dừng \(\pi(\theta)\) chính là phân phối hậu nghiệm \(p(\theta \mid D)\). Khi đó, sau giai đoạn khởi động, các mẫu \(\theta^{(t)}\) thu được sẽ đại diện cho phân phối hậu nghiệm.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-thuật-toán-metropolishastings&quot;&gt;3. Thuật toán Metropolis–Hastings&lt;/h2&gt;

&lt;h3 id=&quot;31-cơ-chế-đề-xuất-và-chấp-nhận--bác-bỏ&quot;&gt;3.1. Cơ chế đề xuất và chấp nhận – bác bỏ&lt;/h3&gt;

&lt;p&gt;Giả sử chuỗi đang ở trạng thái \(\theta\). Mỗi bước của thuật toán Metropolis–Hastings gồm ba thao tác:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 1 – Đề xuất trạng thái mới \(\theta^*\)&lt;/strong&gt; từ một phân phối đề xuất \(q(\theta^* \mid \theta)\), phổ biến nhất là:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước đi ngẫu nhiên (Random walk):&lt;/strong&gt; \(\theta^* = \theta + \epsilon\), với \(\epsilon \sim \mathcal{N}(0, \sigma^2 I)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đề xuất độc lập (Independence proposal):&lt;/strong&gt; \(\theta^* \sim q(\theta^*)\) không phụ thuộc vào vị trí hiện tại.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Bước 2 – Tính xác suất chấp nhận:&lt;/strong&gt;&lt;/p&gt;

\[\alpha = \min\left(1, \frac{p(\theta^* \mid D) \cdot q(\theta \mid \theta^*)}{p(\theta \mid D) \cdot q(\theta^* \mid \theta)}\right).\]

&lt;p&gt;Điểm mấu chốt của công thức này là &lt;strong&gt;hằng số chuẩn hóa \(p(D)\) tự triệt tiêu&lt;/strong&gt; trong tỷ số:&lt;/p&gt;

\[\frac{p(\theta^* \mid D)}{p(\theta \mid D)} = \frac{p(D \mid \theta^*) \cdot p(\theta^*)}{p(D \mid \theta) \cdot p(\theta)}.\]

&lt;p&gt;Nhờ vậy, ta chỉ cần tính được tích của hàm hợp lý và phân phối tiên nghiệm (chưa chuẩn hóa).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 3 – Quyết định chuyển trạng thái:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Rút một số ngẫu nhiên \(u \sim \text{Uniform}(0, 1)\).&lt;/li&gt;
  &lt;li&gt;Nếu \(u \leq \alpha\): chấp nhận đề xuất và đặt \(\theta_{t+1} = \theta^*\).&lt;/li&gt;
  &lt;li&gt;Nếu \(u &amp;gt; \alpha\): bác bỏ đề xuất và giữ nguyên \(\theta_{t+1} = \theta_t\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;32-minh-họa-bằng-mã-python&quot;&gt;3.2. Minh họa bằng mã Python&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;metropolis_hastings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_log_pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;proposal_sd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    p_log_pdf: log posterior (unnormalized) - chỉ cần log p(D|θ) + log p(θ)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Bước 1: Đề xuất vị trí mới (random walk)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;theta_star&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;proposal_sd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Bước 2: Tính tỷ lệ chấp nhận (log scale cho an toàn)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;log_alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;p_log_pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_star&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;p_log_pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Bước 3: Quyết định
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_star&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Chấp nhận đi tiếp
&lt;/span&gt;            
        &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;33-vì-sao-thuật-toán-hội-tụ-về-đúng-phân-phối-hậu-nghiệm&quot;&gt;3.3. Vì sao thuật toán hội tụ về đúng phân phối hậu nghiệm?&lt;/h3&gt;

&lt;p&gt;Điều kiện đủ để \(p(\theta \mid D)\) là phân phối dừng của chuỗi là tính chất &lt;strong&gt;cân bằng chi tiết (Detailed Balance)&lt;/strong&gt;:&lt;/p&gt;

\[p(\theta \mid D) \cdot p(\theta&apos; \mid \theta) = p(\theta&apos; \mid D) \cdot p(\theta \mid \theta&apos;).\]

&lt;p&gt;Đẳng thức này phát biểu rằng dòng xác suất chuyển từ \(\theta\) sang \(\theta&apos;\) cân bằng đúng với dòng xác suất chuyển ngược từ \(\theta&apos;\) về \(\theta\).&lt;/p&gt;

&lt;p&gt;Xét hai trường hợp với xác suất chuyển \(p(\theta&apos; \mid \theta) = q(\theta&apos; \mid \theta) \cdot \alpha(\theta \to \theta&apos;)\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp 1:&lt;/strong&gt; \(\theta&apos; \neq \theta\) (có chuyển trạng thái). Đặt:&lt;/p&gt;

\[r = \frac{p(\theta&apos; \mid D) \cdot q(\theta \mid \theta&apos;)}{p(\theta \mid D) \cdot q(\theta&apos; \mid \theta)}, \qquad \alpha(\theta \to \theta&apos;) = \min(1, r).\]

&lt;ul&gt;
  &lt;li&gt;Nếu \(r \geq 1\) thì \(\alpha(\theta \to \theta&apos;) = 1\) và \(\alpha(\theta&apos; \to \theta) = 1/r\). Thay vào hai vế của đẳng thức cân bằng chi tiết, cả hai vế đều bằng \(p(\theta \mid D) \cdot q(\theta&apos; \mid \theta)\).&lt;/li&gt;
  &lt;li&gt;Nếu \(r &amp;lt; 1\) thì \(\alpha(\theta \to \theta&apos;) = r\) và \(\alpha(\theta&apos; \to \theta) = 1\). Cả hai vế khi đó đều bằng \(p(\theta&apos; \mid D) \cdot q(\theta \mid \theta&apos;)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp 2:&lt;/strong&gt; \(\theta&apos; = \theta\) (giữ nguyên trạng thái hiện tại, tương ứng với xác suất bác bỏ các đề xuất khác). Hai vế của đẳng thức cân bằng chi tiết hiển nhiên bằng nhau.&lt;/p&gt;

&lt;p&gt;Do điều kiện cân bằng chi tiết được thỏa mãn, \(p(\theta \mid D)\) là phân phối dừng của chuỗi; kết hợp với định lý Ergodic, chuỗi sẽ hội tụ về đúng phân phối hậu nghiệm \(p(\theta \mid D)\).&lt;/p&gt;

&lt;h3 id=&quot;34-điều-chỉnh-kích-thước-bước-nhảy&quot;&gt;3.4. Điều chỉnh kích thước bước nhảy&lt;/h3&gt;

&lt;p&gt;Khi phân phối đề xuất đối xứng (chẳng hạn phân phối Chuẩn tâm tại \(\theta\)), \(q(\theta \mid \theta^*) = q(\theta^* \mid \theta)\), nên xác suất chấp nhận rút gọn còn:&lt;/p&gt;

\[\alpha = \min\left(1, \frac{p(\theta^* \mid D)}{p(\theta \mid D)}\right).\]

&lt;p&gt;Hiệu quả lấy mẫu phụ thuộc đáng kể vào kích thước bước nhảy:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước nhảy quá nhỏ:&lt;/strong&gt; hầu hết đề xuất đều được chấp nhận (tỷ lệ chấp nhận khoảng 90%), nhưng chuỗi di chuyển rất chậm và có tự tương quan cao.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước nhảy quá lớn:&lt;/strong&gt; đề xuất thường rơi vào vùng mật độ thấp nên bị bác bỏ nhiều (tỷ lệ chấp nhận khoảng 5%), khiến chuỗi đứng yên tại chỗ lâu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vùng cân bằng:&lt;/strong&gt; tỷ lệ chấp nhận thường được khuyến nghị trong khoảng &lt;strong&gt;23–50%&lt;/strong&gt; tùy theo số chiều không gian tham số.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;thử-nghiệm-metropolis-từng-bước&quot;&gt;Thử nghiệm: Metropolis từng bước&lt;/h3&gt;

&lt;p&gt;Quan sát từng đề xuất được chấp nhận hay bác bỏ, biểu đồ tần suất tiến dần về phân phối đích, cùng trace plot và chỉ số R-hat của 4 chuỗi.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;mcmc-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;metropolis&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;giải-thích-chạy-tay-2-bước-metropolishastings-và-tự-tính-hatr&quot;&gt;Giải thích: Chạy tay 2 bước Metropolis–Hastings và tự tính \(\hat{R}\)&lt;/h3&gt;

&lt;p&gt;Để thấy MCMC hoàn toàn minh bạch chứ không phải hộp đen, hãy tự cầm bút chạy hai phép tính cốt lõi của bài học.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Chạy tay 2 bước Metropolis–Hastings.&lt;/strong&gt; Giả sử mật độ mục tiêu chưa chuẩn hóa là \(\tilde p(\theta) = \exp(-\theta^2/2)\) (chính là \(\mathcal{N}(0,1)\) bỏ qua hằng số \(1/\sqrt{2\pi}\)) và phân phối đề xuất đối xứng. Khởi tạo tại \(\theta^{(0)} = 2.0\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1:&lt;/strong&gt; Đề xuất \(\theta^* = 1.0\) (tiến gần đỉnh 0 hơn). Tính tỷ số mật độ:
\(r = \frac{\tilde p(1.0)}{\tilde p(2.0)} = \frac{e^{-0.5}}{e^{-2.0}} = e^{1.5} \approx 4.482.\)
Vì \(r &amp;gt; 1\), xác suất chấp nhận là \(\alpha = \min(1, 4.482) = 1\). Ta chắc chắn di chuyển: \(\theta^{(1)} = 1.0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2:&lt;/strong&gt; Từ \(\theta^{(1)} = 1.0\), đề xuất \(\theta^* = 2.0\) (đi xuống vùng mật độ thấp hơn). Tỷ số mật độ là:
\(r = \frac{\tilde p(2.0)}{\tilde p(1.0)} = e^{-1.5} \approx 0.223 \implies \alpha = 0.223.\)
Rút số ngẫu nhiên \(u \sim \text{Uniform}(0,1)\), giả sử được \(u = 0.40\). Vì \(u = 0.40 &amp;gt; 0.223\), ta &lt;strong&gt;bác bỏ&lt;/strong&gt; đề xuất và ghi nhận lại vị trí cũ: \(\theta^{(2)} = 1.0\). &lt;em&gt;(Nếu \(u = 0.15 \le 0.223\), ta vẫn chấp nhận bước đi xuống để chuỗi không bị kẹt cứng tại đỉnh — đây chính là khác biệt giữa lấy mẫu và tối ưu hóa!)&lt;/em&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Tự tính \(\hat{R}\) cho 2 chuỗi chưa hội tụ.&lt;/strong&gt; Giả sử có \(M = 2\) chuỗi, mỗi chuỗi \(S = 3\) mẫu: chuỗi 1 là \(\{0, 1, 2\}\) (\(\bar\theta_1 = 1, s_1^2 = 1\)) và chuỗi 2 là \(\{4, 5, 6\}\) (\(\bar\theta_2 = 5, s_2^2 = 1\)). Trung bình chung là \(\bar\theta_{..} = 3\). Khi đó:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Phương sai trong chuỗi: \(W = \frac{1 + 1}{2} = 1\).&lt;/li&gt;
  &lt;li&gt;Phương sai giữa hai chuỗi: \(B = 3 \cdot \frac{(1-3)^2 + (5-3)^2}{2-1} = 3 \cdot 8 = 24\).&lt;/li&gt;
  &lt;li&gt;Phương sai hậu nghiệm gộp: \(\hat\sigma^2 = \frac{2}{3}(1) + \frac{1}{3}(24) = 8.667\).&lt;/li&gt;
  &lt;li&gt;Chỉ số hội tụ: \(\hat{R} = \sqrt{\frac{8.667}{1}} \approx 2.94 \gg 1.05\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Con số \(2.94\) lập tức phát tín hiệu đỏ: hai chuỗi đang đứng ở hai “ngọn đồi” khác nhau và chưa hề hòa trộn.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-mcmc-metropolishastings-đề-xuất--chấp-nhậntừ-chối--hội-tụ&quot;&gt;Video ngắn: MCMC Metropolis–Hastings: Đề xuất — Chấp nhận/Từ chối &amp;amp; Hội tụ&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch04-02b-mcmc-acceptance-walk.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 23 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): theo dõi từng bước nhảy xanh/đỏ của chuỗi Markov trên phân phối hai đỉnh rồi chạy 300 bước hội tụ khít về hậu nghiệm mà không cần tính mẫu số p(D).&lt;/p&gt;

&lt;h2 id=&quot;4-lấy-mẫu-gibbs-gibbs-sampling&quot;&gt;4. Lấy mẫu Gibbs (Gibbs Sampling)&lt;/h2&gt;

&lt;h3 id=&quot;41-hạn-chế-của-metropolishastings-ở-số-chiều-cao&quot;&gt;4.1. Hạn chế của Metropolis–Hastings ở số chiều cao&lt;/h3&gt;

&lt;p&gt;Khi mô hình có nhiều tham số (chẳng hạn 100 tham số), thuật toán Metropolis–Hastings kiểu bước đi ngẫu nhiên gặp khó khăn lớn vì phải đề xuất đồng thời trên cả 100 chiều. Trong không gian chiều cao, xác suất để một bước nhảy ngẫu nhiên rơi vào vùng mật độ cao giảm nhanh theo hàm mũ (chẳng hạn ở mức minh họa cỡ \(0.5^{100}\), gần như bằng 0), khiến tỷ lệ chấp nhận rất thấp và chuỗi khám phá không gian chậm.&lt;/p&gt;

&lt;h3 id=&quot;42-ý-tưởng-cập-nhật-lần-lượt-từng-chiều&quot;&gt;4.2. Ý tưởng: cập nhật lần lượt từng chiều&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Lấy mẫu Gibbs&lt;/strong&gt; giải quyết vấn đề trên bằng cách cập nhật từng tham số (hoặc từng khối tham số) một lần dựa trên phân phối có điều kiện đầy đủ của nó. Với vector tham số \(\theta = (\theta_1, \theta_2, \ldots, \theta_K)\) và giá trị khởi tạo \(\theta^{(0)} = (\theta_1^{(0)}, \ldots, \theta_K^{(0)})\), tại mỗi vòng lặp \(t\) ta thực hiện:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Rút \(\theta_1^{(t+1)} \sim p(\theta_1 \mid \theta_2^{(t)}, \theta_3^{(t)}, \ldots, \theta_K^{(t)}, D)\) — giữ cố định các tham số còn lại và cập nhật \(\theta_1\).&lt;/li&gt;
  &lt;li&gt;Rút \(\theta_2^{(t+1)} \sim p(\theta_2 \mid \theta_1^{(t+1)}, \theta_3^{(t)}, \ldots, \theta_K^{(t)}, D)\) — dùng giá trị \(\theta_1^{(t+1)}\) vừa cập nhật để lấy mẫu \(\theta_2\).&lt;/li&gt;
  &lt;li&gt;Tiếp tục lần lượt cho đến \(\theta_K\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ minh họa:&lt;/strong&gt; Với mô hình hai tham số \(\theta = (\alpha, \beta)\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 – Lấy mẫu \(\alpha\) khi cố định \(\beta\):&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

\[p(\alpha \mid \beta, D) \propto p(D \mid \alpha, \beta) \cdot p(\alpha).\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 – Lấy mẫu \(\beta\) khi cố định \(\alpha\):&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

\[p(\beta \mid \alpha, D) \propto p(D \mid \alpha, \beta) \cdot p(\beta).\]

&lt;p&gt;Mỗi bước chỉ làm việc trên một chiều duy nhất nên đơn giản hơn nhiều so với cập nhật đồng thời.&lt;/p&gt;

&lt;h3 id=&quot;43-gibbs-là-trường-hợp-đặc-biệt-của-metropolishastings&quot;&gt;4.3. Gibbs là trường hợp đặc biệt của Metropolis–Hastings&lt;/h3&gt;

&lt;div class=&quot;textbook-theorem&quot;&gt;
  &lt;p&gt;&lt;strong&gt;Định lý:&lt;/strong&gt; Lấy mẫu Gibbs là một trường hợp đặc biệt của thuật toán Metropolis–Hastings với xác suất chấp nhận luôn bằng 1.&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;Khi chọn phân phối đề xuất cho tọa độ \(\theta_j\) chính là phân phối có điều kiện đầy đủ \(p(\theta_j \mid \theta_{-j}, D)\), tử số và mẫu số trong tỷ lệ Metropolis–Hastings triệt tiêu hoàn toàn, cho xác suất chấp nhận bằng 1.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt; mọi bước đề xuất đều được chấp nhận và không cần chỉnh kích thước bước nhảy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt; đòi hỏi phải biết dạng đóng (hoặc lấy mẫu trực tiếp được) của tất cả các phân phối có điều kiện đầy đủ, và di chuyển chậm khi các tham số có tương quan mạnh với nhau.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;thử-nghiệm-gibbs-trên-phân-phối-tương-quan&quot;&gt;Thử nghiệm: Gibbs trên phân phối tương quan&lt;/h3&gt;

&lt;p&gt;Mỗi bước chỉ thay đổi một tọa độ; khi tương quan giữa hai tham số cao, các bước di chuyển ngang/dọc bị rút ngắn đáng kể.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;mcmc-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;gibbs&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;5-hamiltonian-monte-carlo-hmc&quot;&gt;5. Hamiltonian Monte Carlo (HMC)&lt;/h2&gt;

&lt;h3 id=&quot;51-khi-phân-phối-có-điều-kiện-không-có-dạng-đóng&quot;&gt;5.1. Khi phân phối có điều kiện không có dạng đóng&lt;/h3&gt;

&lt;p&gt;Nếu mô hình không có cấu trúc liên hợp để áp dụng lấy mẫu Gibbs, ta cần một phương pháp vừa hoạt động tốt ở số chiều cao, vừa không dựa vào bước đi ngẫu nhiên kém hiệu quả. Đó là lý do &lt;strong&gt;Hamiltonian Monte Carlo (HMC)&lt;/strong&gt; ra đời.&lt;/p&gt;

&lt;h3 id=&quot;52-ý-tưởng-tận-dụng-đạo-hàm-gradient-và-động-lượng&quot;&gt;5.2. Ý tưởng: tận dụng đạo hàm (gradient) và động lượng&lt;/h3&gt;

&lt;p&gt;Thay vì bước đi ngẫu nhiên, HMC mô phỏng chuyển động của một hạt trượt trên bề mặt thế năng được xác định bởi phân phối hậu nghiệm. Đạo hàm (gradient) cho biết hướng dốc của bề mặt xác suất, còn động lượng (momentum) giúp quỹ đạo đi được quãng đường dài xuyên qua vùng mật độ cao thay vì quanh quẩn tại chỗ.&lt;/p&gt;

&lt;p&gt;Về mặt toán học, quy trình HMC gồm bốn bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Bổ sung biến phụ “động lượng” \(r\) tương ứng với mỗi tham số \(\theta\).&lt;/li&gt;
  &lt;li&gt;Định nghĩa hàm &lt;strong&gt;Hamiltonian&lt;/strong&gt;:&lt;/li&gt;
&lt;/ol&gt;

\[H(\theta, r) = -\log p(\theta \mid D) - \log p(r \mid \theta) = U(\theta) + K(r)\]

&lt;ul&gt;
  &lt;li&gt;\(U(\theta) = -\log p(\theta \mid D)\) là &lt;strong&gt;thế năng&lt;/strong&gt; (potential energy).&lt;/li&gt;
  &lt;li&gt;\(K(r) = \frac{1}{2}r^T M^{-1} r\) là &lt;strong&gt;động năng&lt;/strong&gt; (kinetic energy).
    &lt;ol&gt;
      &lt;li&gt;Mô phỏng phương trình động lực học Hamilton bằng phép tích phân số &lt;strong&gt;leapfrog integration&lt;/strong&gt; để đề xuất trạng thái mới \((\theta^*, r^*)\).&lt;/li&gt;
      &lt;li&gt;Thực hiện bước chấp nhận – bác bỏ Metropolis với xác suất:&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ul&gt;

\[\alpha = \min\left(1, e^{-H(\theta^*, r^*) + H(\theta, r)}\right).\]

&lt;h3 id=&quot;53-ưu-điểm-và-thuật-toán-nuts&quot;&gt;5.3. Ưu điểm và thuật toán NUTS&lt;/h3&gt;

&lt;p&gt;Nhờ khai thác thông tin đạo hàm và động lượng, HMC có ba ưu điểm nổi bật: tạo ra bước di chuyển xa (giảm mạnh tự tương quan), duy trì tỷ lệ chấp nhận cao và hoạt động hiệu quả trong không gian nhiều chiều.&lt;/p&gt;

&lt;p&gt;Trong thực hành, biến thể &lt;strong&gt;NUTS (No-U-Turn Sampler)&lt;/strong&gt; tự động chọn số bước leapfrog phù hợp bằng cách dừng quỹ đạo ngay khi nó bắt đầu quay ngược lại (U-turn). Đây là bộ lấy mẫu mặc định của PyMC.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;thử-nghiệm-quỹ-đạo-leapfrog-của-hmc&quot;&gt;Thử nghiệm: quỹ đạo leapfrog của HMC&lt;/h3&gt;

&lt;p&gt;Điều chỉnh kích thước bước \(\epsilon\) và số bước \(L\): quỹ đạo có thể đi xa và vẫn được chấp nhận cao khi năng lượng được bảo toàn tốt.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;mcmc-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;hmc&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;6-chẩn-đoán-hội-tụ-hatr-r-hat-và-ess&quot;&gt;6. Chẩn đoán hội tụ: \(\hat{R}\) (R-hat) và ESS&lt;/h2&gt;

&lt;h3 id=&quot;61-chỉ-số-hatr-các-chuỗi-độc-lập-có-hội-tụ-về-cùng-một-phân-phối&quot;&gt;6.1. Chỉ số \(\hat{R}\): các chuỗi độc lập có hội tụ về cùng một phân phối?&lt;/h3&gt;

&lt;p&gt;Để kiểm tra chuỗi đã hội tụ hay chưa, ta chạy đồng thời &lt;strong&gt;nhiều chuỗi độc lập&lt;/strong&gt; xuất phát từ các vị trí khởi tạo khác nhau. Nếu tất cả các chuỗi cùng hội tụ về phân phối dừng, phương sai giữa các chuỗi sẽ tương đương với phương sai bên trong từng chuỗi.&lt;/p&gt;

&lt;p&gt;Với \(M\) chuỗi, mỗi chuỗi gồm \(S\) mẫu sau giai đoạn khởi động, các đại lượng được định nghĩa như sau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phương sai trong từng chuỗi (Within-chain variance):&lt;/strong&gt; \(W = \frac{1}{M} \sum_{m=1}^{M} \frac{1}{S-1} \sum_{s=1}^{S} (\theta_{m,s} - \bar{\theta}_m)^2\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương sai giữa các chuỗi (Between-chain variance):&lt;/strong&gt; \(B = \frac{S}{M-1} \sum_{m=1}^{M} (\bar{\theta}_m - \bar{\theta}_{..})^2\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương sai hậu nghiệm ước lượng:&lt;/strong&gt; \(\hat{\sigma}^2 = \frac{S-1}{S}W + \frac{1}{S}B\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chỉ số R-hat:&lt;/strong&gt; \(\hat{R} = \sqrt{\frac{\hat{\sigma}^2}{W}}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Cách diễn giải:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\hat{R} \approx 1\): các chuỗi đã trộn lẫn tốt và cùng khám phá một phân phối.&lt;/li&gt;
  &lt;li&gt;\(\hat{R} &amp;gt; 1.1\): dấu hiệu cảnh báo rõ ràng rằng các chuỗi chưa hội tụ và vẫn đang nằm ở những vùng khác nhau của không gian tham số.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;62-số-mẫu-hiệu-dụng-ess--effective-sample-size&quot;&gt;6.2. Số mẫu hiệu dụng (ESS – Effective Sample Size)&lt;/h3&gt;

&lt;p&gt;Các mẫu sinh ra từ MCMC có &lt;strong&gt;tự tương quan&lt;/strong&gt; (autocorrelation) vì trạng thái sau phụ thuộc vào trạng thái trước. Do đó, một chuỗi gồm 2000 mẫu MCMC không chứa lượng thông tin tương đương 2000 mẫu độc lập cùng phân phối (i.i.d.).&lt;/p&gt;

&lt;p&gt;Chỉ số &lt;strong&gt;ESS&lt;/strong&gt; ước lượng số lượng mẫu độc lập tương đương với chuỗi MCMC hiện có:&lt;/p&gt;

\[\text{ESS} = \frac{S}{1 + 2\sum_{k=1}^{\infty} \rho(k)}\]

&lt;p&gt;trong đó \(\rho(k)\) là hệ số tự tương quan tại độ trễ \(k\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ngưỡng tham khảo thực hành:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\text{ESS} &amp;gt; 400\): đủ tin cậy để ước lượng trung bình hậu nghiệm.&lt;/li&gt;
  &lt;li&gt;\(\text{ESS} &amp;gt; 1000\): phù hợp khi cần ước lượng chính xác các phân vị ở vùng đuôi.&lt;/li&gt;
  &lt;li&gt;\(\text{ESS} &amp;lt; 100\): cảnh báo tự tương quan quá cao, cần chạy dài hơn hoặc kiểm tra lại tham số hóa mô hình.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;63-kiểm-tra-thực-hành-với-arviz&quot;&gt;6.3. Kiểm tra thực hành với ArviZ&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;from_pymc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta_0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta_1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;mean&lt;/th&gt;
      &lt;th&gt;sd&lt;/th&gt;
      &lt;th&gt;hdi_3%&lt;/th&gt;
      &lt;th&gt;hdi_97%&lt;/th&gt;
      &lt;th&gt;r_hat&lt;/th&gt;
      &lt;th&gt;ess&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;beta_0&lt;/td&gt;
      &lt;td&gt;6.52&lt;/td&gt;
      &lt;td&gt;0.31&lt;/td&gt;
      &lt;td&gt;5.91&lt;/td&gt;
      &lt;td&gt;7.13&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1.00&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1203&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;beta_1&lt;/td&gt;
      &lt;td&gt;0.78&lt;/td&gt;
      &lt;td&gt;0.09&lt;/td&gt;
      &lt;td&gt;0.61&lt;/td&gt;
      &lt;td&gt;0.96&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1.01&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;987&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;sigma&lt;/td&gt;
      &lt;td&gt;2.41&lt;/td&gt;
      &lt;td&gt;0.24&lt;/td&gt;
      &lt;td&gt;1.98&lt;/td&gt;
      &lt;td&gt;2.87&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1.00&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;856&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Tiêu chuẩn kiểm tra nhanh:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\hat{R} &amp;lt; 1.05\) (càng sát 1 càng tốt; trong thực hành chặt chẽ thường kỳ vọng \(\hat{R} \le 1.01\)).&lt;/li&gt;
  &lt;li&gt;\(\text{ESS} &amp;gt; 400\) cho ước lượng trung bình.&lt;/li&gt;
  &lt;li&gt;\(\text{ESS} &amp;gt; 200\) tối thiểu cho các xác suất vùng đuôi.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-so-sánh-các-thuật-toán-mcmc-phổ-biến&quot;&gt;7. So sánh các thuật toán MCMC phổ biến&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Thuật toán&lt;/th&gt;
      &lt;th&gt;Ưu điểm&lt;/th&gt;
      &lt;th&gt;Nhược điểm&lt;/th&gt;
      &lt;th&gt;Bối cảnh phù hợp&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Metropolis–Hastings&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Đơn giản, áp dụng linh hoạt&lt;/td&gt;
      &lt;td&gt;Bước đi ngẫu nhiên chậm, tỷ lệ chấp nhận thấp ở số chiều cao&lt;/td&gt;
      &lt;td&gt;Mô hình ít tham số hoặc không tính được đạo hàm&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Gibbs Sampling&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Tỷ lệ chấp nhận 100%, không cần chỉnh bước nhảy&lt;/td&gt;
      &lt;td&gt;Cần biết phân phối có điều kiện đầy đủ; chậm khi tương quan cao&lt;/td&gt;
      &lt;td&gt;Mô hình có cấu trúc liên hợp&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Hamiltonian MC&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Khám phá không gian hiệu quả, bước nhảy dài&lt;/td&gt;
      &lt;td&gt;Đòi hỏi tính đạo hàm và chọn tham số leapfrog&lt;/td&gt;
      &lt;td&gt;Mô hình liên tục nhiều chiều&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;NUTS&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Tự động điều chỉnh độ dài quỹ đạo leapfrog&lt;/td&gt;
      &lt;td&gt;Tốn chi phí tính toán ở giai đoạn khởi động (tuning)&lt;/td&gt;
      &lt;td&gt;Mặc định cho hầu hết mô hình trong PyMC&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-tổng-kết-bài-học&quot;&gt;8. Tổng kết bài học&lt;/h2&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ:&lt;/strong&gt;&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;Metropolis–Hastings&lt;/strong&gt; hội tụ về phân phối hậu nghiệm vì thỏa mãn điều kiện cân bằng chi tiết với phân phối dừng là \(p(\theta \mid D)\).&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Gibbs sampling&lt;/strong&gt; là trường hợp đặc biệt của Metropolis–Hastings có xác suất chấp nhận bằng 1 khi biết các phân phối có điều kiện đầy đủ.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;HMC/NUTS&lt;/strong&gt; đạt hiệu quả cao trong không gian nhiều chiều nhờ kết hợp đạo hàm và động lượng.&lt;/li&gt;
  &lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;MCMC không phải là “hộp đen” thần bí, mà là ứng dụng trực tiếp của lý thuyết chuỗi Markov và phương pháp Monte Carlo. Hiểu rõ cơ chế hoạt động giúp bạn đọc đúng các chỉ số chẩn đoán \(\hat{R}\) và ESS, chọn thuật toán phù hợp và chẩn đoán nguyên nhân khi bộ lấy mẫu gặp sự cố.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yApmR-c_hKU&quot;&gt;Markov Chain Monte Carlo (MCMC) : Data Science Concepts&lt;/a&gt; — ritvikmath, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Giới thiệu MCMC như giải pháp lấy mẫu khi tích phân chuẩn hóa không tính được giải tích, khớp với phần mở đầu của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yCv2N7wGDCw&quot;&gt;Metropolis - Hastings : Data Science Concepts&lt;/a&gt; — ritvikmath, English. Giải thích bước đề xuất và quy tắc chấp nhận – bác bỏ của Metropolis–Hastings, hỗ trợ mục 3.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=a-wydhEuAm0&quot;&gt;The intuition behind the Hamiltonian Monte Carlo algorithm&lt;/a&gt; — Ben Lambert, English. Minh họa trực giác về cách HMC dùng đạo hàm để di chuyển theo hình dạng phân phối hậu nghiệm, bổ trợ cho mục 5.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao tỷ lệ chấp nhận của Metropolis–Hastings với phân phối đề xuất đối xứng không cần tính mẫu số \(p(D)\)?&lt;/li&gt;
  &lt;li&gt;Hãy chứng minh lấy mẫu Gibbs là trường hợp đặc biệt của Metropolis–Hastings với xác suất chấp nhận bằng 1.&lt;/li&gt;
  &lt;li&gt;Với một mô hình đơn giản, hãy giải thích vì sao \(\hat{R} &amp;gt; 1.1\) cho thấy các chuỗi chưa hội tụ.&lt;/li&gt;
  &lt;li&gt;So sánh chỉ số ESS giữa chuỗi bước đi ngẫu nhiên (Metropolis–Hastings) và chuỗi dùng tích phân leapfrog (HMC). Nguyên nhân nào tạo ra sự khác biệt đó?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., Carlin, J., Stern, H., Dunson, D., Vehtari, A., &amp;amp; Rubin, D. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 11.&lt;/li&gt;
  &lt;li&gt;Robert, C., &amp;amp; Casella, G. (2004). &lt;em&gt;Monte Carlo Statistical Methods&lt;/em&gt;, Chapter 7.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 8.&lt;/li&gt;
  &lt;li&gt;Hoff, P. (2009). &lt;em&gt;A First Course in Bayesian Statistical Methods&lt;/em&gt;, Chapter 6.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter04/04_03_posterior_inference_pymc/&quot;&gt;4.3 Posterior Inference với PyMC&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 4.2: Priors for Regression - Chọn Prior có Nguyên tắc</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_02_priors_for_regression/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_02_priors_for_regression</id>
   <content type="html">&lt;p&gt;Hãy tưởng tượng hai nhà nghiên cứu cùng phân tích một tập dữ liệu chiều cao và cân nặng, và cả hai đều viết vào mô hình một dòng tưởng chừng vô hại: \(\beta \sim \mathcal{N}(0, 1)\). Người thứ nhất đo chiều cao bằng centimet, người thứ hai đo bằng mét. Khi mô phỏng thử dữ liệu từ mô hình trước khi nhìn vào dữ liệu thật, người thứ nhất tạo ra những con người cao 1m70 nhưng nặng từ âm 30 kg đến dương 180 kg, còn người thứ hai lại ép cân nặng hầu như không đổi theo chiều cao. Cùng một công thức tiên nghiệm, nhưng đổi thang đo đã biến nó thành hai giả định vật lý hoàn toàn khác nhau — đó là lý do chọn phân phối tiên nghiệm cho hồi quy phải có nguyên tắc rõ ràng.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ biết cách lựa chọn phân phối tiên nghiệm (prior) cho mô hình hồi quy một cách có nguyên tắc. Bạn cũng sẽ hiểu vì sao chuẩn hóa dữ liệu (standardization) là bước nền quan trọng, vì sao phân phối tiên nghiệm thông tin yếu (weakly informative prior) thường là điểm khởi đầu phù hợp, và vì sao kiểm tra dự báo tiên nghiệm (prior predictive check) cần được thực hiện trước khi khớp mô hình.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ ngắn.&lt;/strong&gt; Nếu đặt phân phối tiên nghiệm cho hệ số dốc quá rộng, mô hình có thể ngầm chấp nhận những đường hồi quy hoàn toàn phi thực tế theo kiến thức chuyên môn. Chọn phân phối tiên nghiệm cho hồi quy không phải là thao tác hình thức, mà là cách đặt ra biên giới hợp lý cho mô hình ngay từ đầu.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Vì sao cùng một phân phối tiên nghiệm có thể hợp lý ở thang đo này nhưng lại bất hợp lý ở thang đo khác?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bất-biến-thang-đo-điều-chuẩn-hình-học-và-dự-báo-tiên-nghiệm&quot;&gt;Kiến thức cần nhớ: Bất biến thang đo, Điều chuẩn hình học và Dự báo tiên nghiệm&lt;/h2&gt;

&lt;p&gt;Để không còn cảm giác “chọn prior là đoán mò”, hãy đặt bài toán này trên ba trụ cột toán học quen thuộc từ bậc đại học:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa tuyến tính (\(z\)-score) và bất biến đơn vị:&lt;/strong&gt; Phép biến đổi \(x_{\text{std}} = (x - \bar x)/\mathrm{SD}(x)\) đưa mọi biến về không thứ nguyên với trung bình 0 và phương sai 1. Trong hồi quy chuẩn hóa, hệ số dốc \(\beta\) có cùng thang đo với hệ số tương quan: \(\lvert \beta \rvert\) hiếm khi vượt quá 1 hoặc 2 trong các hệ thực, giúp ta đặt tiên nghiệm nhất quán bất kể đơn vị đo ban đầu là mét, inch hay triệu đồng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối tiên nghiệm thông tin yếu (Weakly Informative Prior) và điều chuẩn:&lt;/strong&gt; Trong giải tích lồi, thêm thành phần phạt \(\lambda \beta^2\) (hồi quy Ridge) tương đương trực tiếp với đặt tiên nghiệm Gaussian \(\beta \sim \mathcal{N}(0, \tau^2)\) với \(\lambda = \sigma^2 / \tau^2\). Tiên nghiệm thông tin yếu không áp đặt kết luận thay dữ liệu, mà dựng một “hàng rào mềm” loại bỏ các vùng tham số phi vật lý và làm mượt hình học mặt hậu nghiệm cho MCMC.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phép chiếu sang không gian dữ liệu (Prior Predictive Distribution):&lt;/strong&gt; Tham số \((\alpha, \beta, \sigma)\) sống trong không gian trừu tượng khó hình dung, còn dữ liệu \(y\) sống trong thế giới thực có đơn vị và giới hạn rõ ràng. Kiểm tra dự báo tiên nghiệm lấy tích phân \(p(y) = \int p(y \mid \theta) p(\theta)\,d\theta\) để dịch niềm tin trên tham số thành các đường hồi quy quan sát được.
    &lt;h2 id=&quot;1-khó-khăn-khi-chọn-phân-phối-tiên-nghiệm-cho-hồi-quy&quot;&gt;1. Khó khăn khi chọn phân phối tiên nghiệm cho hồi quy&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trong hồi quy tuyến tính cơ bản, ta có ít nhất ba tham số cần đặt phân phối tiên nghiệm: hệ số chặn \(\alpha\), hệ số dốc \(\beta\) và độ nhiễu \(\sigma\). Nếu chọn thiếu cân nhắc, phân phối tiên nghiệm có thể quá rộng và cho phép những giá trị vô lý, quá hẹp và làm sai lệch phân phối hậu nghiệm, hoặc khiến bộ lấy mẫu (sampler) hoạt động kém ổn định. Do đó, chọn phân phối tiên nghiệm vừa đòi hỏi hiểu biết thống kê, vừa đòi hỏi nắm vững thang đo và bối cảnh thực tế của dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;2-chuẩn-hóa-dữ-liệu-bước-nên-thực-hiện-trước-khi-đặt-tiên-nghiệm&quot;&gt;2. Chuẩn hóa dữ liệu: bước nên thực hiện trước khi đặt tiên nghiệm&lt;/h2&gt;

&lt;p&gt;Một trong những cách đơn giản và hiệu quả nhất để việc chọn phân phối tiên nghiệm trở nên nhất quán hơn là chuẩn hóa (standardize) các biến đầu vào và đầu ra:&lt;/p&gt;

\[x_{std} = \frac{x-\bar{x}}{\mathrm{SD}(x)}, \qquad
y_{std} = \frac{y-\bar{y}}{\mathrm{SD}(y)}.\]

&lt;p&gt;Sau phép biến đổi này, các biến đều có trung bình bằng 0 và độ lệch chuẩn bằng 1, giúp việc chọn phân phối tiên nghiệm theo thang đo chuẩn trở nên trực quan hơn nhiều.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_standardization_raw_data.png&quot; alt=&quot;Dữ liệu ở thang đo gốc trước khi standardize&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_standardization_standardized_data.png&quot; alt=&quot;Dữ liệu sau khi standardize về mean 0 và SD 1&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;ba-lợi-ích-chính-của-chuẩn-hóa-dữ-liệu&quot;&gt;Ba lợi ích chính của chuẩn hóa dữ liệu&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hệ số chặn dễ diễn giải hơn.&lt;/strong&gt; Sau khi dịch tâm hoặc chuẩn hóa, hệ số chặn tương ứng với giá trị kỳ vọng của \(y\) tại mức trung bình của \(x\), thay vì tại mốc \(x = 0\) vốn có thể vô nghĩa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối tiên nghiệm ít phụ thuộc vào đơn vị đo.&lt;/strong&gt; Cùng một công thức tiên nghiệm có thể mang ý nghĩa rất khác nhau nếu đổi đơn vị từ cm sang m hoặc từ kg sang pound. Chuẩn hóa loại bỏ sự lệ thuộc này.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bộ lấy mẫu hội tụ ổn định hơn.&lt;/strong&gt; Khi các biến nằm trên cùng một thang đo, hình dạng phân phối hậu nghiệm thường cân đối hơn, giúp các thuật toán lấy mẫu như HMC/NUTS hoạt động hiệu quả hơn.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;21-ví-dụ-minh-họa-cùng-một-tiên-nghiệm-trước-và-sau-khi-chuẩn-hóa&quot;&gt;2.1. Ví dụ minh họa: cùng một tiên nghiệm trước và sau khi chuẩn hóa&lt;/h3&gt;

&lt;p&gt;Giả sử \(x\) là chiều cao tính bằng cm (chủ yếu trong khoảng 150–190 cm) và \(y\) là cân nặng tính bằng kg (khoảng 45–90 kg). Nếu chưa chuẩn hóa mà đặt trực tiếp:&lt;/p&gt;

\[\alpha \sim \mathcal{N}(0,1), \qquad \beta \sim \mathcal{N}(0,1),\]

&lt;p&gt;thì hai phân phối này tuy gọn về mặt ký hiệu nhưng bất hợp lý về mặt ngữ nghĩa:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Tiên nghiệm \(\alpha \sim \mathcal{N}(0,1)\) ngầm cho rằng khi \(x = 0\) cm, cân nặng trung bình nằm quanh 0 kg — một phát biểu không có ý nghĩa thực tế.&lt;/li&gt;
  &lt;li&gt;Tiên nghiệm \(\beta \sim \mathcal{N}(0,1)\) có khoảng 95% xấp xỉ \([-2, 2]\) kg/cm. Nghĩa là chỉ cần chênh lệch 20 cm chiều cao, mô hình đã cho phép mức chênh cân nặng trung bình từ \(-40\) đến \(40\) kg, quá rộng so với thực tế.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ngược lại, sau khi chuẩn hóa \(x\) và \(y\) thành \(x_{std}\) và \(y_{std}\), cùng cặp phân phối tiên nghiệm:&lt;/p&gt;

\[\alpha \sim \mathcal{N}(0,1), \qquad \beta \sim \mathcal{N}(0,1)\]

&lt;p&gt;lại mang ý nghĩa rõ ràng và hợp lý hơn nhiều:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\alpha\) quanh 0 có nghĩa là tại mức chiều cao trung bình, cân nặng kỳ vọng cũng nằm quanh mức trung bình của tập dữ liệu.&lt;/li&gt;
  &lt;li&gt;\(\beta\) quanh 0 với độ lệch chuẩn 1 có nghĩa là khi \(x\) tăng thêm 1 độ lệch chuẩn, \(y\) thường thay đổi trong phạm vi vài độ lệch chuẩn — đủ linh hoạt cho dữ liệu nhưng loại bỏ được các giá trị cực đoan.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Như vậy, chuẩn hóa không chỉ là kỹ thuật tính toán mà còn giúp ta diễn giải phân phối tiên nghiệm một cách trực quan.&lt;/p&gt;

&lt;h2 id=&quot;3-phân-phối-tiên-nghiệm-cho-hệ-số-chặn-alpha&quot;&gt;3. Phân phối tiên nghiệm cho hệ số chặn \(\alpha\)&lt;/h2&gt;

&lt;p&gt;Sau khi chuẩn hóa dữ liệu, hệ số chặn thường nằm gần 0 với mức độ bất định vừa phải. Vì vậy, những lựa chọn như:&lt;/p&gt;

\[\alpha \sim \mathcal{N}(0,1)\]

&lt;p&gt;hoặc&lt;/p&gt;

\[\alpha \sim \mathcal{N}(0,2)\]

&lt;p&gt;thường là điểm khởi đầu phù hợp. Ba biểu đồ dưới đây minh họa sự khác biệt giữa phân phối tiên nghiệm quá rộng, thông tin yếu (vừa phải) và quá hẹp cho hệ số chặn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_intercept_too_wide.png&quot; alt=&quot;Prior quá rộng cho intercept&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_intercept_weakly_informative.png&quot; alt=&quot;Prior weakly informative cho intercept&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_intercept_too_narrow.png&quot; alt=&quot;Prior quá hẹp cho intercept&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Nguyên tắc chung ở đây khá rõ: tiên nghiệm quá rộng cho phép các giá trị thiếu thực tế, tiên nghiệm quá hẹp áp đặt ràng buộc quá mạnh lên ước lượng, còn tiên nghiệm vừa phải vừa có tác dụng điều chuẩn (regularization) vừa để dữ liệu đóng vai trò chính.&lt;/p&gt;

&lt;h2 id=&quot;4-phân-phối-tiên-nghiệm-cho-hệ-số-dốc-beta&quot;&gt;4. Phân phối tiên nghiệm cho hệ số dốc \(\beta\)&lt;/h2&gt;

&lt;p&gt;Trên thang đo chuẩn hóa, hệ số dốc \(\beta\) biểu thị mức thay đổi trung bình của \(y\) (tính theo độ lệch chuẩn) khi \(x\) tăng thêm 1 độ lệch chuẩn. Khi chưa có thông tin chuyên sâu về độ lớn của tác động, một phân phối tiên nghiệm thông tin yếu như:&lt;/p&gt;

\[\beta \sim \mathcal{N}(0,1)\]

&lt;p&gt;thường là lựa chọn hợp lý. Phân phối này cho phép cả mối quan hệ dương lẫn âm, đồng thời hạn chế các hệ số dốc quá cực đoan. Ba hình dưới đây so sánh trực quan ba mức độ rộng khác nhau của tiên nghiệm cho hệ số dốc.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_slope_too_wide.png&quot; alt=&quot;Prior quá rộng cho slope&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_slope_weakly_informative.png&quot; alt=&quot;Prior weakly informative cho slope&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_slope_too_narrow.png&quot; alt=&quot;Prior quá hẹp cho slope&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;5-phân-phối-tiên-nghiệm-cho-độ-nhiễu-sigma&quot;&gt;5. Phân phối tiên nghiệm cho độ nhiễu \(\sigma\)&lt;/h2&gt;

&lt;p&gt;Do \(\sigma &amp;gt; 0\), ta cần chọn các phân phối chỉ nhận giá trị dương như HalfNormal, Exponential hoặc HalfStudentT. Sau khi chuẩn hóa dữ liệu, một lựa chọn phổ biến là:&lt;/p&gt;

\[\sigma \sim \mathrm{HalfNormal}(1).\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_noise_halfnormal_curve.png&quot; alt=&quot;Đường prior HalfNormal cho noise sigma&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Lựa chọn này phản ánh kỳ vọng rằng độ nhiễu nằm ở mức vừa phải trên thang chuẩn hóa, đồng thời vẫn đủ mở để mô hình thích ứng nếu dữ liệu thực tế có độ phân tán lớn hơn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_noise_halfnormal_summary.png&quot; alt=&quot;Tóm tắt cách đọc prior cho noise sigma&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-phân-phối-tiên-nghiệm-thông-tin-yếu-là-gì-và-vì-sao-nên-bắt-đầu-từ-đó&quot;&gt;6. Phân phối tiên nghiệm thông tin yếu là gì và vì sao nên bắt đầu từ đó?&lt;/h2&gt;

&lt;p&gt;Phân phối tiên nghiệm thông tin yếu (weakly informative prior) không mang nghĩa “hoàn toàn không có thông tin”. Ngược lại, nó thể hiện mục tiêu không áp đặt niềm tin quá chặt lên mô hình, nhưng vẫn loại bỏ được những vùng tham số phi lý mà kiến thức chuyên môn có thể bác bỏ ngay từ đầu. Trong hồi quy, loại tiên nghiệm này giúp điều chuẩn mô hình, ổn định phân phối hậu nghiệm và giảm nguy cơ bộ lấy mẫu đi vào những vùng tham số không có ý nghĩa.&lt;/p&gt;

&lt;h2 id=&quot;7-kiểm-tra-dự-báo-tiên-nghiệm-prior-predictive-check&quot;&gt;7. Kiểm tra dự báo tiên nghiệm (prior predictive check)&lt;/h2&gt;

&lt;p&gt;Nếu chỉ quan sát biểu đồ mật độ trên không gian tham số, đôi khi rất khó đánh giá một phân phối tiên nghiệm có hợp lý hay không. Cách kiểm tra hiệu quả hơn là dùng chính các phân phối tiên nghiệm đó để mô phỏng dữ liệu giả lập: rút nhiều mẫu \((\alpha, \beta, \sigma)\) từ tiên nghiệm, vẽ các đường hồi quy tương ứng và xem liệu dữ liệu được sinh ra có phù hợp với thực tế hay không.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_predictive_weakly_informative.png&quot; alt=&quot;Prior predictive với slope weakly informative&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Nếu phân phối tiên nghiệm sinh ra các đường hồi quy có độ dốc cực đoan hoặc tạo ra những dự đoán vô lý như cân nặng âm, điểm thi 300 điểm hay doanh thu tăng giảm phi thực tế, thì phân phối tiên nghiệm cần được điều chỉnh lại — dù về mặt toán học nó hoàn toàn hợp lệ.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_predictive_too_wide.png&quot; alt=&quot;Prior predictive với slope quá rộng&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;giải-thích-tự-tính-khoảng-dự-báo-tiên-nghiệm-bằng-tay-trước-khi-chạy-mô-hình&quot;&gt;Giải thích: Tự tính khoảng dự báo tiên nghiệm bằng tay trước khi chạy mô hình&lt;/h3&gt;

&lt;p&gt;Trước khi cần đến máy tính mô phỏng hàng nghìn đường thẳng, bạn có thể kiểm tra nhanh một lựa chọn phân phối tiên nghiệm chỉ bằng phép cộng phương sai.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Thiết lập mô hình chuẩn hóa:&lt;/strong&gt; Xét \(y_z \sim \mathcal{N}(\mu, \sigma^2)\) với \(\mu = \alpha + \beta x_z\), trong đó \(\alpha \sim \mathcal{N}(0, 1^2)\) và \(\beta \sim \mathcal{N}(0, \sigma_\beta^2)\) độc lập nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính phương sai tiên nghiệm của đường trung bình \(\mu\) tại \(x_z = 2\)&lt;/strong&gt; (tức một quan sát cao hơn trung bình 2 độ lệch chuẩn):
\(\operatorname{Var}(\mu) = \operatorname{Var}(\alpha) + 2^2 \operatorname{Var}(\beta) = 1 + 4\sigma_\beta^2.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh hai lựa chọn tiên nghiệm cho \(\beta\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Lựa chọn A (prior “phẳng” \(\sigma_\beta = 10\)):&lt;/strong&gt; \(\operatorname{Var}(\mu) = 1 + 4(100) = 401 \implies \mathrm{SD}(\mu) \approx 20.02\). Khoảng 95% tiên nghiệm của \(\mu\) tại \(x_z = 2\) rộng tới \([-39.2,\ +39.2]\) độ lệch chuẩn! Nếu \(y\) là cân nặng có \(\bar y = 65\) kg và \(\mathrm{SD}(y) = 10\) kg, mô hình trước khi thấy dữ liệu đã gán xác suất đáng kể cho những người cao 1m85 nhưng nặng &lt;strong&gt;âm 320 kg&lt;/strong&gt; hoặc &lt;strong&gt;dương 450 kg&lt;/strong&gt;.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Lựa chọn B (weakly informative \(\sigma_\beta = 0.5\)):&lt;/strong&gt; \(\operatorname{Var}(\mu) = 1 + 4(0.25) = 2 \implies \mathrm{SD}(\mu) = \sqrt{2} \approx 1.414\). Khoảng 95% tiên nghiệm của \(\mu\) tại \(x_z = 2\) là \([-2.77,\ +2.77]\) độ lệch chuẩn — tức quanh \(37\)–\(93\) kg, vừa đủ rộng để dữ liệu quyết định xu hướng, vừa loại trừ các kịch bản vô lý.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài học cốt lõi:&lt;/strong&gt; Một phân phối tiên nghiệm “phẳng” trên không gian tham số thường biến thành một phân phối cực kỳ &lt;strong&gt;điên rồ&lt;/strong&gt; trên không gian dự đoán. Luôn kiểm tra bằng phép tính nhẩm phương sai hoặc mô phỏng prior predictive trước khi bấm chạy MCMC.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;video-ngắn-chọn-prior-cho-hồi-quy-prior-quá-rộng-vs-chuẩn-hóa-dữ-liệu&quot;&gt;Video ngắn: Chọn Prior cho Hồi quy: Prior Quá rộng vs Chuẩn hóa Dữ liệu&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch04-02a-priors-ppc-lines.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 19 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): mô phỏng 24 đường Prior Predictive cho thấy Prior phẳng Normal(0, 100) vẽ đường dốc đứng phi lý, còn chuẩn hóa Z-score + Prior yếu nằm gọn trong vùng dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;8-ví-dụ-trực-quan-chi-phí-quảng-cáo-và-doanh-thu&quot;&gt;8. Ví dụ trực quan: chi phí quảng cáo và doanh thu&lt;/h2&gt;

&lt;p&gt;Giả sử \(x\) là chi phí quảng cáo và \(y\) là doanh thu. Nếu phân phối tiên nghiệm của hệ số dốc quá rộng, mô hình sẽ ngầm cho phép kịch bản tăng rất ít ngân sách nhưng doanh thu tăng đột biến phi thực tế, hoặc ngược lại, tăng nhẹ ngân sách nhưng doanh thu sụt giảm nghiêm trọng. Trước khi nhìn vào dữ liệu, kiến thức thực tế đã cho thấy những kịch bản đó không hợp lý, và phân phối tiên nghiệm cần phản ánh điều này.&lt;/p&gt;

&lt;h3 id=&quot;81-đọc-kết-quả-kiểm-tra-dự-báo-tiên-nghiệm-bằng-con-số&quot;&gt;8.1. Đọc kết quả kiểm tra dự báo tiên nghiệm bằng con số&lt;/h3&gt;

&lt;p&gt;Giả sử dữ liệu quảng cáo và doanh thu đã được chuẩn hóa, và bạn đang cân nhắc giữa hai phân phối tiên nghiệm cho hệ số dốc:&lt;/p&gt;

\[\beta \sim \mathcal{N}(0,3)\]

&lt;p&gt;hoặc&lt;/p&gt;

\[\beta \sim \mathcal{N}(0,0.5).\]

&lt;p&gt;Với lựa chọn thứ nhất, khoảng 95% của \(\beta\) xấp xỉ \([-6, 6]\). Khi một chiến dịch có chi phí ở mức \(x_{std} = 2\) (cao hơn trung bình 2 độ lệch chuẩn), chỉ riêng giá trị trung bình dự đoán:&lt;/p&gt;

\[\mu = \alpha + \beta x_{std}\]

&lt;p&gt;đã có thể dao động quanh khoảng \(-12\) đến \(12\) độ lệch chuẩn của \(y\), chưa kể phần nhiễu. Trong hầu hết bối cảnh kinh doanh, biên độ này rộng một cách phi thực tế.&lt;/p&gt;

&lt;p&gt;Ngược lại, với&lt;/p&gt;

\[\beta \sim \mathcal{N}(0,0.5),\]

&lt;p&gt;khoảng 95% của hệ số dốc thu gọn về xấp xỉ \([-1, 1]\). Tại cùng mức \(x_{std} = 2\), giá trị trung bình dự đoán chủ yếu nằm trong phạm vi \(-2\) đến \(2\) độ lệch chuẩn quanh mức trung tâm — vẫn đủ linh hoạt nhưng sát với thực tế hơn nhiều. Ví dụ này cho thấy kiểm tra dự báo tiên nghiệm hữu ích hơn việc chỉ nhìn vào tham số vì nó chuyển đổi phân phối tiên nghiệm sang chính ngôn ngữ của dữ liệu quan sát.&lt;/p&gt;

&lt;h2 id=&quot;9-phân-tích-độ-nhạy-của-phân-phối-tiên-nghiệm-prior-sensitivity-analysis&quot;&gt;9. Phân tích độ nhạy của phân phối tiên nghiệm (prior sensitivity analysis)&lt;/h2&gt;

&lt;p&gt;Sau khi ước lượng mô hình, một bước kiểm tra quan trọng là đặt câu hỏi: &lt;strong&gt;Nếu thay đổi phân phối tiên nghiệm sang một vài phương án hợp lý lân cận, phân phối hậu nghiệm có biến đổi đáng kể không?&lt;/strong&gt; Nếu kết quả thay đổi mạnh, điều đó cho thấy dữ liệu chưa đủ mạnh để áp đảo tiên nghiệm và kết luận chịu ảnh hưởng rõ rệt từ giả định ban đầu — một thông tin cần được trình bày minh bạch khi báo cáo.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_sensitivity_posterior_overlay.png&quot; alt=&quot;Posterior khi thay đổi các prior hợp lý khác nhau&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Phân tích độ nhạy không nhằm tìm ra một phân phối tiên nghiệm “duy nhất đúng”, mà nhằm đo lường mức độ phụ thuộc của kết luận vào lựa chọn tiên nghiệm.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_sensitivity_summary.png&quot; alt=&quot;Tóm tắt cách đọc prior sensitivity analysis&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;10-bộ-phân-phối-tiên-nghiệm-khởi-đầu-thực-dụng&quot;&gt;10. Bộ phân phối tiên nghiệm khởi đầu thực dụng&lt;/h2&gt;

&lt;p&gt;Với dữ liệu đã được chuẩn hóa, một bộ phân phối tiên nghiệm khởi đầu hợp lý cho hồi quy tuyến tính đơn giản thường là:&lt;/p&gt;

\[\alpha \sim \mathcal{N}(0,1)\]

\[\beta \sim \mathcal{N}(0,1)\]

\[\sigma \sim \mathrm{HalfNormal}(1)\]

&lt;p&gt;Đây không phải công thức cố định cho mọi bài toán, nhưng là điểm xuất phát an toàn để bắt đầu và điều chỉnh tiếp theo bối cảnh cụ thể.&lt;/p&gt;

&lt;h2 id=&quot;11-những-sai-lầm-phổ-biến-khi-chọn-phân-phối-tiên-nghiệm&quot;&gt;11. Những sai lầm phổ biến khi chọn phân phối tiên nghiệm&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bỏ qua thang đo dữ liệu:&lt;/strong&gt; đặt tiên nghiệm theo thói quen mà không kiểm tra đơn vị đo là lỗi thường gặp nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dùng tiên nghiệm quá rộng và xem là “không thông tin”:&lt;/strong&gt; tiên nghiệm trải quá phẳng thường gây khó khăn cho bộ lấy mẫu, tạo dự báo tiên nghiệm phi thực tế và làm giảm độ ổn định của ước lượng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bỏ qua bước kiểm tra dự báo tiên nghiệm:&lt;/strong&gt; nếu không mô phỏng dữ liệu từ tiên nghiệm, ta rất dễ bỏ sót các giả định vô lý ẩn sau công thức.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không thực hiện phân tích độ nhạy:&lt;/strong&gt; ngay cả khi tiên nghiệm ban đầu có vẻ hợp lý, vẫn nên đối chiếu với một vài lựa chọn lân cận để đánh giá độ vững của kết luận.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Chuẩn hóa dữ liệu giúp việc chọn và diễn giải phân phối tiên nghiệm trong hồi quy trở nên đơn giản và nhất quán hơn; phân phối tiên nghiệm thông tin yếu giúp loại bỏ các giá trị phi thực tế mà vẫn để dữ liệu đóng vai trò quyết định; và kiểm tra dự báo tiên nghiệm cùng phân tích độ nhạy là hai công cụ cốt lõi để thẩm định lựa chọn tiên nghiệm.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Bayesian Priors Explained&lt;/td&gt;
          &lt;td&gt;Prior Modelling &amp;amp; Prior Predictive Checks](https://www.youtube.com/watch?v=G3ludfAUAng) — stats 4 good, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Trình bày cách xây dựng phân phối tiên nghiệm và kiểm tra bằng dự báo tiên nghiệm, khớp với quy trình thực hành trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=UH6-9FU6bRg&quot;&gt;Keynote 2: Weakly Informative Priors – Andrew Gelman&lt;/a&gt; — AISTATS 2014, English. Giải thích cơ sở của phân phối tiên nghiệm thông tin yếu, bổ trợ cho phần lấy tiên nghiệm loại này làm điểm khởi đầu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=RTFnrK5ZZ8E&quot;&gt;Standardized variables in a simple regression&lt;/a&gt; — Jos Dornschneider-Elkink, English. Minh họa sự thay đổi ý nghĩa của các hệ số hồi quy sau khi chuẩn hóa biến, làm rõ lý do nên chuẩn hóa trước khi đặt tiên nghiệm.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao chuẩn hóa dữ liệu giúp việc lựa chọn phân phối tiên nghiệm trở nên dễ dàng hơn?&lt;/li&gt;
  &lt;li&gt;Hãy diễn giải bằng lời ý nghĩa của một phân phối tiên nghiệm thông tin yếu đặt cho hệ số dốc.&lt;/li&gt;
  &lt;li&gt;Kiểm tra dự báo tiên nghiệm giúp phát hiện điều gì mà việc chỉ quan sát phân phối tiên nghiệm trên tham số có thể bỏ sót?&lt;/li&gt;
  &lt;li&gt;Trong một bài toán hồi quy thuộc lĩnh vực của bạn, tham số nào đòi hỏi phải chọn phân phối tiên nghiệm cẩn thận nhất?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., Simpson, D., &amp;amp; Betancourt, M. (2017). The prior can often only be understood in the context of the likelihood.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 4.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Regression and Other Stories&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter04/04_03_posterior_inference_pymc/&quot;&gt;4.3 Posterior Inference với PyMC - Từ Theory đến Practice&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 4.1: Bayesian Linear Regression - Mô hình Sinh dữ liệu</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_01_linear_regression_generative/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter04/04_01_linear_regression_generative</id>
   <content type="html">&lt;p&gt;Năm 1886, nhà khoa học người Anh Francis Galton ngồi đối chiếu chiều cao của hàng trăm cặp cha mẹ và con cái trưởng thành tại London. Ông không chỉ thấy một đường thẳng đi lên: ông thấy con của những cặp cha mẹ rất cao vẫn dao động rộng quanh một xu hướng trung bình và có khuynh hướng “hồi quy về trung bình”. Từ quan sát ấy, thuật ngữ &lt;em&gt;hồi quy&lt;/em&gt; (regression) ra đời — và ngay từ khoảnh khắc đầu tiên, bản chất của nó không phải là bài toán hình học vẽ đường thẳng, mà là bài toán mô tả một &lt;strong&gt;quá trình sinh dữ liệu ngẫu nhiên&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu hồi quy tuyến tính Bayes như một &lt;strong&gt;mô hình sinh dữ liệu&lt;/strong&gt; (generative model), thay vì chỉ là bài toán khớp một đường thẳng vào các điểm dữ liệu. Bạn cũng sẽ nắm rõ vai trò của hệ số chặn (intercept), hệ số dốc (slope) và độ nhiễu (noise) trong mô hình, cũng như lý do hồi quy Bayes luôn giữ lại bất định của cả tham số lẫn dự đoán.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ ngắn.&lt;/strong&gt; Khi mô tả mối liên hệ giữa chiều cao và cân nặng, cách tiếp cận truyền thống thường đặt câu hỏi: “Đường thẳng nào khớp dữ liệu tốt nhất?” Trong khi đó, cách tiếp cận Bayes đặt câu hỏi: “Cân nặng của mỗi người được sinh ra quanh một xu hướng trung bình như thế nào, và mức độ bất định của ta về xu hướng đó là bao nhiêu?”&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Vì sao không nên hiểu hồi quy Bayes chỉ đơn thuần là việc tìm một đường thẳng duy nhất?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-mô-hình-sinh-dữ-liệu-phân-phối-có-điều-kiện-và-bất-định-hai-tầng&quot;&gt;Kiến thức cần nhớ: Mô hình sinh dữ liệu, Phân phối có điều kiện và Bất định hai tầng&lt;/h2&gt;

&lt;p&gt;Với người đọc đã có nền tảng đại học (giải tích, đại số tuyến tính, xác suất cơ bản), bước chuyển lớn nhất khi học hồi quy Bayes không nằm ở công thức mới mà ở cách thay đổi góc nhìn trên ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối có điều kiện và mô hình sinh dữ liệu (Generative Model):&lt;/strong&gt; Thay vì xem \(y = \alpha + \beta x + \varepsilon\) như một phương trình đại số có thêm “rác” \(\varepsilon\), thống kê Bayes đọc nó như một họ phân phối xác suất \(p(y \mid x, \alpha, \beta, \sigma) = \mathcal{N}(\alpha + \beta x, \sigma^2)\). Tại mỗi mức \(x\), không có một giá trị \(y\) duy nhất mà có cả một phân phối các giá trị khả dĩ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tham số như biến ngẫu nhiên trên không gian liên tục:&lt;/strong&gt; Nếu xác suất đại học quen gán phân phối cho dữ liệu \(y\), thì suy luận Bayes gán phân phối cho chính các tham số chưa biết \((\alpha, \beta, \sigma)\). Khi kết hợp tiên nghiệm và hàm hợp lý qua định lý Bayes, kết quả không phải một điểm tối ưu mà là mật độ xác suất hậu nghiệm \(p(\alpha, \beta, \sigma \mid x, y)\) trên \(\mathbb{R}^2 \times \mathbb{R}_+\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hai tầng bất định (Epistemic vs. Aleatoric Uncertainty):&lt;/strong&gt; Bất định về tham số \((\alpha, \beta)\) (&lt;em&gt;bất định nhận thức&lt;/em&gt;) sẽ thu hẹp dần về 0 khi ta thu thập thêm nhiều dữ liệu; ngược lại, nhiễu cá thể \(\sigma\) (&lt;em&gt;bất định ngẫu nhiên nội tại&lt;/em&gt;) vẫn tồn tại ngay cả khi cỡ mẫu tiến ra vô cực. Tách bạch hai tầng này là chìa khóa để phân biệt khoảng tin cậy cho trung bình với khoảng dự đoán cho một cá nhân mới.
    &lt;h2 id=&quot;1-hồi-quy-không-chỉ-là-vẽ-một-đường-thẳng&quot;&gt;1. Hồi quy không chỉ là vẽ một đường thẳng&lt;/h2&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Khi mới học hồi quy, nhiều người thường tiếp cận bài toán bằng cách chọn phương trình đường thẳng \(y = \alpha + \beta x\) rồi tìm các hệ số sao cho tổng bình phương sai số đạt giá trị nhỏ nhất. Cách làm này hữu ích, nhưng dễ tạo ra cảm giác hồi quy chỉ là một kỹ thuật khớp đường mang tính hình học.&lt;/p&gt;

&lt;p&gt;Trong hồi quy Bayes, ta đi sâu hơn một bước: đặt câu hỏi dữ liệu được tạo ra từ quá trình nào, vì sao các điểm quan sát không nằm chính xác trên cùng một đường thẳng, và mức độ bất định của ta đối với chính các tham số của đường thẳng đó lớn đến đâu.&lt;/p&gt;

&lt;h2 id=&quot;2-quá-trình-sinh-dữ-liệu-của-hồi-quy-tuyến-tính&quot;&gt;2. Quá trình sinh dữ liệu của hồi quy tuyến tính&lt;/h2&gt;

&lt;p&gt;Giả sử ta muốn mô hình hóa mối quan hệ giữa chiều cao \(x\) và cân nặng \(y\). Quá trình sinh dữ liệu có thể được mô tả qua ba bước sau.&lt;/p&gt;

&lt;h3 id=&quot;bước-1-giả-định-một-xu-hướng-trung-bình&quot;&gt;Bước 1. Giả định một xu hướng trung bình&lt;/h3&gt;

&lt;p&gt;Người cao hơn thường có xu hướng nặng hơn. Ta biểu diễn xu hướng trung bình đó bằng:&lt;/p&gt;

\[\mu_i = \alpha + \beta x_i.\]

&lt;p&gt;Trong đó, \(\alpha\) là hệ số chặn (intercept) và \(\beta\) là hệ số dốc (slope).&lt;/p&gt;

&lt;h3 id=&quot;bước-2-mỗi-cá-thể-dao-động-quanh-xu-hướng-trung-bình&quot;&gt;Bước 2. Mỗi cá thể dao động quanh xu hướng trung bình&lt;/h3&gt;

&lt;p&gt;Trên thực tế, không ai nằm chính xác trên đường trung bình vì cân nặng còn chịu ảnh hưởng của nhiều yếu tố khác như khối lượng cơ, chế độ ăn, giới tính, mức độ vận động hay sai số đo lường. Do đó, ta mô hình hóa giá trị quan sát quanh đường trung bình như sau:&lt;/p&gt;

\[y_i \sim \mathcal{N}(\mu_i,\sigma).\]

&lt;p&gt;Ở đây, \(\sigma\) biểu thị độ nhiễu (noise) — tức mức độ phân tán của các quan sát quanh đường hồi quy.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_regression_data_generating_process.png&quot; alt=&quot;Quá trình sinh dữ liệu của regression&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_regression_distribution_fixed_height.png&quot; alt=&quot;Phân phối cân nặng tại một chiều cao cố định&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;bước-3-thừa-nhận-sự-bất-định-về-các-tham-số&quot;&gt;Bước 3. Thừa nhận sự bất định về các tham số&lt;/h3&gt;

&lt;p&gt;Ta không biết trước giá trị chính xác của hệ số chặn \(\alpha\), hệ số dốc \(\beta\) hay độ nhiễu \(\sigma\). Vì vậy, ta gán phân phối tiên nghiệm (prior) cho các tham số này, sau đó kết hợp với dữ liệu quan sát để suy luận phân phối hậu nghiệm (posterior).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_regression_story_summary.png&quot; alt=&quot;Tóm tắt generative story của regression&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-ba-tham-số-cốt-lõi-cần-nắm-vững&quot;&gt;3. Ba tham số cốt lõi cần nắm vững&lt;/h2&gt;

&lt;h3 id=&quot;31-hệ-số-chặn-alpha&quot;&gt;3.1. Hệ số chặn \(\alpha\)&lt;/h3&gt;

&lt;p&gt;Hệ số chặn là giá trị kỳ vọng của \(y\) khi \(x = 0\). Dù thuận tiện về mặt toán học, tham số này không phải lúc nào cũng có ý nghĩa trực quan trong thực tế. Chẳng hạn, nếu \(x\) là chiều cao tính bằng cm, mốc \(x = 0\) không tồn tại ở người thật. Vì vậy, trong hồi quy Bayes, ta thường dịch tâm (centering) hoặc chuẩn hóa (standardization) biến đầu vào để hệ số chặn mang ý nghĩa dễ diễn giải hơn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_intercept_after_centering.png&quot; alt=&quot;Intercept sau khi center biến đầu vào&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;32-hệ-số-dốc-beta&quot;&gt;3.2. Hệ số dốc \(\beta\)&lt;/h3&gt;

&lt;p&gt;Hệ số dốc cho biết giá trị trung bình của \(y\) thay đổi bao nhiêu khi \(x\) tăng thêm 1 đơn vị. Ví dụ, nếu \(\beta = 0.7\) kg/cm, mỗi 1 cm chiều cao tăng thêm tương ứng với mức tăng trung bình 0.7 kg cân nặng.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_slope_interpretation.png&quot; alt=&quot;Diễn giải slope trong hồi quy tuyến tính&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;33-độ-nhiễu-sigma&quot;&gt;3.3. Độ nhiễu \(\sigma\)&lt;/h3&gt;

&lt;p&gt;Độ nhiễu đo mức độ phân tán của các điểm dữ liệu quanh đường hồi quy. Khi \(\sigma\) nhỏ, các quan sát tập trung sát đường trung bình; khi \(\sigma\) lớn, dữ liệu phân tán rộng hơn quanh đường đó.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_noise_interpretation.png&quot; alt=&quot;Diễn giải noise quanh đường hồi quy&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;4-hồi-quy-bayes-khác-phương-pháp-ols-ở-đâu&quot;&gt;4. Hồi quy Bayes khác phương pháp OLS ở đâu?&lt;/h2&gt;

&lt;h3 id=&quot;phương-pháp-ols-trả-lời-câu-hỏi-gì&quot;&gt;Phương pháp OLS trả lời câu hỏi gì?&lt;/h3&gt;

&lt;p&gt;Phương pháp bình phương tối thiểu thông thường (OLS — Ordinary Least Squares) tập trung tìm một đường thẳng “tốt nhất” duy nhất theo tiêu chí tối thiểu hóa tổng bình phương sai số.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_frequentist_point_estimate.png&quot; alt=&quot;Góc nhìn point estimate của OLS&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;hồi-quy-bayes-trả-lời-câu-hỏi-gì&quot;&gt;Hồi quy Bayes trả lời câu hỏi gì?&lt;/h3&gt;

&lt;p&gt;Hồi quy Bayes đặt câu hỏi rộng hơn: những đường thẳng nào vẫn hợp lý sau khi quan sát dữ liệu, mức độ bất định của hệ số chặn và hệ số dốc là bao nhiêu, và dự đoán cho một quan sát mới có độ bất định lớn đến mức nào. Nói ngắn gọn, OLS cho một đường ước lượng điểm, còn hồi quy Bayes cho một &lt;strong&gt;phân phối gồm nhiều đường thẳng khả dĩ&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bayesian_uncertainty_quantification.png&quot; alt=&quot;Góc nhìn bất định của Bayesian regression&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;41-các-giả-định-nền-cần-nêu-rõ-trước-khi-suy-luận-bayes&quot;&gt;4.1. Các giả định nền cần nêu rõ trước khi suy luận Bayes&lt;/h3&gt;

&lt;p&gt;Trước khi tính phân phối hậu nghiệm, cần nêu rõ các giả định cơ bản của mô hình hồi quy tuyến tính:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Quan hệ trung bình có dạng tuyến tính theo các tham số.&lt;/li&gt;
  &lt;li&gt;Sai số có kỳ vọng bằng 0.&lt;/li&gt;
  &lt;li&gt;Các sai số độc lập có điều kiện với nhau khi biết biến đầu vào.&lt;/li&gt;
  &lt;li&gt;Phương sai của sai số không đổi theo biến đầu vào (tính đồng phương sai — homoscedasticity) trong mô hình cơ bản.&lt;/li&gt;
  &lt;li&gt;Ở dạng đơn giản nhất, sai số được giả định tuân theo phân phối Chuẩn (Normal).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cách tiếp cận Bayes không loại bỏ các giả định này; thay vào đó, nó bổ sung tầng bất định cho tham số và giúp ta kiểm tra lại các giả định một cách minh bạch ở bước kiểm định mô hình (model checking).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_regression_residual_distribution.png&quot; alt=&quot;Residual distribution quanh đường hồi quy&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-phân-phối-hậu-nghiệm-của-hồi-quy-là-cả-một-bó-đường-thẳng&quot;&gt;Thử nghiệm: phân phối hậu nghiệm của hồi quy là cả một bó đường thẳng&lt;/h3&gt;

&lt;p&gt;Thêm từng điểm dữ liệu để quan sát bó đường thẳng khả dĩ thu hẹp dần, đồng thời so sánh với đường OLS và đường thực.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;regression-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;video-ngắn-hồi-quy-bayes-cả-bó-đường-thẳng--hai-tầng-bất-định&quot;&gt;Video ngắn: Hồi quy Bayes: Cả Bó Đường thẳng &amp;amp; Hai tầng Bất định&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch04-01a-regression-posterior-lines.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 22 giây (mô phỏng chuyển động liên tục + nhạc nền nhẹ nhàng): so sánh đường OLS đơn lẻ với bó 25 đường thẳng hậu nghiệm, đồng thời tách rõ bất định của đường trung bình và khoảng dự đoán cá nhân tại 175 cm.&lt;/p&gt;

&lt;h2 id=&quot;5-vì-sao-góc-nhìn-sinh-dữ-liệu-lại-quan-trọng&quot;&gt;5. Vì sao góc nhìn sinh dữ liệu lại quan trọng?&lt;/h2&gt;

&lt;p&gt;Khi xem hồi quy là một mô hình sinh dữ liệu, ta sẽ chủ động đặt ra những câu hỏi sát thực tế hơn: dữ liệu được tạo ra theo cơ chế nào, giả định phân phối Chuẩn cho phần dư (residual) có phù hợp không, độ nhiễu có đồng nhất trên toàn miền giá trị của \(x\) không, và dữ liệu mô phỏng từ mô hình có giống dữ liệu quan sát hay không. Đây chính là ranh giới giữa việc “chạy hồi quy xong là dừng” và việc “xây dựng mô hình rồi kiểm tra lại”.&lt;/p&gt;

&lt;h2 id=&quot;6-viết-mô-hình-bayes-đầy-đủ&quot;&gt;6. Viết mô hình Bayes đầy đủ&lt;/h2&gt;

&lt;p&gt;Một mô hình hồi quy tuyến tính Bayes tối giản được viết như sau:&lt;/p&gt;

\[\alpha \sim p(\alpha)\]

\[\beta \sim p(\beta)\]

\[\sigma \sim p(\sigma)\]

\[y_i \sim \mathcal{N}(\alpha + \beta x_i,\sigma)\]

&lt;p&gt;Từ mô hình này, ta suy luận phân phối hậu nghiệm đồng thời:&lt;/p&gt;

\[p(\alpha,\beta,\sigma \mid x,y).\]

&lt;p&gt;Điều quan trọng không nằm ở việc học thuộc ký hiệu, mà ở việc hiểu rõ ba thành phần: phân phối tiên nghiệm (prior) biểu diễn niềm tin trước khi có dữ liệu, hàm hợp lý (likelihood) mô tả cơ chế sinh dữ liệu, và phân phối hậu nghiệm (posterior) là kết quả kết hợp hai thành phần đó sau khi quan sát dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;61-khung-hàm-hợp-lý--tiên-nghiệm--hậu-nghiệm-cho-hồi-quy&quot;&gt;6.1. Khung hàm hợp lý – tiên nghiệm – hậu nghiệm cho hồi quy&lt;/h3&gt;

&lt;p&gt;Với tập dữ liệu \(\mathcal D=\{(x_i,y_i)\}_{i=1}^n\), hàm hợp lý có dạng:&lt;/p&gt;

\[p(y\mid X,\alpha,\beta,\sigma)=\prod_{i=1}^n \mathcal N(y_i\mid \alpha+\beta x_i,\sigma).\]

&lt;p&gt;Nếu các tham số được giả định độc lập tiên nghiệm, phân phối tiên nghiệm đồng thời là:&lt;/p&gt;

\[p(\alpha,\beta,\sigma)=p(\alpha)p(\beta)p(\sigma).\]

&lt;p&gt;Theo định lý Bayes, phân phối hậu nghiệm thỏa mãn:&lt;/p&gt;

\[p(\alpha,\beta,\sigma\mid X,y)
\propto p(y\mid X,\alpha,\beta,\sigma)\,p(\alpha,\beta,\sigma).\]

&lt;p&gt;Đây là khung tư duy xuyên suốt chương này: mọi suy luận về tham số hồi quy đều bắt nguồn từ một mô hình phân phối đồng thời được xác định rõ ràng.&lt;/p&gt;

&lt;h3 id=&quot;62-khoảng-bất-định-cho-hệ-số-dốc-biết-trước-và-chưa-biết-phương-sai-nhiễu&quot;&gt;6.2. Khoảng bất định cho hệ số dốc: biết trước và chưa biết phương sai nhiễu&lt;/h3&gt;

&lt;p&gt;Khi phương sai nhiễu được xem là đã biết trước, phân phối hậu nghiệm của hệ số dốc thường có dạng gần phân phối Chuẩn, và khoảng hậu nghiệm 95% cho \(\beta\) có dạng:&lt;/p&gt;

\[\mu_{\beta\mid D}\pm z_{0.975}\,\sigma_{\beta\mid D}.\]

&lt;p&gt;Ngược lại, khi phương sai nhiễu chưa biết và phải được suy luận đồng thời từ dữ liệu, phân phối hậu nghiệm biên của \(\beta\) thường có đuôi dày hơn (trong thiết lập liên hợp là phân phối Student-t), khiến khoảng hậu nghiệm rộng hơn để phản ánh thêm bất định về nhiễu. Vì vậy, khi báo cáo khoảng ước lượng cho hệ số dốc, cần nêu rõ phương sai nhiễu đang được cố định hay được ước lượng từ dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;giải-thích-từ-3-điểm-dữ-liệu-đến-phân-phối-hậu-nghiệm-và-hai-tầng-bất-định&quot;&gt;Giải thích: Từ 3 điểm dữ liệu đến phân phối hậu nghiệm và hai tầng bất định&lt;/h3&gt;

&lt;p&gt;Để thấy cơ chế Bayes vận hành cụ thể ra sao thay vì dừng ở ký hiệu tổng quát, hãy tự tay tính một mô hình hồi quy nhỏ từ đầu đến cuối.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Dữ liệu đã dịch tâm:&lt;/strong&gt; Giả sử ta quan sát \(n = 3\) điểm \((x_i, y_i) \in \{(-1, 1),\ (0, 2),\ (1, 5)\}\), trong đó \(\bar x = 0\) và \(\sum x_i^2 = 2\). Giả sử độ nhiễu đã biết là \(\sigma = 1\) (độ chính xác dữ liệu \(\tau_y = 1/\sigma^2 = 1\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đặt phân phối tiên nghiệm:&lt;/strong&gt; Chọn \(\alpha \sim \mathcal{N}(0, 2^2)\) (độ chính xác tiên nghiệm \(\tau_{\alpha,0} = 1/4 = 0.25\)) và \(\beta \sim \mathcal{N}(0, 1^2)\) (độ chính xác \(\tau_{\beta,0} = 1\)), độc lập nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật hậu nghiệm bằng tay:&lt;/strong&gt; Vì \(\sum x_i = 0\), trong hàm hợp lý không có tích chéo giữa \(\alpha\) và \(\beta\), nên hai tham số cập nhật hoàn toàn độc lập:
    &lt;ul&gt;
      &lt;li&gt;Với hệ số chặn \(\alpha\): \(\sum y_i = 1 + 2 + 5 = 8\). Độ chính xác hậu nghiệm là \(\tau_{\alpha \mid D} = 0.25 + 3 = 3.25\), suy ra trung bình hậu nghiệm \(\mu_{\alpha \mid D} = 8 / 3.25 \approx 2.462\) và phương sai \(\operatorname{Var}(\alpha \mid D) = 1/3.25 \approx 0.308\) (\(\text{SD} \approx 0.555\)).&lt;/li&gt;
      &lt;li&gt;Với hệ số dốc \(\beta\): \(\sum x_i y_i = (-1)(1) + 0(2) + (1)(5) = 4\). Độ chính xác hậu nghiệm là \(\tau_{\beta \mid D} = 1 + 2 = 3\), suy ra trung bình hậu nghiệm \(\mu_{\beta \mid D} = 4/3 \approx 1.333\) và phương sai \(\operatorname{Var}(\beta \mid D) = 1/3 \approx 0.333\) (\(\text{SD} \approx 0.577\)).
&lt;em&gt;(Lưu ý: ước lượng OLS thuần túy là \(\hat\alpha_{\text{OLS}} = 8/3 \approx 2.667\) và \(\hat\beta_{\text{OLS}} = 4/2 = 2.0\); phân phối tiên nghiệm tâm tại 0 đã kéo nhẹ cả hai ước lượng về gần 0 — hiện tượng co cụm điều chuẩn tự nhiên của Bayes.)&lt;/em&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tách hai tầng bất định khi dự đoán tại \(x_{\text{new}} = 1\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Giá trị trung bình dự đoán là \(\mathbb{E}[\mu_{\text{new}} \mid D] = 2.462 + 1.333(1) = 3.795\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tầng 1 (bất định đường trung bình):&lt;/strong&gt; \(\operatorname{Var}(\mu_{\text{new}} \mid D) = \operatorname{Var}(\alpha \mid D) + 1^2 \operatorname{Var}(\beta \mid D) = 0.308 + 0.333 = 0.641 \implies \text{SD} \approx 0.80\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tầng 2 (dự đoán một quan sát mới \(y_{\text{new}}\)):&lt;/strong&gt; Cộng thêm phương sai nhiễu cá thể \(\sigma^2 = 1\), ta được \(\operatorname{Var}(y_{\text{new}} \mid D) = 0.641 + 1 = 1.641 \implies \text{SD} \approx 1.28\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chỉ với bốn dòng số học, bạn thấy ngay toàn bộ tinh thần hồi quy Bayes: phân phối hậu nghiệm co cụm nhẹ ước lượng OLS, và dự đoán cho một điểm mới luôn gánh thêm phương sai nhiễu \(\sigma^2\) bên cạnh bất định tham số.&lt;/p&gt;

&lt;h2 id=&quot;7-một-số-ví-dụ-thực-tế-khác&quot;&gt;7. Một số ví dụ thực tế khác&lt;/h2&gt;

&lt;p&gt;Hồi quy Bayes được áp dụng rộng rãi trong nhiều lĩnh vực khác nhau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Giá nhà và diện tích:&lt;/strong&gt; biến đầu vào \(x\) là diện tích, biến đầu ra \(y\) là giá nhà.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điểm thi và số giờ học:&lt;/strong&gt; \(x\) là số giờ ôn tập, \(y\) là điểm thi.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Doanh thu và chi phí quảng cáo:&lt;/strong&gt; \(x\) là ngân sách quảng cáo, \(y\) là doanh thu.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trong mọi trường hợp, cấu trúc mô hình sinh dữ liệu đều giống nhau: tồn tại một xu hướng trung bình, các quan sát thực tế dao động quanh xu hướng đó, và ta luôn có mức độ bất định nhất định đối với các tham số điều khiển xu hướng.&lt;/p&gt;

&lt;h2 id=&quot;8-hồi-quy-bayes-tạo-dự-đoán-như-thế-nào&quot;&gt;8. Hồi quy Bayes tạo dự đoán như thế nào?&lt;/h2&gt;

&lt;p&gt;Giả sử bạn cần dự đoán cân nặng của một người cao 175 cm. Hồi quy Bayes không chỉ trả về một con số duy nhất, mà cung cấp cả giá trị trung bình dự đoán, phần bất định do chưa biết chính xác \(\alpha\) và \(\beta\), cùng phần bất định do độ nhiễu cá thể \(\sigma\). Nhờ đó, ta không chỉ có dự đoán mà còn biết mức độ tin cậy của dự đoán ấy.&lt;/p&gt;

&lt;h3 id=&quot;81-ví-dụ-minh-họa-dự-đoán-cân-nặng-ở-chiều-cao-175-cm&quot;&gt;8.1. Ví dụ minh họa: dự đoán cân nặng ở chiều cao 175 cm&lt;/h3&gt;

&lt;p&gt;Giả sử sau khi ước lượng mô hình trên dữ liệu chiều cao – cân nặng, phân phối hậu nghiệm tập trung quanh các giá trị điển hình:&lt;/p&gt;

\[\alpha \approx -55,\qquad \beta \approx 0.75,\qquad \sigma \approx 6.\]

&lt;p&gt;Ba con số này có thể được diễn giải như sau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Hệ số chặn \(\alpha \approx -55\) xác định vị trí hình học của đường trung bình.&lt;/li&gt;
  &lt;li&gt;Hệ số dốc \(\beta \approx 0.75\) cho biết khi chiều cao tăng thêm 1 cm, cân nặng trung bình tăng khoảng 0.75 kg.&lt;/li&gt;
  &lt;li&gt;Độ nhiễu \(\sigma \approx 6\) kg cho thấy ngay cả giữa những người có cùng chiều cao, cân nặng thực tế vẫn dao động đáng kể quanh mức trung bình.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Với một người mới có chiều cao \(x_{\text{new}}=175\) cm, giá trị trung bình dự đoán theo bộ tham số đại diện là:&lt;/p&gt;

\[\mu_{\text{new}} = \alpha + \beta x_{\text{new}}
\approx -55 + 0.75 \times 175 = 76.25.\]

&lt;p&gt;Nếu chỉ dùng một bộ tham số duy nhất, ta sẽ kết luận mức cân nặng trung bình hợp lý là khoảng 76.25 kg. Tuy nhiên, hồi quy Bayes không giả định rằng \(\alpha\) và \(\beta\) đã được biết chắc chắn. Hãy xem xét vài mẫu tham số rút ra từ phân phối hậu nghiệm:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Mẫu hậu nghiệm&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(\alpha\)&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(\beta\)&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(\sigma\)&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(\mu_{\text{new}} = \alpha + \beta \cdot 175\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;-52&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.73&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;5.8&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;75.75&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;-58&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.77&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6.1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;76.75&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;-50&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.72&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;5.5&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;76.00&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;-57&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.76&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6.4&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;76.00&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Bảng trên cho thấy: ngay cả khi chưa tính đến nhiễu cá thể, bản thân sự bất định về \(\alpha\) và \(\beta\) đã tạo ra một &lt;strong&gt;phân phối cho giá trị trung bình dự đoán&lt;/strong&gt;. Thay vì khẳng định mức trung bình đúng bằng 76.25 kg, mô hình cho biết vùng giá trị hợp lý của trung bình tại chiều cao 175 cm nằm khoảng từ 75 đến 77 kg.&lt;/p&gt;

&lt;p&gt;Từ đây, cần phân biệt rõ hai câu hỏi khác nhau:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Câu hỏi 1. Cân nặng trung bình của nhóm người cao 175 cm là bao nhiêu?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Câu hỏi này hướng tới đại lượng \(\mu_{\text{new}}\). Khi rút nhiều mẫu từ phân phối hậu nghiệm và tính \(\mu_{\text{new}}\) cho từng mẫu, ta thu được phân phối hậu nghiệm của giá trị trung bình. Giả sử khoảng hậu nghiệm 89% thu được là:&lt;/p&gt;

\[\mu_{\text{new}} \in [74,\ 78.5]\ \text{kg}.\]

&lt;p&gt;Khoảng này phản ánh &lt;strong&gt;bất định tham số&lt;/strong&gt; — tức sự chưa chắc chắn về vị trí chính xác của đường hồi quy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Câu hỏi 2. Một cá nhân cụ thể cao 175 cm sẽ nặng bao nhiêu?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Câu hỏi này khó hơn vì ngoài bất định tham số còn có biến thiên cá thể quanh đường trung bình. Ta cần dùng phân phối dự báo hậu nghiệm (posterior predictive distribution):&lt;/p&gt;

\[y_{\text{new}} \sim \mathcal{N}(\mu_{\text{new}}, \sigma).\]

&lt;p&gt;Khi lan truyền đồng thời bất định của \(\alpha, \beta, \sigma\) và nhiễu cá thể, khoảng dự đoán 89% sẽ rộng hơn đáng kể, chẳng hạn:&lt;/p&gt;

\[y_{\text{new}} \in [66,\ 87]\ \text{kg}.\]

&lt;p&gt;Khoảng thứ hai rộng hơn nhiều vì nó dự đoán cho &lt;strong&gt;một cá nhân cụ thể&lt;/strong&gt; thay vì giá trị trung bình của cả nhóm. Điểm khác biệt này thường dễ bị nhầm lẫn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Khoảng của \(\mu_{\text{new}}\) phản ánh bất định về xu hướng trung bình.&lt;/li&gt;
  &lt;li&gt;Khoảng của \(y_{\text{new}}\) phản ánh bất định về một quan sát mới cụ thể.&lt;/li&gt;
  &lt;li&gt;Khoảng dự đoán cho \(y_{\text{new}}\) luôn rộng hơn vì bao hàm cả biến thiên cá thể.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Theo tinh thần mô hình sinh dữ liệu, quy trình dự đoán Bayes gồm bốn bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Rút một bộ mẫu tham số \((\alpha^{(s)}, \beta^{(s)}, \sigma^{(s)})\) từ phân phối hậu nghiệm.&lt;/li&gt;
  &lt;li&gt;Tính giá trị trung bình dự đoán \(\mu_{\text{new}}^{(s)} = \alpha^{(s)} + \beta^{(s)} x_{\text{new}}\).&lt;/li&gt;
  &lt;li&gt;Sinh một quan sát mới \(y_{\text{new}}^{(s)} \sim \mathcal{N}(\mu_{\text{new}}^{(s)}, \sigma^{(s)})\).&lt;/li&gt;
  &lt;li&gt;Lặp lại quá trình trên nhiều lần để thu được phân phối dự báo hậu nghiệm.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Như vậy, dự đoán trong hồi quy Bayes không phải là thay số vào một đường thẳng cố định, mà là tạo ra cả một phân phối các giá trị mới hợp lý sau khi đã cập nhật dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;82-mở-rộng-từ-hồi-quy-một-biến-sang-nhiều-biến-dạng-ma-trận&quot;&gt;8.2. Mở rộng từ hồi quy một biến sang nhiều biến (dạng ma trận)&lt;/h3&gt;

&lt;p&gt;Khi có nhiều biến giải thích, mô hình được viết gọn dưới dạng ma trận:&lt;/p&gt;

\[y=X\mathbf w+\varepsilon,\]

&lt;p&gt;trong đó \(\mathbf w=(\alpha,\beta_1,\dots,\beta_p)^\top\) là vector tham số và \(X\) là ma trận thiết kế (design matrix). Suy luận Bayes khi đó chuyển từ một hệ số dốc sang một vector hệ số, nhưng cấu trúc tư duy không thay đổi: đặt phân phối tiên nghiệm trên \(\mathbf w\), xác định hàm hợp lý từ cơ chế sinh dữ liệu và suy luận phân phối hậu nghiệm cho toàn bộ vector tham số.&lt;/p&gt;

&lt;h2 id=&quot;9-thói-quen-tư-duy-cần-hình-thành&quot;&gt;9. Thói quen tư duy cần hình thành&lt;/h2&gt;

&lt;p&gt;Mỗi khi gặp một bài toán hồi quy, hãy lần lượt trả lời năm câu hỏi: dữ liệu được sinh ra từ quá trình nào, đâu là xu hướng trung bình, đâu là phần nhiễu, những tham số nào chưa biết, và khi dự đoán cho quan sát mới thì cần giữ lại những nguồn bất định nào. Thực hành đều đặn chuỗi câu hỏi này sẽ giúp bạn tiếp cận bài toán như một người làm mô hình hóa Bayes thay vì chỉ chạy thuật toán khớp đường.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Hồi quy tuyến tính Bayes là một mô hình sinh dữ liệu, trong đó các quan sát dao động quanh một xu hướng trung bình kèm nhiễu; hệ số chặn, hệ số dốc và độ nhiễu đều là các đại lượng chưa biết cần được suy luận bằng phân phối thay vì ước lượng điểm; và ưu điểm cốt lõi của hồi quy Bayes là giữ lại đầy đủ bất định của cả tham số lẫn dự đoán thay vì chỉ đưa ra một đường thẳng duy nhất.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aFDOzpTeg0s&quot;&gt;The Essence of Linear Regression!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Trình bày hồi quy như mô hình trung bình có điều kiện cộng nhiễu, phù hợp với cách tiếp cận không bắt đầu từ bình phương tối thiểu trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=7ArmBVF2dCs&quot;&gt;Linear Regression, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Minh họa trực quan hệ số chặn, hệ số dốc và phần dư trên đường hồi quy, bổ trợ cho phần diễn giải \(\alpha\), \(\beta\) và \(\sigma\).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=tNOu-SEacNU&quot;&gt;Statistical Rethinking 2023 - 03 - Geocentric Models&lt;/a&gt; — Richard McElreath, English. Trình bày cách viết mô hình hồi quy dưới dạng mô hình sinh trước khi ước lượng, tương ứng với trình tự của bài học.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Hãy mô tả quá trình sinh dữ liệu cho mối quan hệ giữa số giờ học và điểm thi.&lt;/li&gt;
  &lt;li&gt;Vì sao \(\sigma\) là một tham số quan trọng của mô hình chứ không chỉ là phần dư phụ thêm?&lt;/li&gt;
  &lt;li&gt;Sự khác biệt cốt lõi giữa “khớp một đường thẳng” (fit a line) và “mô hình hóa một quá trình” (model a process) là gì?&lt;/li&gt;
  &lt;li&gt;Trong công việc hoặc lĩnh vực bạn quan tâm, bài toán hồi quy nào nên được tiếp cận theo hướng mô hình sinh dữ liệu?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 4.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Regression and Other Stories&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapters on regression.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter04/04_02_priors_for_regression/&quot;&gt;4.2 Priors for Regression - Chọn Prior có Nguyên tắc&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 2.6: Grid Approximation - Xấp xỉ Lưới</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_06_grid_approximation/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_06_grid_approximation</id>
   <content type="html">&lt;p&gt;Chuyện gì xảy ra khi bạn muốn dùng một phân phối prior thực tế — chẳng hạn prior cắt cụt bằng 0 ở nửa dưới hoặc prior có hai đỉnh — không còn liên hợp với likelihood nữa? Công thức cộng siêu tham số gọn gàng lập tức biến mất. Thay vì nhảy ngay vào các thuật toán MCMC phức tạp, &lt;strong&gt;xấp xỉ lưới (grid approximation)&lt;/strong&gt; cho ta một cách tiếp cận trực quan nhất: chia miền tham số liên tục thành một lưới hữu hạn các điểm, tính &lt;em&gt;prior × likelihood&lt;/em&gt; tại từng điểm, rồi chuẩn hóa để tổng bằng 1.&lt;/p&gt;

&lt;p&gt;Dù chỉ hiệu quả trong không gian 1–2 chiều, xấp xỉ lưới là “kính hiển vi sư phạm” tốt nhất giúp bạn nhìn thấy tận mắt hình dạng thực sự của định lý Bayes trên bất kỳ prior nào.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn cần hiểu xấp xỉ lưới (grid approximation) như cây cầu nối từ suy luận Bayes giải tay sang suy luận Bayes bằng tính toán số. Bạn cần nắm ý tưởng rời rạc hóa không gian tham số, tự tính được posterior trên một lưới đơn giản, biết cách khai thác kết quả từ lưới, đồng thời hiểu rõ vì sao phương pháp này gặp giới hạn khi số chiều tham số tăng lên.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ mini.&lt;/strong&gt; Bạn muốn suy luận \(\theta\) sau khi quan sát 6 mặt ngửa trong 9 lần tung, nhưng thay vì xét liên tục trên toàn đoạn \([0,1]\), bạn chỉ đánh giá trên 5 giá trị ứng viên \(0, 0.25, 0.5, 0.75, 1\). Đó chính là tinh thần của xấp xỉ lưới.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Khi tăng số điểm lưới từ 5 lên 100 hoặc 1000, posterior xấp xỉ sẽ thay đổi như thế nào?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-rời-rạc-hóa-tích-phân-tính-bất-biến-của-bayes-và-lời-nguyền-số-chiều&quot;&gt;Kiến thức cần nhớ: Rời rạc hóa tích phân, Tính bất biến của Bayes và Lời nguyền số chiều&lt;/h2&gt;

&lt;p&gt;Xấp xỉ lưới nối trực tiếp lý thuyết giải tích với tư duy tính toán số qua ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xấp xỉ tích phân Riemann (Numerical Quadrature):&lt;/strong&gt; Tích phân mẫu số \(p(y) = \int p(y \mid \theta) p(\theta)\,d\theta\) được xấp xỉ bằng tổng Riemann trên lưới đều \(\theta_1, \dots, \theta_M\) có bước lưới \(\Delta\theta\). Khi bỏ hằng số \(\Delta\theta\) chung ở cả tử và mẫu, trọng số hậu nghiệm tại mỗi điểm lưới đơn giản là \(w_j \propto p(y \mid \theta_j) p(\theta_j)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tự do tuyệt đối trong chọn Prior:&lt;/strong&gt; Xấp xỉ lưới phá bỏ hoàn toàn sự phụ thuộc vào tính liên hợp — bạn có thể dùng prior bậc thang, prior hỗn hợp hay prior cắt cụt chỉ bằng một dòng mảng NumPy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lời nguyền số chiều (Curse of Dimensionality) &amp;amp; Cầu nối sang MCMC:&lt;/strong&gt; Với \(d\) tham số và \(M = 100\) điểm mỗi chiều, số điểm lưới là \(100^d\): \(d = 1\) chỉ cần \(100\) điểm, \(d = 2\) cần \(10^4\) điểm, nhưng \(d = 10\) đã vọt lên \(10^{20}\) điểm (bất khả thi). Chính rào cản này là động lực trực tiếp dẫn sang MCMC ở Chương 3.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mở-đầu-khi-posterior-không-có-công-thức-dạng-đóng&quot;&gt;Mở đầu: khi posterior không có công thức dạng đóng&lt;/h2&gt;

&lt;p&gt;Ở Bài 2.5, các cặp liên hợp cho phép tính posterior rất gọn. Tuy nhiên, trong thực tế không phải lúc nào mô hình cũng có dạng giải tích thuận tiện như vậy: prior có thể là hỗn hợp của hai niềm tin cạnh tranh, likelihood có thể không liên hợp với prior, hoặc đôi khi ta đơn giản cần một cách tính trực quan để nhìn rõ từng bước cập nhật Bayes. Trong những tình huống đó, xấp xỉ lưới là phương pháp đơn giản nhất để bắt đầu.&lt;/p&gt;

&lt;h2 id=&quot;1-ý-tưởng-cốt-lõi-thay-miền-liên-tục-bằng-một-tập-điểm-hữu-hạn&quot;&gt;1. Ý tưởng cốt lõi: thay miền liên tục bằng một tập điểm hữu hạn&lt;/h2&gt;

&lt;p&gt;Giả sử tham số \(\theta\) nhận giá trị trên đoạn \([0,1]\). Thay vì xét vô hạn giá trị liên tục, ta chọn một tập hữu hạn gồm \(G\) điểm lưới trên đoạn này:&lt;/p&gt;

\[\theta_1,\theta_2,\dots,\theta_G.\]

&lt;p&gt;Tại mỗi điểm lưới, ta lần lượt tính giá trị prior, likelihood và tích của chúng (posterior chưa chuẩn hóa), sau đó chia cho tổng toàn bộ các giá trị để thu được một phân phối posterior rời rạc hợp lệ. Nói cách khác, &lt;strong&gt;xấp xỉ lưới chuyển bài toán tích phân liên tục thành bài toán chấm điểm và chuẩn hóa trên một tập các giá trị ứng viên.&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-ví-dụ-tính-tay-6-mặt-ngửa-trong-9-lần-tung&quot;&gt;2. Ví dụ tính tay: 6 mặt ngửa trong 9 lần tung&lt;/h2&gt;

&lt;p&gt;Giả sử prior là phân phối đều trên \([0,1]\), dữ liệu quan sát là 6 mặt ngửa trong 9 lần tung, và ta dùng lưới gồm 5 điểm:&lt;/p&gt;

\[\theta \in \{0,\ 0.25,\ 0.5,\ 0.75,\ 1\}.\]

&lt;p&gt;Likelihood tỉ lệ với:&lt;/p&gt;

\[\theta^6(1-\theta)^3.\]

&lt;p&gt;Tính giá trị tại từng điểm lưới:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;\(\theta\)&lt;/th&gt;
      &lt;th&gt;prior&lt;/th&gt;
      &lt;th&gt;likelihood chưa chuẩn hóa&lt;/th&gt;
      &lt;th&gt;posterior chưa chuẩn hóa&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;0.00&lt;/td&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;0.000000&lt;/td&gt;
      &lt;td&gt;0.000000&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;0.25&lt;/td&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;0.000103&lt;/td&gt;
      &lt;td&gt;0.000103&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;0.50&lt;/td&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;0.001953&lt;/td&gt;
      &lt;td&gt;0.001953&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;0.75&lt;/td&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;0.002781&lt;/td&gt;
      &lt;td&gt;0.002781&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;1.00&lt;/td&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;0.000000&lt;/td&gt;
      &lt;td&gt;0.000000&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Tiếp theo, ta chuẩn hóa bằng cách chia mỗi giá trị cho tổng của cột cuối. Kết quả cho thấy trên lưới này, vùng quanh \(0.75\) được dữ liệu ủng hộ mạnh nhất, vùng quanh \(0.25\) yếu hơn hẳn, còn hai đầu mút \(0\) và \(1\) có trọng số bằng 0. Ví dụ nhỏ này minh họa rằng suy luận Bayes không nhất thiết phải bắt đầu bằng các tích phân phức tạp, mà có thể hiểu trực tiếp như quy trình chấm điểm và chuẩn hóa.&lt;/p&gt;

&lt;h3 id=&quot;21-đọc-kết-quả-posterior-rời-rạc-bằng-số&quot;&gt;2.1. Đọc kết quả posterior rời rạc bằng số&lt;/h3&gt;

&lt;p&gt;Tổng ba trọng số khác 0 ở bảng trên xấp xỉ:&lt;/p&gt;

\[0.000103 + 0.001953 + 0.002781 = 0.004837.\]

&lt;p&gt;Sau khi chuẩn hóa, posterior rời rạc trên lưới gồm:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
\[P(\theta=0.25 \mid D) \approx 0.021\]
  &lt;/li&gt;
  &lt;li&gt;
\[P(\theta=0.50 \mid D) \approx 0.404\]
  &lt;/li&gt;
  &lt;li&gt;
\[P(\theta=0.75 \mid D) \approx 0.575\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ngay trên một lưới rất thô như vậy, ta đã có thể tính trực tiếp xác suất của một biến cố, chẳng hạn:&lt;/p&gt;

\[P(\theta \ge 0.5 \mid D) \approx 0.404 + 0.575 = 0.979.\]

&lt;p&gt;Ưu điểm trực giác của xấp xỉ lưới nằm ở chỗ nó biến posterior thành các xác suất cụ thể có thể cộng, so sánh và diễn giải ngay lập tức.&lt;/p&gt;

&lt;h2 id=&quot;3-thuật-toán-xấp-xỉ-lưới&quot;&gt;3. Thuật toán xấp xỉ lưới&lt;/h2&gt;

&lt;p&gt;Quy trình chuẩn gồm 5 bước:&lt;/p&gt;

&lt;h3 id=&quot;bước-1-tạo-lưới-tham-số&quot;&gt;Bước 1. Tạo lưới tham số&lt;/h3&gt;

&lt;p&gt;Ví dụ:&lt;/p&gt;

\[\theta_{\text{grid}} = \text{linspace}(0,1,G).\]

&lt;h3 id=&quot;bước-2-tính-prior-tại-từng-điểm-lưới&quot;&gt;Bước 2. Tính prior tại từng điểm lưới&lt;/h3&gt;

&lt;p&gt;Mỗi điểm trên lưới nhận một giá trị mật độ hoặc trọng số tiền nghiệm tương ứng.&lt;/p&gt;

&lt;h3 id=&quot;bước-3-tính-likelihood-tại-từng-điểm-lưới&quot;&gt;Bước 3. Tính likelihood tại từng điểm lưới&lt;/h3&gt;

&lt;p&gt;Với cùng bộ dữ liệu đã quan sát, đánh giá mức độ giải thích dữ liệu tại từng điểm lưới.&lt;/p&gt;

&lt;h3 id=&quot;bước-4-nhân-prior-với-likelihood&quot;&gt;Bước 4. Nhân prior với likelihood&lt;/h3&gt;

&lt;p&gt;Tích này tạo ra posterior chưa chuẩn hóa:&lt;/p&gt;

\[p(\theta_i \mid D) \propto p(D \mid \theta_i)p(\theta_i).\]

&lt;h3 id=&quot;bước-5-chuẩn-hóa&quot;&gt;Bước 5. Chuẩn hóa&lt;/h3&gt;

&lt;p&gt;Chia từng giá trị cho tổng toàn bộ trọng số trên lưới để thu được phân phối hậu nghiệm rời rạc hợp lệ.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-từng-bước-của-xấp-xỉ-lưới&quot;&gt;Thử nghiệm: từng bước của xấp xỉ lưới&lt;/h3&gt;

&lt;p&gt;Chia lưới, tính prior, likelihood, nhân rồi chuẩn hóa; tăng số điểm lưới để thấy sai số giảm.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;grid-explainer&quot; data-lang=&quot;vi&quot; data-prior=&quot;flat&quot; data-k=&quot;6&quot; data-n=&quot;9&quot; data-points=&quot;10&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-đánh-đổi-giữa-độ-mịn-của-lưới-và-chi-phí-tính-toán&quot;&gt;4. Đánh đổi giữa độ mịn của lưới và chi phí tính toán&lt;/h2&gt;

&lt;p&gt;Một lưới 5 điểm đủ để minh họa nguyên lý, nhưng để thu được xấp xỉ chính xác hơn, ta cần lưới mịn hơn như 20, 100 hay 1000 điểm. Khi lưới mịn hơn, phân phối rời rạc càng tiệm cận phân phối liên tục chính xác, kéo theo các thống kê như trung bình hậu nghiệm hay khoảng tin cậy Bayes cũng chính xác hơn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_resolution_5.png&quot; alt=&quot;Grid rất thô với 5 điểm&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_resolution_20.png&quot; alt=&quot;Grid trung bình với 20 điểm&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_resolution_100.png&quot; alt=&quot;Grid mịn với 100 điểm&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Vì vậy, ta luôn gặp sự đánh đổi quen thuộc: lưới thô chạy nhanh nhưng sai số lớn, còn lưới mịn chính xác hơn nhưng tốn chi phí tính toán hơn.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-xấp-xỉ-lưới-5--15--50-điểm--lời-nguyền-số-chiều-1d--10d&quot;&gt;Video ngắn: Xấp xỉ Lưới (5 → 15 → 50 điểm) &amp;amp; Lời nguyền Số chiều (1D → 10D)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch02-06a-grid-approx-resolution-curse.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 23 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): nâng dần độ mịn lưới cho khớp khít mật độ hậu nghiệm chính xác, rồi chỉ rõ số điểm bùng nổ từ 100¹ lên 100¹⁰ — mở đường sang MCMC ở Chương 03.&lt;/p&gt;

&lt;h2 id=&quot;5-ví-dụ-thực-tế-prior-không-liên-hợp&quot;&gt;5. Ví dụ thực tế: prior không liên hợp&lt;/h2&gt;

&lt;p&gt;Giả sử nhóm phân tích có hai giả thuyết cạnh tranh về tỷ lệ khách quay lại: một giả thuyết cho rằng tỷ lệ nằm quanh \(0.3\), giả thuyết kia cho rằng nó nằm quanh \(0.7\). Ta có thể biểu diễn prior này bằng một phân phối hỗn hợp hai đỉnh. Khi đó posterior không còn công thức đóng đơn giản như Beta–Binomial, nhưng xấp xỉ lưới vẫn xử lý dễ dàng: tính mật độ prior hỗn hợp tại từng điểm lưới, nhân với likelihood rồi chuẩn hóa.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/grid_mixture_prior_example.png&quot; alt=&quot;Ví dụ grid với prior mixture&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ưu điểm lớn của xấp xỉ lưới là không đòi hỏi tính liên hợp; nó chỉ cần ta tính được giá trị của prior và likelihood tại các điểm lưới.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-prior-không-liên-hợp-tam-giác-lệch&quot;&gt;Thử nghiệm: prior không liên hợp (tam giác lệch)&lt;/h3&gt;

&lt;p&gt;Với prior không có công thức đóng, lưới vẫn cho posterior chính xác khi đủ mịn.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;grid-explainer&quot; data-lang=&quot;vi&quot; data-prior=&quot;tri&quot; data-k=&quot;8&quot; data-n=&quot;12&quot; data-points=&quot;100&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;6-khai-thác-posterior-thu-được-từ-lưới&quot;&gt;6. Khai thác posterior thu được từ lưới&lt;/h2&gt;

&lt;p&gt;Từ phân phối posterior rời rạc trên lưới, ta có thể tính trực tiếp hầu hết các đại lượng suy luận cần thiết.&lt;/p&gt;

&lt;h3 id=&quot;61-tính-trung-bình-hậu-nghiệm&quot;&gt;6.1. Tính trung bình hậu nghiệm&lt;/h3&gt;

&lt;p&gt;Lấy trung bình có trọng số theo xác suất hậu nghiệm:&lt;/p&gt;

\[E[\theta \mid D] \approx \sum_i \theta_i p(\theta_i \mid D).\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_stat_mean_median_mode.png&quot; alt=&quot;Posterior mean cùng median và mode trên grid&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;62-tính-xác-suất-của-một-khoảng&quot;&gt;6.2. Tính xác suất của một khoảng&lt;/h3&gt;

&lt;p&gt;Chẳng hạn, xác suất:&lt;/p&gt;

\[P(0.5 \le \theta \le 0.8 \mid D)\]

&lt;p&gt;được tính bằng tổng trọng số posterior của tất cả các điểm lưới nằm trong đoạn \([0.5, 0.8]\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_stat_interval_probability.png&quot; alt=&quot;Xác suất posterior của một khoảng trên grid&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;63-tính-khoảng-tin-cậy-bayes-credible-interval&quot;&gt;6.3. Tính khoảng tin cậy Bayes (Credible interval)&lt;/h3&gt;

&lt;p&gt;Ta tính hàm phân phối tích lũy rời rạc bằng cách cộng dồn trọng số trên lưới rồi trích ra các phân vị (quantile) mong muốn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_stat_credible_interval.png&quot; alt=&quot;Credible interval được lấy từ posterior rời rạc&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;64-lấy-mẫu-từ-posterior&quot;&gt;6.4. Lấy mẫu từ posterior&lt;/h3&gt;

&lt;p&gt;Ta có thể lấy mẫu các điểm lưới theo xác suất posterior để phục vụ cho các phép tính hoặc mô phỏng ở bước tiếp theo.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_stat_sampling.png&quot; alt=&quot;Lấy mẫu trực tiếp từ posterior trên grid&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Nhờ cách tiếp cận này, mọi khái niệm suy luận Bayes đều trở nên cụ thể thông qua các phép cộng và phép nhân cơ bản.&lt;/p&gt;

&lt;h2 id=&quot;7-dự-báo-hậu-nghiệm-posterior-predictive-trên-lưới&quot;&gt;7. Dự báo hậu nghiệm (Posterior predictive) trên lưới&lt;/h2&gt;

&lt;p&gt;Sau khi có posterior của tham số trên lưới, ta có thể tính phân phối dự báo cho dữ liệu mới — chẳng hạn dự báo số đơn hàng trong 50 khách tiếp theo từ posterior của tỷ lệ mua hàng — bằng cách lấy trung bình có trọng số các phân phối dự báo điều kiện theo từng điểm lưới:&lt;/p&gt;

\[P(y_{\text{new}} \mid D) = \sum_i P(y_{\text{new}} \mid \theta_i)p(\theta_i \mid D).\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_predictive_distribution.png&quot; alt=&quot;Phân phối posterior predictive lấy từ posterior trên grid&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_predictive_vs_exact.png&quot; alt=&quot;So sánh posterior predictive từ grid với công thức chính xác&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Bước này kết nối trực tiếp suy luận tham số với dự báo thực tế.&lt;/p&gt;

&lt;h2 id=&quot;8-khi-nào-xấp-xỉ-lưới-đặc-biệt-hữu-ích&quot;&gt;8. Khi nào xấp xỉ lưới đặc biệt hữu ích?&lt;/h2&gt;

&lt;h3 id=&quot;81-khi-mới-học-thống-kê-bayes&quot;&gt;8.1. Khi mới học thống kê Bayes&lt;/h3&gt;

&lt;p&gt;Xấp xỉ lưới giúp nhìn rõ từng thành phần — prior, likelihood, posterior, bước chuẩn hóa và dự báo hậu nghiệm — thông qua các trọng số cụ thể trên một tập điểm hữu hạn.&lt;/p&gt;

&lt;h3 id=&quot;82-khi-mô-hình-chỉ-có-1-tham-số&quot;&gt;8.2. Khi mô hình chỉ có 1 tham số&lt;/h3&gt;

&lt;p&gt;Với bài toán một tham số, phương pháp lưới dễ cài đặt, chạy nhanh và thuận tiện để trực quan hóa bằng đồ thị.&lt;/p&gt;

&lt;h3 id=&quot;83-khi-cần-đối-chiếu-kết-quả-cho-mô-hình-nhỏ&quot;&gt;8.3. Khi cần đối chiếu kết quả cho mô hình nhỏ&lt;/h3&gt;

&lt;p&gt;Ngay cả khi sử dụng MCMC về sau, xấp xỉ lưới vẫn là điểm đối chiếu tin cậy cho các mô hình một tham số để kiểm chứng xem thuật toán phức tạp hơn có hoạt động đúng hay không.&lt;/p&gt;

&lt;h2 id=&quot;9-hạn-chế-lớn-nhất-lời-nguyền-số-chiều-curse-of-dimensionality&quot;&gt;9. Hạn chế lớn nhất: lời nguyền số chiều (Curse of dimensionality)&lt;/h2&gt;

&lt;p&gt;Hạn chế nghiêm trọng của xấp xỉ lưới xuất hiện ngay khi số tham số tăng lên. Nếu mỗi chiều tham số dùng 100 điểm lưới, thì:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;1 tham số cần \(100\) điểm,&lt;/li&gt;
  &lt;li&gt;2 tham số cần \(10{,}000\) điểm,&lt;/li&gt;
  &lt;li&gt;3 tham số cần \(1{,}000{,}000\) điểm,&lt;/li&gt;
  &lt;li&gt;4 tham số vọt lên \(100{,}000{,}000\) điểm.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tốc độ tăng theo cấp số mũ này gọi là &lt;strong&gt;lời nguyền số chiều (curse of dimensionality)&lt;/strong&gt;. Vì vậy, xấp xỉ lưới rất hiệu quả cho bài toán 1 tham số, còn chấp nhận được cho một số bài toán 2 tham số nhỏ, nhưng nhanh chóng trở nên bất khả thi ở các mô hình nhiều tham số trong thực tế.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_dimensionality_growth.png&quot; alt=&quot;Số điểm grid tăng bùng nổ theo số chiều tham số&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;10-vị-trí-của-xấp-xỉ-lưới-trong-bức-tranh-tổng-thể&quot;&gt;10. Vị trí của xấp xỉ lưới trong bức tranh tổng thể&lt;/h2&gt;

&lt;p&gt;Các phương pháp tính posterior nằm trên một trục phát triển tự nhiên: &lt;strong&gt;prior liên hợp&lt;/strong&gt; cho lời giải giải tích chính xác và nhanh khi mô hình đủ đơn giản; &lt;strong&gt;xấp xỉ lưới&lt;/strong&gt; cung cấp phương pháp số trực quan và linh hoạt cho các mô hình ít tham số; còn &lt;strong&gt;MCMC&lt;/strong&gt; là công cụ tổng quát dành cho các mô hình phức tạp nhiều chiều. Xấp xỉ lưới đóng vai trò cây cầu giúp ta hiểu rõ lý do cần đến các phương pháp lấy mẫu ở các chương sau.&lt;/p&gt;

&lt;h2 id=&quot;11-những-nhầm-lẫn-phổ-biến&quot;&gt;11. Những nhầm lẫn phổ biến&lt;/h2&gt;

&lt;h3 id=&quot;111-xấp-xỉ-lưới-luôn-cho-kết-quả-chính-xác-tuyệt-đối&quot;&gt;11.1. “Xấp xỉ lưới luôn cho kết quả chính xác tuyệt đối”&lt;/h3&gt;

&lt;p&gt;Không đúng. Đây là phương pháp xấp xỉ; độ chính xác phụ thuộc vào độ mịn của lưới, việc lưới có bao phủ đủ vùng mật độ posterior quan trọng hay không, và số chiều tham số.&lt;/p&gt;

&lt;h3 id=&quot;112-cứ-tăng-số-điểm-lưới-là-giải-quyết-được-mọi-bài-toán&quot;&gt;11.2. “Cứ tăng số điểm lưới là giải quyết được mọi bài toán”&lt;/h3&gt;

&lt;p&gt;Không đúng. Khi số tham số tăng, tổng số điểm lưới tăng theo cấp số mũ khiến chi phí tính toán vượt quá khả năng xử lý rất nhanh.&lt;/p&gt;

&lt;h3 id=&quot;113-xấp-xỉ-lưới-chỉ-là-công-cụ-minh-họa-không-đáng-học&quot;&gt;11.3. “Xấp xỉ lưới chỉ là công cụ minh họa, không đáng học”&lt;/h3&gt;

&lt;p&gt;Ngược lại. Xấp xỉ lưới là công cụ rất hiệu quả để xây dựng trực giác Bayes, hiểu cơ chế hình thành posterior và tạo nền tảng trực tiếp cho MCMC.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Xấp xỉ lưới (grid approximation) ước lượng posterior bằng cách rời rạc hóa không gian tham số thành một lưới điểm hữu hạn.&lt;/strong&gt; Phương pháp này trực quan, dễ cài đặt, không yêu cầu prior liên hợp và đặc biệt phù hợp cho các mô hình ít tham số. Hạn chế cốt lõi của nó là không mở rộng được lên không gian nhiều chiều do lời nguyền số chiều. Nếu prior liên hợp giúp ta hiểu suy luận Bayes bằng giải tích, thì xấp xỉ lưới mở ra cánh cửa sang suy luận Bayes bằng tính toán số.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-năm-bước-thực-hiện-xấp-xỉ-lưới-không-bao-giờ-sai&quot;&gt;Giải thích: Năm bước thực hiện xấp xỉ lưới không bao giờ sai&lt;/h2&gt;

&lt;p&gt;Bất kỳ bài toán Bayes 1 chiều nào cũng giải được bằng xấp xỉ lưới theo đúng 5 bước sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tạo lưới điểm \(\theta_1, \dots, \theta_M\)&lt;/strong&gt; phủ kín miền tham số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh giá prior&lt;/strong&gt; \(p(\theta_j)\) (hoặc \(\log p(\theta_j)\)) tại mỗi điểm lưới.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh giá likelihood&lt;/strong&gt; \(p(y \mid \theta_j)\) (hoặc \(\log p(y \mid \theta_j)\)) tại mỗi điểm lưới.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhân prior với likelihood&lt;/strong&gt; (hoặc cộng trên thang log rồi dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log-sum-exp&lt;/code&gt;) để thu hậu nghiệm chưa chuẩn hóa \(u_j\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa&lt;/strong&gt; \(w_j = u_j / \sum_{m=1}^M u_m\) để thu phân phối hậu nghiệm rời rạc, từ đó tính kỳ vọng \(\sum_j \theta_j w_j\) hoặc rút mẫu trực tiếp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-xấp-xỉ-lưới-5-điểm-với-prior-không-liên-hợp&quot;&gt;Ví dụ tính toán làm từng bước: Xấp xỉ lưới 5 điểm với prior không liên hợp&lt;/h3&gt;

&lt;p&gt;Giả sử ta có prior bậc thang (không liên hợp): tin chắc đồng xu không thể có \(p &amp;lt; 0.5\), tức \(p(\theta) = 0\) nếu \(\theta &amp;lt; 0.5\) và đều nhau nếu \(\theta \ge 0.5\). Ta quan sát \(k = 2\) Ngửa trong \(n = 3\) lần tung (\(L(\theta) \propto \theta^2(1-\theta)\)) trên lưới 5 điểm \(\{0.1, 0.3, 0.5, 0.7, 0.9\}\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Điểm lưới \(\theta_j\)&lt;/th&gt;
      &lt;th&gt;Prior chưa chuẩn hóa&lt;/th&gt;
      &lt;th&gt;Likelihood lõi \(\theta_j^2(1-\theta_j)\)&lt;/th&gt;
      &lt;th&gt;Tích \(u_j\)&lt;/th&gt;
      &lt;th&gt;Hậu nghiệm \(w_j = u_j / 0.353\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(0.1\)&lt;/td&gt;
      &lt;td&gt;\(0\)&lt;/td&gt;
      &lt;td&gt;\(0.009\)&lt;/td&gt;
      &lt;td&gt;\(0.000\)&lt;/td&gt;
      &lt;td&gt;\(0.0000\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(0.3\)&lt;/td&gt;
      &lt;td&gt;\(0\)&lt;/td&gt;
      &lt;td&gt;\(0.063\)&lt;/td&gt;
      &lt;td&gt;\(0.000\)&lt;/td&gt;
      &lt;td&gt;\(0.0000\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(0.5\)&lt;/td&gt;
      &lt;td&gt;\(1\)&lt;/td&gt;
      &lt;td&gt;\(0.125\)&lt;/td&gt;
      &lt;td&gt;\(0.125\)&lt;/td&gt;
      &lt;td&gt;\(0.3541\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(0.7\)&lt;/td&gt;
      &lt;td&gt;\(1\)&lt;/td&gt;
      &lt;td&gt;\(0.147\)&lt;/td&gt;
      &lt;td&gt;\(0.147\)&lt;/td&gt;
      &lt;td&gt;\(0.4164\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(0.9\)&lt;/td&gt;
      &lt;td&gt;\(1\)&lt;/td&gt;
      &lt;td&gt;\(0.081\)&lt;/td&gt;
      &lt;td&gt;\(0.081\)&lt;/td&gt;
      &lt;td&gt;\(0.2295\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Tổng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(0.353\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(1.0000\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Kỳ vọng hậu nghiệm trên lưới 5 điểm là:&lt;/p&gt;

\[\mathbb{E}[\theta \mid y] \approx 0.5(0.3541) + 0.7(0.4164) + 0.9(0.2295) = 0.1771 + 0.2915 + 0.2066 = 0.6752.\]

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Dùng lưới quá thưa (như 5 điểm trên) cho mô hình thật mà không kiểm tra độ hội tụ khi tăng số điểm lưới (ví dụ 200 so với 1.000 điểm), hoặc đặt lưới quá hẹp làm cắt cụt phần đuôi có khối lượng xác suất lớn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu mô hình có \(d = 5\) tham số và ta đặt \(M = 50\) điểm cho mỗi tham số, tổng số điểm phải tính là \(50^5 = 312\,500\,000\) (hơn 312 triệu điểm) — lý do rõ ràng nhất giải thích vì sao ta cần MCMC từ Chương 3 trở đi.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=w4fKaBCX02Q&quot;&gt;Introduction to the elements of Bayesian statistics. Week 3. Video 2. Grid approx. &amp;amp; probability.&lt;/a&gt; — Peter Blenis, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Minh họa cách tính posterior trên lưới điểm và chuẩn hóa bằng tổng, bám sát thuật toán trình bày trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2BhfFLATx8c&quot;&gt;Bayes Week 2, Lecture 1: Grid Approximation&lt;/a&gt; — Kevin James, English. Trình bày thêm một ví dụ xây dựng lưới, nhân prior với likelihood và đọc phân phối rời rạc thu được.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R1vcdhPBlXA&quot;&gt;Statistical Rethinking 2023 - 02 - The Garden of Forking Data&lt;/a&gt; — Richard McElreath, English. Giải thích cách đếm các khả năng sinh dữ liệu, giúp hiểu xấp xỉ lưới như phép rời rạc hóa của quá trình đếm đó.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Hãy giải thích bằng lời vì sao lưới 5 điểm chỉ cho một xấp xỉ thô.&lt;/li&gt;
  &lt;li&gt;Với bài toán một tham số, vì sao xấp xỉ lưới là công cụ học tập rất hiệu quả?&lt;/li&gt;
  &lt;li&gt;Vì sao xấp xỉ lưới gặp khó khăn nghiêm trọng khi mô hình có 4 hoặc 5 tham số?&lt;/li&gt;
  &lt;li&gt;Hãy nêu một ví dụ prior không liên hợp mà xấp xỉ lưới xử lý thuận tiện hơn giải tích.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2-3.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 6.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 3.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Kết thúc Chapter 02. Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter04/&quot;&gt;Chapter 04 - Bayesian Linear Regression&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 2.5: Prior liên hợp và đại số của cập nhật Bayes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_05_conjugate_priors/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_05_conjugate_priors</id>
   <content type="html">&lt;p&gt;Trước khi máy tính và MCMC ra đời, các nhà thống kê Bayes đối mặt với một bức tường toán học khổng lồ: mẫu số \(p(y) = \int p(y \mid \theta) p(\theta)\,d\theta\) của định lý Bayes thường không thể tính được bằng giải tích sơ cấp. Để vượt qua bức tường ấy, Howard Raiffa và Robert Schlaifer (1961) đã hệ thống hóa một ý tưởng tuyệt đẹp: chọn phân phối prior sao cho khi nhân với likelihood, phân phối hậu nghiệm quay về &lt;strong&gt;đúng cùng một họ phân phối&lt;/strong&gt; với prior — gọi là &lt;strong&gt;prior liên hợp (conjugate prior)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Dù ngày nay ta có PyMC và MCMC cho các mô hình tổng quát, việc làm chủ các cặp liên hợp kinh điển (Beta–Binomial, Gamma–Poisson, Normal–Normal) vẫn vô giá: chúng là những ví dụ giải tích trong suốt nhất giúp ta hiểu bản chất phép cập nhật Bayes bằng những phép cộng trừ sơ cấp.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn cần hiểu prior liên hợp (conjugate prior) không phải là “mẹo học thuộc”, mà là những cặp prior–likelihood giúp phép cập nhật Bayes có dạng giải tích rất gọn. Bạn cũng cần nắm được ý nghĩa thực tế của các cặp liên hợp phổ biến, biết khi nào chúng hữu ích và khi nào cần chuyển sang các phương pháp tính toán tổng quát hơn.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ mini.&lt;/strong&gt; Nếu prior cho tỷ lệ qua môn là Beta\((2,2)\) và dữ liệu mới là 7 sinh viên đậu trên 10 người, posterior trở thành Beta\((9,5)\). Ta không phải tìm một họ phân phối mới mà chỉ cần cập nhật hai tham số.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Điều gì làm cho một prior được gọi là “liên hợp” với một likelihood?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-họ-mũ-thống-kê-đủ-và-bốn-cặp-liên-hợp-kinh-điển&quot;&gt;Kiến thức cần nhớ: Họ mũ, Thống kê đủ và Bốn cặp liên hợp kinh điển&lt;/h2&gt;

&lt;p&gt;Tính liên hợp không phải sự trùng hợp ngẫu nhiên mà xuất phát trực tiếp từ cấu trúc toán học của &lt;strong&gt;họ phân phối mũ (Exponential Family)&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cấu trúc lõi (Kernel Matching):&lt;/strong&gt; Một cặp prior–likelihood là liên hợp khi phần phụ thuộc vào \(\theta\) của prior có cùng dạng đại số với phần phụ thuộc vào \(\theta\) của likelihood (nhờ vậy khi nhân lại, ta chỉ cần cộng các số mũ).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật qua Thống kê đủ (Sufficient Statistics):&lt;/strong&gt; Mọi cặp liên hợp đều cập nhật siêu tham số chỉ bằng các thống kê đủ của dữ liệu (như \((n, \sum y_i)\) cho Gamma–Poisson và Normal–Normal, hay \((n, k)\) cho Beta–Binomial) — giúp cập nhật trực tuyến với bộ nhớ \(O(1)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giới hạn và Cầu nối sang MCMC:&lt;/strong&gt; Trong mô hình hồi quy logistic, mô hình hỗn hợp hay mô hình phân cấp nhiều tầng, không tồn tại prior liên hợp cho toàn bộ mô hình. Khi đó ta chuyển sang xấp xỉ lưới (Bài 2.6) và MCMC (Chương 3–4).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mở-đầu-vì-sao-một-số-bài-toán-bayes-có-thể-giải-tay-gọn-gàng&quot;&gt;Mở đầu: vì sao một số bài toán Bayes có thể giải tay gọn gàng?&lt;/h2&gt;

&lt;p&gt;Trong các bài trước, ta đã biết:&lt;/p&gt;

\[P(\theta \mid D) \propto P(D \mid \theta)P(\theta).\]

&lt;p&gt;Về mặt nguyên lý, biểu thức này rất rõ ràng. Tuy nhiên, khi tính toán thực tế, ta phải chuẩn hóa posterior — và tích phân chuẩn hóa thường rất khó giải bằng tay.&lt;/p&gt;

&lt;p&gt;Dù vậy, có một số trường hợp đặc biệt mà khi nhân prior với likelihood, posterior vẫn rơi vào &lt;strong&gt;cùng một họ phân phối&lt;/strong&gt; với prior. Những trường hợp đó gọi là &lt;strong&gt;prior liên hợp (conjugate prior)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Nếu cảm thấy phần này có nhiều công thức, thay vì cố ghi nhớ máy móc, bạn nên đi theo bốn câu hỏi cơ bản:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Tham số chưa biết thực chất là đại lượng gì?&lt;/li&gt;
  &lt;li&gt;Dữ liệu quan sát có dạng như thế nào?&lt;/li&gt;
  &lt;li&gt;Likelihood nào mô tả đúng cơ chế sinh dữ liệu đó?&lt;/li&gt;
  &lt;li&gt;Có họ prior nào đồng dạng về mặt đại số với likelihood để sau khi nhân lại, posterior vẫn thuộc cùng họ phân phối ban đầu không?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Đi theo đúng trình tự này, các cặp liên hợp quen thuộc sẽ xuất hiện rất tự nhiên:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Khi dữ liệu đếm số thành công trong \(n\) phép thử cố định, likelihood là Binomial và prior liên hợp cho xác suất thành công là Beta.&lt;/li&gt;
  &lt;li&gt;Khi dữ liệu đếm số lần thử cho đến khi có thành công đầu tiên, likelihood là Geometric và prior liên hợp vẫn là Beta.&lt;/li&gt;
  &lt;li&gt;Khi dữ liệu là số sự kiện xảy ra theo thời gian hoặc đơn vị phơi nhiễm, likelihood là Poisson và prior liên hợp cho cường độ là Gamma.&lt;/li&gt;
  &lt;li&gt;Khi dữ liệu liên tục dao động quanh một trung bình chưa biết (với phương sai đã biết), ta có cặp Normal–Normal.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Bạn chỉ cần nhận diện mình đang đứng trước bài toán về tỷ lệ, thời gian chờ rời rạc, tốc độ đếm hay trung bình liên tục; phần cập nhật tham số sẽ trở nên dễ theo dõi hơn nhiều.&lt;/p&gt;

&lt;h2 id=&quot;1-prior-liên-hợp-là-gì&quot;&gt;1. Prior liên hợp là gì?&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Ta nói prior \(p(\theta)\) là liên hợp với likelihood \(p(y \mid \theta)\) nếu posterior \(p(\theta \mid y)\) thuộc cùng một họ phân phối với prior.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ví dụ: prior Beta \(\rightarrow\) posterior vẫn là Beta; prior Gamma \(\rightarrow\) posterior vẫn là Gamma; prior Normal \(\rightarrow\) posterior vẫn là Normal.&lt;/p&gt;

&lt;p&gt;Nhờ tính chất này, ta không cần tìm một họ phân phối mới sau mỗi lần cập nhật mà chỉ cần cập nhật các tham số của họ phân phối ban đầu. Biểu thức posterior vì thế ngắn gọn, dễ diễn giải và rất hữu ích để xây dựng trực giác về sự tương tác giữa prior và dữ liệu.&lt;/p&gt;

&lt;p&gt;Trước khi đi sâu, nếu muốn ôn lại vai trò của hàm Gamma, miền tham số của Beta/Gamma/Normal và lưu ý về xấp xỉ Normal, bạn có thể xem lại &lt;a href=&quot;/vi/chapter02/probability-distributions/&quot;&gt;Bài 2.1: Phân phối Xác suất&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;2-trực-giác-vì-sao-tính-liên-hợp-xuất-hiện&quot;&gt;2. Trực giác: vì sao tính liên hợp xuất hiện?&lt;/h2&gt;

&lt;p&gt;Tính liên hợp xuất hiện khi prior và likelihood có “cùng cấu trúc đại số” theo tham số. Chẳng hạn, likelihood Binomial chứa các lũy thừa của \(\theta\) và \(1-\theta\), trong khi prior Beta cũng được cấu tạo từ đúng hai thừa số đó. Khi nhân prior với likelihood, ta không làm đổi dạng hàm mà chỉ cộng các số mũ tương ứng, nên posterior vẫn thuộc họ Beta.&lt;/p&gt;

&lt;p&gt;Nói ngắn gọn: &lt;strong&gt;tính liên hợp (conjugacy) là sự tương thích về cấu trúc đại số giữa prior và likelihood.&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-betabinomial-cặp-liên-hợp-nền-tảng&quot;&gt;3. Beta–Binomial: cặp liên hợp nền tảng&lt;/h2&gt;

&lt;h3 id=&quot;31-mô-hình-và-phép-cập-nhật&quot;&gt;3.1. Mô hình và phép cập nhật&lt;/h3&gt;

&lt;p&gt;Một giảng viên muốn suy luận tỷ lệ sinh viên qua môn \(\theta\) dựa trên lớp 40 sinh viên có 31 em qua môn. Nếu xem mỗi sinh viên là một phép thử Bernoulli độc lập, ta có:&lt;/p&gt;

\[Y \mid \theta \sim \text{Binomial}(n,\theta).\]

&lt;p&gt;Với prior:&lt;/p&gt;

\[\theta \sim \text{Beta}(\alpha,\beta),\]

&lt;p&gt;posterior tương ứng là:&lt;/p&gt;

\[\theta \mid y \sim \text{Beta}(\alpha + y,\beta + n - y).\]

&lt;p&gt;Kiểm tra nhanh phần phụ thuộc vào \(\theta\):&lt;/p&gt;

\[p(\theta)\propto \theta^{\alpha-1}(1-\theta)^{\beta-1}\]

&lt;p&gt;và&lt;/p&gt;

\[p(y\mid \theta)\propto \theta^y(1-\theta)^{n-y}.\]

&lt;p&gt;Nhân hai biểu thức lại:&lt;/p&gt;

\[p(\theta\mid y)\propto p(y\mid \theta)p(\theta)
\propto \theta^{\alpha+y-1}(1-\theta)^{\beta+n-y-1},\]

&lt;p&gt;suy ra:&lt;/p&gt;

\[\theta\mid y\sim \text{Beta}(\alpha+y,\beta+n-y).\]

&lt;p&gt;Nếu dữ liệu được viết ở dạng từng quan sát Bernoulli \(y_1,\dots,y_n\) và đặt \(s=\sum_{i=1}^n y_i\) thì:&lt;/p&gt;

\[\theta\mid y_{1:n}\sim \text{Beta}(\alpha+s,\beta+n-s).\]

&lt;p&gt;Trung bình hậu nghiệm là:&lt;/p&gt;

\[E[\theta\mid y]=\frac{\alpha+y}{\alpha+\beta+n}.\]

&lt;h3 id=&quot;32-ý-nghĩa-trực-giác&quot;&gt;3.2. Ý nghĩa trực giác&lt;/h3&gt;

&lt;p&gt;Với prior Beta\((2,2)\) và dữ liệu 31/40, posterior trở thành Beta\((33,11)\). Có thể hiểu prior như đang mang sẵn một số “lần thành công giả định” (\(\alpha\)) và “lần thất bại giả định” (\(\beta\)); khi dữ liệu thực xuất hiện, ta chỉ cần cộng số thành công và thất bại quan sát được vào hai tham số này.&lt;/p&gt;

&lt;h3 id=&quot;321-ví-dụ-cập-nhật-tuần-tự&quot;&gt;3.2.1. Ví dụ cập nhật tuần tự&lt;/h3&gt;

&lt;p&gt;Tính liên hợp cũng cho thấy sự nhất quán của cập nhật từng đợt. Bắt đầu từ prior Beta\((2,2)\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Sau đợt 1 (3 sinh viên qua môn trên 4 em), posterior là Beta\((5,3)\).&lt;/li&gt;
  &lt;li&gt;Sau đợt 2 (thêm 28 sinh viên qua môn trên 36 em), posterior mới là Beta\((33,11)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Kết quả cuối cùng trùng khớp hoàn toàn với việc cập nhật một lần bằng toàn bộ dữ liệu 31/40.&lt;/p&gt;

&lt;h3 id=&quot;33-các-bối-cảnh-ứng-dụng-phổ-biến&quot;&gt;3.3. Các bối cảnh ứng dụng phổ biến&lt;/h3&gt;

&lt;p&gt;Cặp Beta–Binomial phù hợp với nhiều bài toán thực tế như tỷ lệ mua hàng sau khi xem quảng cáo, tỷ lệ hoàn thành khóa học, tỷ lệ đáp ứng điều trị, tỷ lệ mở email hay tỷ lệ sản phẩm lỗi trong kiểm định chất lượng — nơi dữ liệu là số thành công trong một số lần thử xác định trước.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-betabinomial-qua-từng-lần-tung&quot;&gt;Thử nghiệm: Beta–Binomial qua từng lần tung&lt;/h3&gt;

&lt;p&gt;Tung từng lần, xem Beta(a + k, b + n − k) thay đổi, khoảng 95% và đối chiếu bằng lưới.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;conjugate-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;betabinom&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-betageometric-khi-dữ-liệu-là-số-lần-thử-đến-thành-công-đầu-tiên&quot;&gt;4. Beta–Geometric: khi dữ liệu là số lần thử đến thành công đầu tiên&lt;/h2&gt;

&lt;h3 id=&quot;41-mô-hình-và-phép-cập-nhật&quot;&gt;4.1. Mô hình và phép cập nhật&lt;/h3&gt;

&lt;p&gt;Giả sử Nam thi chứng chỉ tiếng Anh cho tới khi đậu và ta muốn suy luận xác suất đậu mỗi lần thi \(\theta\). Nếu Nam đậu đúng ở lần thứ ba, dữ liệu không phải “3 lần thi có 1 lần đậu” theo kiểu Binomial, mà là chuỗi có thứ tự gồm 2 lần trượt liên tiếp rồi đến 1 lần đậu ở lần thứ ba.&lt;/p&gt;

&lt;p&gt;Theo quy ước phân phối Geometric đếm tổng số lần thử cho đến thành công đầu tiên:&lt;/p&gt;

\[Y \mid \theta \sim \text{Geometric}(\theta),\]

&lt;p&gt;với likelihood:&lt;/p&gt;

\[P(Y=y \mid \theta) = \theta(1-\theta)^{y-1}.\]

&lt;p&gt;Với prior:&lt;/p&gt;

\[\theta \sim \text{Beta}(\alpha,\beta),\]

&lt;p&gt;posterior là:&lt;/p&gt;

\[\theta \mid y \sim \text{Beta}(\alpha + 1,\beta + y - 1).\]

&lt;p&gt;Thật vậy, kết hợp:&lt;/p&gt;

\[p(y\mid \theta)=\theta(1-\theta)^{y-1}\propto \theta^1(1-\theta)^{y-1}\]

&lt;p&gt;và&lt;/p&gt;

\[p(\theta)\propto \theta^{\alpha-1}(1-\theta)^{\beta-1},\]

&lt;p&gt;ta thu được:&lt;/p&gt;

\[p(\theta\mid y)\propto \theta^{\alpha}(1-\theta)^{\beta+y-2},\]

&lt;p&gt;nên:&lt;/p&gt;

\[\theta\mid y\sim \text{Beta}(\alpha+1,\beta+y-1).\]

&lt;p&gt;Nếu có \(m\) quan sát độc lập \(y_1,\dots,y_m\) thì:&lt;/p&gt;

\[p(y_{1:m}\mid \theta)=\prod_{i=1}^m \theta(1-\theta)^{y_i-1}
=\theta^m(1-\theta)^{\sum_{i=1}^m y_i-m},\]

&lt;p&gt;suy ra posterior là:&lt;/p&gt;

\[\theta\mid y_{1:m}\sim \text{Beta}\left(\alpha+m,\beta+\sum_{i=1}^m y_i-m\right),\]

&lt;p&gt;với trung bình hậu nghiệm:&lt;/p&gt;

\[E[\theta\mid y_{1:m}]=\frac{\alpha+m}{\alpha+\beta+\sum_{i=1}^m y_i}.\]

&lt;h3 id=&quot;42-vì-sao-vẫn-giữ-được-tính-liên-hợp&quot;&gt;4.2. Vì sao vẫn giữ được tính liên hợp?&lt;/h3&gt;

&lt;p&gt;Likelihood Geometric vẫn gồm hai thừa số quen thuộc:&lt;/p&gt;

\[\theta^1(1-\theta)^{y-1}.\]

&lt;p&gt;Khi nhân với hạt nhân của prior Beta:&lt;/p&gt;

\[\theta^{\alpha-1}(1-\theta)^{\beta-1},\]

&lt;p&gt;ta chỉ cộng số mũ của \(\theta\) và \(1-\theta\), nên posterior vẫn thuộc họ Beta.&lt;/p&gt;

&lt;h3 id=&quot;43-cách-đọc-trực-giác&quot;&gt;4.3. Cách đọc trực giác&lt;/h3&gt;

&lt;p&gt;Với quan sát “đậu ở lần thứ ba”, dữ liệu cung cấp đúng 1 lần thành công và 2 lần thất bại xảy ra trước đó. Vì vậy, Beta–Geometric rất phù hợp cho các tình huống như thi cho đến khi đậu, chờ đến khách hàng mua đầu tiên, hay đếm số lần thử trước khi hệ thống vận hành thành công lần đầu.&lt;/p&gt;

&lt;h3 id=&quot;44-phân-biệt-betageometric-và-betabinomial&quot;&gt;4.4. Phân biệt Beta–Geometric và Beta–Binomial&lt;/h3&gt;

&lt;p&gt;Binomial trả lời câu hỏi “trong \(n\) lần thử cố định, có bao nhiêu lần thành công?”, còn Geometric trả lời câu hỏi “cần đến lần thử thứ mấy mới xuất hiện thành công đầu tiên?”. Hai mô hình khác nhau về thiết kế thí nghiệm và cơ chế sinh dữ liệu, dù cùng dùng prior Beta vì đều xây dựng trên xác suất thành công và thất bại.&lt;/p&gt;

&lt;h2 id=&quot;5-gammapoisson-khi-dữ-liệu-là-số-đếm-theo-thời-gian&quot;&gt;5. Gamma–Poisson: khi dữ liệu là số đếm theo thời gian&lt;/h2&gt;

&lt;h3 id=&quot;51-mô-hình-và-phép-cập-nhật&quot;&gt;5.1. Mô hình và phép cập nhật&lt;/h3&gt;

&lt;p&gt;Một tổng đài muốn suy luận số cuộc gọi trung bình mỗi giờ \(\lambda\). Trong 8 giờ gần nhất, số cuộc gọi quan sát được lần lượt là:&lt;/p&gt;

\[7, 9, 8, 6, 10, 8, 11, 7.\]

&lt;p&gt;Nếu mô hình hóa số cuộc gọi mỗi giờ bằng Poisson:&lt;/p&gt;

\[Y_i \mid \lambda \sim \text{Poisson}(\lambda),\]

&lt;p&gt;và đặt prior Gamma theo tham số hóa shape–rate:&lt;/p&gt;

\[\lambda \sim \text{Gamma}(\alpha,\beta),\]

&lt;p&gt;thì posterior là:&lt;/p&gt;

\[\lambda \mid y_{1:n} \sim \text{Gamma}\left(\alpha + \sum_i y_i,\beta + n\right).\]

&lt;p&gt;Thật vậy, prior Gamma có hạt nhân:&lt;/p&gt;

\[p(\lambda)\propto \lambda^{\alpha-1}e^{-\beta\lambda},\]

&lt;p&gt;còn likelihood Poisson cho \(n\) quan sát là:&lt;/p&gt;

\[p(y_{1:n}\mid \lambda)=\prod_{i=1}^n \frac{e^{-\lambda}\lambda^{y_i}}{y_i!}
\propto \lambda^{\sum_{i=1}^n y_i}e^{-n\lambda}.\]

&lt;p&gt;Nhân lại ta được:&lt;/p&gt;

\[p(\lambda\mid y_{1:n})\propto p(y_{1:n}\mid \lambda)p(\lambda)
\propto \lambda^{\alpha+\sum_i y_i-1}e^{-(\beta+n)\lambda},\]

&lt;p&gt;nên:&lt;/p&gt;

\[\lambda\mid y_{1:n}\sim \text{Gamma}\left(\alpha+\sum_i y_i,\beta+n\right),\]

&lt;p&gt;với trung bình hậu nghiệm:&lt;/p&gt;

\[E[\lambda\mid y]=\frac{\alpha+\sum_i y_i}{\beta+n}.\]

&lt;p&gt;Trường hợp tổng quát khi mỗi quan sát có mức phơi nhiễm \(t_i\) và \(Y_i\mid \lambda \sim \text{Poisson}(t_i\lambda)\), ta thay \(n\) bằng tổng mức phơi nhiễm:&lt;/p&gt;

\[\lambda\mid y_{1:n}\sim \text{Gamma}\left(\alpha+\sum_i y_i,\beta+\sum_i t_i\right).\]

&lt;h3 id=&quot;52-ý-nghĩa-trực-giác&quot;&gt;5.2. Ý nghĩa trực giác&lt;/h3&gt;

&lt;p&gt;Trong cặp Gamma–Poisson, tổng số sự kiện quan sát được cộng vào tham số hình dạng (shape), còn số khoảng thời gian hoặc tổng mức phơi nhiễm cộng vào tham số tốc độ (rate). Cách cập nhật này phản ánh trực tiếp cả cường độ sự kiện lẫn thời lượng theo dõi.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_gamma_poisson_prior_posterior.png&quot; alt=&quot;Prior Gamma và posterior sau khi thấy dữ liệu đếm&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_gamma_poisson_posterior_predictive.png&quot; alt=&quot;Posterior predictive trong mô hình Gamma-Poisson&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_gamma_poisson_sequential_updates.png&quot; alt=&quot;Cập nhật tuần tự trong Gamma-Poisson&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;53-các-bối-cảnh-ứng-dụng&quot;&gt;5.3. Các bối cảnh ứng dụng&lt;/h3&gt;

&lt;p&gt;Gamma–Poisson thường dùng cho số lỗi hệ thống mỗi ngày, số bệnh nhân nhập viện mỗi ca trực, số đơn hàng mỗi giờ, số sinh viên nghỉ học mỗi tuần hoặc số sự cố an ninh mạng mỗi tháng — nói chung là các bài toán đếm sự kiện trên một đơn vị thời gian hoặc phơi nhiễm.&lt;/p&gt;

&lt;h3 id=&quot;54-quy-tắc-nhớ-nhanh&quot;&gt;5.4. Quy tắc nhớ nhanh&lt;/h3&gt;

&lt;p&gt;Tham số shape hậu nghiệm bằng shape tiền nghiệm cộng tổng số sự kiện quan sát được; tham số rate hậu nghiệm bằng rate tiền nghiệm cộng tổng số khoảng thời gian (hoặc đơn vị phơi nhiễm) đã theo dõi.&lt;/p&gt;

&lt;h3 id=&quot;55-ví-dụ-cập-nhật-số-sự-cố-mất-điện&quot;&gt;5.5. Ví dụ: cập nhật số sự cố mất điện&lt;/h3&gt;

&lt;p&gt;Một trạm điện theo dõi số sự cố mất điện hằng tuần với mô hình:&lt;/p&gt;

\[Y_i\mid\lambda \sim \text{Poisson}(\lambda),\quad i=1,\dots,6.\]

&lt;p&gt;Prior kỹ thuật ban đầu (shape–rate) là:&lt;/p&gt;

\[\lambda \sim \text{Gamma}(\alpha_0=4,\beta_0=2),\]

&lt;p&gt;ứng với trung bình tiền nghiệm \(E[\lambda]=2\) sự cố/tuần. Sau 6 tuần, tổng số sự cố ghi nhận là:&lt;/p&gt;

\[\sum_{i=1}^6 y_i = 18.\]

&lt;p&gt;Posterior là:&lt;/p&gt;

\[\lambda\mid y_{1:6}\sim \text{Gamma}(\alpha_0+\sum y_i,\beta_0+n)
=\text{Gamma}(22,8),\]

&lt;p&gt;với trung bình hậu nghiệm:&lt;/p&gt;

\[E[\lambda\mid y]=\frac{22}{8}=2.75.\]

&lt;p&gt;Như vậy, dữ liệu mới kéo ước lượng cường độ sự cố trung bình từ 2 lên 2.75 sự cố/tuần.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-gammapoisson-qua-từng-quan-sát&quot;&gt;Thử nghiệm: Gamma–Poisson qua từng quan sát&lt;/h3&gt;

&lt;p&gt;Prior Gamma trên tốc độ λ, cập nhật sau mỗi khoảng quan sát.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;conjugate-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;gammapoisson&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;6-normalnormal-khi-dữ-liệu-liên-tục-dao-động-quanh-một-trung-bình&quot;&gt;6. Normal–Normal: khi dữ liệu liên tục dao động quanh một trung bình&lt;/h2&gt;

&lt;h3 id=&quot;61-mô-hình-và-phép-cập-nhật&quot;&gt;6.1. Mô hình và phép cập nhật&lt;/h3&gt;

&lt;p&gt;Giả sử bạn muốn suy luận chiều cao trung bình \(\mu\) của một nhóm sinh viên, với độ lệch chuẩn quan sát \(\sigma\) đã biết:&lt;/p&gt;

\[Y_i \mid \mu \sim \mathcal{N}(\mu,\sigma^2).\]

&lt;p&gt;Nếu prior cho \(\mu\) cũng là phân phối Normal:&lt;/p&gt;

\[\mu \sim \mathcal{N}(\mu_0,\tau_0^2),\]

&lt;p&gt;thì posterior cho \(\mu\) vẫn là phân phối Normal. Cụ thể, phần hạt nhân của likelihood theo \(\mu\) là:&lt;/p&gt;

\[p(y_{1:n}\mid \mu)\propto \exp\left(-\frac{1}{2\sigma^2}\sum_{i=1}^n (y_i-\mu)^2\right)
\propto \exp\left(-\frac{n}{2\sigma^2}(\mu-\bar y)^2\right),\]

&lt;p&gt;trong đó:&lt;/p&gt;

\[\bar y=\frac{1}{n}\sum_{i=1}^n y_i.\]

&lt;p&gt;Prior Normal có hạt nhân:&lt;/p&gt;

\[p(\mu)\propto \exp\left(-\frac{(\mu-\mu_0)^2}{2\tau_0^2}\right).\]

&lt;p&gt;Nhân prior với likelihood và nhóm bình phương hoàn chỉnh theo \(\mu\), ta thu được:&lt;/p&gt;

\[\mu\mid y_{1:n}\sim \mathcal{N}(\mu_n,\tau_n^2),\]

&lt;p&gt;với:&lt;/p&gt;

\[\tau_n^2=\left(\frac{1}{\tau_0^2}+\frac{n}{\sigma^2}\right)^{-1}\]

&lt;p&gt;và&lt;/p&gt;

\[\mu_n=\tau_n^2\left(\frac{\mu_0}{\tau_0^2}+\frac{n\bar y}{\sigma^2}\right)
=\frac{\mu_0/\tau_0^2+n\bar y/\sigma^2}{1/\tau_0^2+n/\sigma^2}.\]

&lt;p&gt;Nói cách khác:&lt;/p&gt;

\[E[\mu\mid y]=\mu_n,\qquad \mathrm{Var}(\mu\mid y)=\tau_n^2.\]

&lt;h3 id=&quot;62-ý-nghĩa-trực-giác&quot;&gt;6.2. Ý nghĩa trực giác&lt;/h3&gt;

&lt;p&gt;Trung bình hậu nghiệm trong mô hình Normal–Normal là &lt;strong&gt;trung bình có trọng số&lt;/strong&gt; giữa trung bình tiền nghiệm \(\mu_0\) và trung bình mẫu \(\bar y\), với trọng số tỉ lệ thuận với độ chính xác (nghịch đảo phương sai) của từng nguồn thông tin. Nguồn nào chính xác hơn (prior hẹp hơn, cỡ mẫu lớn hơn, hoặc nhiễu quan sát nhỏ hơn) sẽ chi phối mạnh hơn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_normal_normal_prior_posterior.png&quot; alt=&quot;Prior Normal và posterior sau khi kết hợp với dữ liệu&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_normal_normal_sample_size_effect.png&quot; alt=&quot;Ảnh hưởng của kích thước mẫu trong Normal-Normal&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_normal_normal_prior_data_weights.png&quot; alt=&quot;Trọng số tương đối của prior và dữ liệu trong Normal-Normal&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;63-các-bối-cảnh-ứng-dụng&quot;&gt;6.3. Các bối cảnh ứng dụng&lt;/h3&gt;

&lt;p&gt;Normal–Normal thường gặp khi suy luận chiều cao trung bình, điểm trung bình của lớp học, thời gian xử lý trung bình của một quy trình, hoặc sai số đo đạc của cảm biến quanh một giá trị thực chưa biết.&lt;/p&gt;

&lt;h3 id=&quot;64-cách-nhớ-ngắn-gọn&quot;&gt;6.4. Cách nhớ ngắn gọn&lt;/h3&gt;

&lt;p&gt;Trong mô hình Normal–Normal, trung bình hậu nghiệm luôn dịch về phía nguồn thông tin có độ chính xác cao hơn, còn phương sai hậu nghiệm co nhỏ lại khi cỡ mẫu tăng hoặc nhiễu quan sát giảm.&lt;/p&gt;

&lt;h3 id=&quot;65-ví-dụ-ước-lượng-bayes-và-rủi-ro-hậu-nghiệm-trong-normalnormal&quot;&gt;6.5. Ví dụ: ước lượng Bayes và rủi ro hậu nghiệm trong Normal–Normal&lt;/h3&gt;

&lt;p&gt;Giả sử cần suy luận thời gian xử lý hồ sơ trung bình \(\mu\) (tính bằng phút), với phương sai quan sát đã biết:&lt;/p&gt;

\[Y_i\mid\mu \sim \mathcal{N}(\mu,\sigma^2),\quad \sigma^2=25.\]

&lt;p&gt;Prior từ chuyên gia:&lt;/p&gt;

\[\mu\sim \mathcal{N}(\mu_0=50,\tau_0^2=100).\]

&lt;p&gt;Quan sát \(n=16\) hồ sơ cho trung bình mẫu \(\bar y=55\). Khi đó:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Phương sai hậu nghiệm:&lt;/li&gt;
&lt;/ul&gt;

\[\tau_n^2=\left(\frac{1}{\tau_0^2}+\frac{n}{\sigma^2}\right)^{-1}
=\left(\frac{1}{100}+\frac{16}{25}\right)^{-1}\approx 1.538.\]

&lt;ul&gt;
  &lt;li&gt;Trung bình hậu nghiệm:&lt;/li&gt;
&lt;/ul&gt;

\[\mu_n=\tau_n^2\left(\frac{\mu_0}{\tau_0^2}+\frac{n\bar y}{\sigma^2}\right)
\approx 54.92.\]

&lt;p&gt;Vậy:&lt;/p&gt;

\[\mu\mid y \sim \mathcal{N}(54.92,1.538).\]

&lt;p&gt;Dưới hàm tổn thất bình phương, ước lượng Bayes tối ưu là trung bình hậu nghiệm:&lt;/p&gt;

\[\hat\mu_{Bayes}=E[\mu\mid y]=54.92,\]

&lt;p&gt;và rủi ro hậu nghiệm (posterior risk) tại ước lượng này bằng chính phương sai hậu nghiệm:&lt;/p&gt;

\[R(\hat\mu_{Bayes})=E\left[(\mu-\hat\mu_{Bayes})^2\mid y\right]=\mathrm{Var}(\mu\mid y)=1.538.\]

&lt;p&gt;So với prior ban đầu, dữ liệu đã kéo ước lượng trung tâm về sát 55 và thu hẹp mạnh độ bất định hậu nghiệm.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-normalnormal-và-trọng-số-theo-độ-chính-xác&quot;&gt;Thử nghiệm: Normal–Normal và trọng số theo độ chính xác&lt;/h3&gt;

&lt;p&gt;Kéo μ₀, τ₀, σ để thấy posterior là trung bình có trọng số giữa prior và dữ liệu.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;conjugate-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;normalnormal&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;video-ngắn-phép-màu-3-cặp-liên-hợp-kinh-điển-cập-nhật-hậu-nghiệm-chỉ-bằng-phép-cộng&quot;&gt;Video ngắn: Phép màu 3 Cặp Liên hợp Kinh điển: Cập nhật Hậu nghiệm chỉ bằng Phép CỘNG!&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch02-05a-conjugate-trio-live.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 23 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): biến đổi trực tiếp cả 3 cặp Beta–Binomial (cộng số đếm), Gamma–Poisson (cộng tổng sự cố &amp;amp; thời gian) và Normal–Normal (cộng độ chính xác τ = 1/σ²).&lt;/p&gt;

&lt;h2 id=&quot;7-cập-nhật-tuần-tự-trong-mô-hình-liên-hợp&quot;&gt;7. Cập nhật tuần tự trong mô hình liên hợp&lt;/h2&gt;

&lt;p&gt;Một lợi ích thiết thực của tính liên hợp là khả năng cập nhật tuần tự rất gọn. Chẳng hạn, khi theo dõi tỷ lệ nhấp quảng cáo hằng ngày bằng Beta–Binomial, bạn chỉ cần lấy posterior ngày hôm qua làm prior cho hôm nay rồi cộng thêm số lượt thành công và thất bại mới. Tương tự với Gamma–Poisson, thông tin mới được hấp thụ ngay qua phép cộng tham số — rất phù hợp với các hệ thống giám sát vận hành và bảng điều khiển thời gian thực.&lt;/p&gt;

&lt;h2 id=&quot;8-giới-hạn-của-prior-liên-hợp&quot;&gt;8. Giới hạn của prior liên hợp&lt;/h2&gt;

&lt;p&gt;Ta không nên chọn prior chỉ vì tính liên hợp nếu lựa chọn đó phản ánh kém kiến thức thực tế, làm mất cấu trúc quan trọng của bài toán, hoặc khi mô hình có nhiều tầng và nhiều tham số phụ thuộc lẫn nhau (chẳng hạn prior hỗn hợp hai đỉnh hoặc tham số bị ràng buộc miền phức tạp).&lt;/p&gt;

&lt;p&gt;Một điểm thường bị bỏ qua là &lt;strong&gt;miền xác định (support) của tham số&lt;/strong&gt;. Ngay cả khi phần biểu thức đại số trông quen thuộc, posterior vẫn có thể không rơi vào một họ phân phối chuẩn nếu miền giá trị bị chặn. Ví dụ, nếu tham số \(\theta\) bị giới hạn trong \([0,1]\) nhưng likelihood có dạng Poisson, mật độ chưa chuẩn hóa sẽ có dạng:&lt;/p&gt;

\[\theta^{y+1}e^{-\theta}, \qquad 0 \le \theta \le 1.\]

&lt;p&gt;Biểu thức này vẫn hoàn toàn hợp lệ cho suy luận Bayes, nhưng không còn thuộc một họ liên hợp dạng đóng quen thuộc như Beta–Binomial hay Gamma–Poisson. Do đó, tính liên hợp đòi hỏi cả sự tương thích đại số lẫn sự khớp nhau về miền giá trị của tham số.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_conjugate_limit_truncated_prior.png&quot; alt=&quot;Prior liên hợp có thể biểu diễn kém khi prior lý tưởng bị chặn miền&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_conjugate_limit_mixture_prior.png&quot; alt=&quot;Mixture prior là ví dụ điển hình khiến conjugate prior trở nên gượng ép&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Khi bài toán không còn liên hợp, ta chuyển sang xấp xỉ lưới (grid approximation) cho mô hình rất nhỏ hoặc MCMC cho các mô hình tổng quát hơn.&lt;/p&gt;

&lt;h2 id=&quot;9-chọn-cặp-liên-hợp-theo-bối-cảnh-dữ-liệu&quot;&gt;9. Chọn cặp liên hợp theo bối cảnh dữ liệu&lt;/h2&gt;

&lt;p&gt;Thay vì học thuộc bảng công thức, bạn nên gắn mỗi cặp với câu chuyện dữ liệu tương ứng: xác suất thành công trong \(n\) phép thử cố định dẫn tới Beta–Binomial; số lần thử cho đến thành công đầu tiên dẫn tới Beta–Geometric; cường độ sự kiện đếm theo thời gian dẫn tới Gamma–Poisson; và trung bình của dữ liệu liên tục dẫn tới Normal–Normal.&lt;/p&gt;

&lt;h2 id=&quot;10-những-nhầm-lẫn-phổ-biến&quot;&gt;10. Những nhầm lẫn phổ biến&lt;/h2&gt;

&lt;h3 id=&quot;101-prior-liên-hợp-luôn-là-prior-tốt-nhất&quot;&gt;10.1. “Prior liên hợp luôn là prior tốt nhất”&lt;/h3&gt;

&lt;p&gt;Không đúng. Nó chỉ là lựa chọn thuận tiện về mặt tính toán.&lt;/p&gt;

&lt;h3 id=&quot;102-chỉ-cần-học-thuộc-công-thức-là-đủ&quot;&gt;10.2. “Chỉ cần học thuộc công thức là đủ”&lt;/h3&gt;

&lt;p&gt;Không đúng. Nếu không hiểu cơ chế sinh dữ liệu và ý nghĩa của tham số, ta rất dễ áp dụng sai mô hình.&lt;/p&gt;

&lt;h3 id=&quot;103-đã-có-mcmc-thì-không-cần-học-prior-liên-hợp&quot;&gt;10.3. “Đã có MCMC thì không cần học prior liên hợp”&lt;/h3&gt;

&lt;p&gt;Không đúng. Prior liên hợp vẫn là nền tảng xây dựng trực giác về cập nhật Bayes và vẫn được dùng rộng rãi trong nhiều hệ thống cần độ trễ thấp.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Prior liên hợp là prior đảm bảo posterior thuộc cùng một họ phân phối sau khi cập nhật.&lt;/strong&gt; Nhờ tính chất này, các bài toán cơ bản có thể giải tay gọn gàng, dễ diễn giải và cập nhật tuần tự nhanh chóng. Bốn cặp nền tảng cần nắm gồm Beta–Binomial, Beta–Geometric, Gamma–Poisson và Normal–Normal. Tuy nhiên, cần luôn ghi nhớ rằng sự tiện lợi về đại số không đồng nghĩa với mô hình tốt nhất: khi prior liên hợp không còn phản ánh đúng thực tế, ta nên chuyển sang các phương pháp tính toán linh hoạt hơn.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-công-thức-cập-nhật-3-cặp-liên-hợp-cốt-lõi-và-ví-dụ-gammapoisson&quot;&gt;Giải thích: Công thức cập nhật 3 cặp liên hợp cốt lõi và ví dụ Gamma–Poisson&lt;/h2&gt;

&lt;p&gt;Bất cứ khi nào nhận ra bài toán thuộc họ liên hợp, bạn chỉ cần làm đúng 3 bước: (1) xác định cặp likelihood–prior khớp miền, (2) tính thống kê đủ từ dữ liệu, và (3) cộng trực tiếp vào siêu tham số của prior:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Dữ liệu / Likelihood&lt;/th&gt;
      &lt;th&gt;Prior liên hợp&lt;/th&gt;
      &lt;th&gt;Thống kê đủ&lt;/th&gt;
      &lt;th&gt;Công thức cập nhật Hậu nghiệm&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Nhị phân: \(\text{Binomial}(n, p)\)&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(\alpha, \beta)\)&lt;/td&gt;
      &lt;td&gt;\((n, k)\)&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(\alpha + k,\; \beta + n - k)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Đếm sự kiện: \(\text{Poisson}(\lambda)\)&lt;/td&gt;
      &lt;td&gt;\(\text{Gamma}(\alpha, \beta)\) (rate)&lt;/td&gt;
      &lt;td&gt;\((n, \sum y_i)\)&lt;/td&gt;
      &lt;td&gt;\(\text{Gamma}\!\left(\alpha + \sum y_i,\; \beta + n\right)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Liên tục (biết \(\sigma^2\)): \(\mathcal{N}(\mu, \sigma^2)\)&lt;/td&gt;
      &lt;td&gt;\(\mathcal{N}(\mu_0, \tau_0^2)\)&lt;/td&gt;
      &lt;td&gt;\((n, \bar y)\)&lt;/td&gt;
      &lt;td&gt;Độ chính xác \(\tau_n^{-2} = \tau_0^{-2} + \frac{n}{\sigma^2}\), trung bình \(\mu_n = \tau_n^2\!\left(\frac{\mu_0}{\tau_0^2} + \frac{n\bar y}{\sigma^2}\right)\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-ước-lượng-tốc-độ-lỗi-máy-chủ-bằng-gammapoisson&quot;&gt;Ví dụ tính toán làm từng bước: Ước lượng tốc độ lỗi máy chủ bằng Gamma–Poisson&lt;/h3&gt;

&lt;p&gt;Giả sử số lỗi máy chủ mỗi giờ tuân theo \(\text{Poisson}(\lambda)\). Trước khi nâng cấp hệ thống, đội ngũ đặt prior \(\lambda \sim \text{Gamma}(\alpha = 6, \beta = 2)\) (tương ứng kỳ vọng ban đầu \(\alpha/\beta = 6/2 = 3.0\) lỗi/giờ, dựa trên 2 giờ quan sát giả định). Sau nâng cấp, ta theo dõi \(n = 5\) giờ và ghi nhận số lỗi lần lượt là \(1, 2, 0, 2, 1\) (tổng \(\sum y_i = 6\) lỗi).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật siêu tham số:&lt;/strong&gt;
\(\alpha_{\text{post}} = 6 + 6 = 12, \qquad \beta_{\text{post}} = 2 + 5 = 7.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối hậu nghiệm:&lt;/strong&gt; \(\lambda \mid y \sim \text{Gamma}(12, 7)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kỳ vọng và độ lệch chuẩn hậu nghiệm:&lt;/strong&gt;
\(\mathbb{E}[\lambda \mid y] = \frac{12}{7} \approx 1.714\text{ lỗi/giờ}, \qquad \mathrm{SD}(\lambda \mid y) = \frac{\sqrt{12}}{7} \approx 0.495\text{ lỗi/giờ}.\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Ta thấy kỳ vọng hậu nghiệm \(1.714\) nằm đúng giữa kỳ vọng prior (\(3.0\)) và trung bình mẫu (\(6/5 = 1.2\)), với trọng số \(2/7\) cho prior và \(5/7\) cho dữ liệu: \(\frac{2}{7}(3.0) + \frac{5}{7}(1.2) = \frac{12}{7} \approx 1.714\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhầm lẫn giữa hai cách tham số hóa của phân phối Gamma: &lt;strong&gt;shape–rate&lt;/strong&gt; (\(\alpha, \beta\) với trung bình \(\alpha/\beta\)) và &lt;strong&gt;shape–scale&lt;/strong&gt; (\(\alpha, \theta = 1/\beta\) với trung bình \(\alpha\theta\)). Khi lập trình bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats.gamma&lt;/code&gt;, luôn kiểm tra xem thư viện dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale = 1/beta&lt;/code&gt; hay &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rate = beta&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu theo dõi thêm 3 giờ nữa và không có lỗi nào (\(0, 0, 0\)), ta chỉ cần cập nhật tiếp từ \(\text{Gamma}(12, 7)\) thành \(\text{Gamma}(12 + 0, 7 + 3) = \text{Gamma}(12, 10)\) với kỳ vọng mới giảm xuống \(1.20\) lỗi/giờ.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aPNrhR0dFi8&quot;&gt;What is a conjugate prior?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Giải thích định nghĩa prior liên hợp và lý do posterior giữ nguyên họ phân phối, giúp hiểu bản chất thay vì học thuộc.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=GqSX-8AQL90&quot;&gt;Bayesian Updates and Conjugate Priors&lt;/a&gt; — Steve Brunton, English. Minh họa quá trình cập nhật Bayes trên các cặp liên hợp quen thuộc cùng ý nghĩa thực tế của chúng.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=hKYvZF9wXkk&quot;&gt;20 - Beta conjugate prior to Binomial and Bernoulli likelihoods&lt;/a&gt; — Ox educ, English. Trình bày chi tiết phép cập nhật Beta–Binomial dựa trên số lần thành công và thất bại.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Hãy nêu một ví dụ thực tế phù hợp với cặp Beta–Binomial.&lt;/li&gt;
  &lt;li&gt;Beta–Geometric khác Beta–Binomial ở kiểu dữ liệu nào, dù cả hai cùng sử dụng prior Beta?&lt;/li&gt;
  &lt;li&gt;Vì sao Gamma–Poisson phù hợp với dữ liệu đếm theo thời gian?&lt;/li&gt;
  &lt;li&gt;Trong mô hình Normal–Normal, yếu tố nào quyết định trung bình hậu nghiệm nằm gần trung bình tiền nghiệm hay gần trung bình mẫu hơn?&lt;/li&gt;
  &lt;li&gt;Khi nào bạn không nên dùng prior liên hợp dù biết nó thuận tiện về mặt tính toán?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 2.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 6-7.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2-3.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter02/02_06_grid_approximation/&quot;&gt;2.6 Grid Approximation - Xấp xỉ Lưới&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 2.4: Posterior - Cập nhật Niềm tin với Dữ liệu</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_04_posterior/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_04_posterior</id>
   <content type="html">&lt;p&gt;Mọi bước chuẩn bị trong thống kê Bayes — chọn prior, viết likelihood, tính hoặc mô phỏng tích phân chuẩn hóa — đều hội tụ về một đích đến duy nhất: &lt;strong&gt;phân phối hậu nghiệm (posterior)&lt;/strong&gt; \(p(\theta \mid y)\). Đây không chỉ là “đáp án cuối cùng” của một phép toán, mà là kho chứa toàn bộ tri thức cập nhật về tham số: từ vị trí trung tâm, độ bất định hai phía, xác suất vượt ngưỡng kinh doanh cho đến nền tảng để sinh dự báo tương lai.&lt;/p&gt;

&lt;p&gt;Bài học này hướng dẫn cách đọc trọn vẹn một phân phối hậu nghiệm, trích xuất các tóm tắt hữu ích (mean, median, MAP, credible interval / HDI) và chuyển sang phân phối dự báo hậu nghiệm (&lt;em&gt;posterior predictive&lt;/em&gt;).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn cần nhìn nhận posterior (phân phối hậu nghiệm) như đích đến trung tâm của suy luận Bayes. Bạn cần hiểu cách posterior được hình thành từ prior và likelihood, biết diễn giải posterior qua xác suất và khoảng tin cậy Bayes (credible interval), đồng thời biết vận dụng posterior để trả lời các câu hỏi thực tế thay vì chỉ thực hiện biến đổi đại số.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ mini.&lt;/strong&gt; Bạn bắt đầu với prior cho tỷ lệ qua môn quanh \(60\%\). Sau khi chấm bài, lớp hiện tại có 31 sinh viên qua môn trên 40 người. Posterior là kết quả cập nhật niềm tin ban đầu bằng dữ liệu mới này.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Vì sao posterior thường không trùng hẳn với prior, nhưng cũng không nhất thiết trùng với tỷ lệ quan sát trực tiếp từ dữ liệu?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-giải-phẫu-hậu-nghiệm-khoảng-tin-cậy-bayes-và-dự-báo-hậu-nghiệm&quot;&gt;Kiến thức cần nhớ: Giải phẫu Hậu nghiệm, Khoảng tin cậy Bayes và Dự báo Hậu nghiệm&lt;/h2&gt;

&lt;p&gt;Làm việc chuyên sâu với hậu nghiệm dựa trên ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tóm tắt hậu nghiệm theo hàm mất mát (Point Summaries):&lt;/strong&gt; Trung bình hậu nghiệm (Posterior Mean) tối thiểu hóa sai số bình phương; Trung vị hậu nghiệm (Posterior Median) tối thiểu hóa sai số tuyệt đối; Đỉnh hậu nghiệm (MAP) tương ứng hàm mất mát 0–1. Khi hậu nghiệm lệch mạnh, ba giá trị này có thể khác nhau rõ rệt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng tin cậy Bayes (Equal-Tailed vs. HDI):&lt;/strong&gt; Khoảng hai đuôi đều cắt đều \(\alpha/2\) ở mỗi phía; khoảng mật độ cao nhất (HDI — Highest Density Interval) là khoảng &lt;em&gt;ngắn nhất&lt;/em&gt; chứa \(1-\alpha\) khối lượng xác suất, đặc biệt hữu ích khi hậu nghiệm bị lệch hoặc đa đỉnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối dự báo hậu nghiệm (Posterior Predictive):&lt;/strong&gt; Để dự báo quan sát mới \(\tilde y\), ta không chỉ thay một ước lượng điểm \(\hat\theta\) mà lấy tích phân trên toàn bộ hậu nghiệm: \(p(\tilde y \mid y) = \int p(\tilde y \mid \theta) p(\theta \mid y)\,d\theta\), nhờ đó truyền trọn vẹn cả bất định tham số lẫn nhiễu dữ liệu vào dự báo.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mở-đầu-sau-khi-thấy-dữ-liệu-ta-nên-tin-điều-gì&quot;&gt;Mở đầu: sau khi thấy dữ liệu, ta nên tin điều gì?&lt;/h2&gt;

&lt;p&gt;Giả sử bạn là giảng viên theo dõi tỷ lệ sinh viên qua môn của một lớp mới. Trước khi chấm bài, bạn có một prior dựa trên kinh nghiệm các khóa trước. Khi có kết quả thực tế của lớp hiện tại, bạn không nên giữ nguyên niềm tin cũ, nhưng cũng không nên bỏ qua hoàn toàn kinh nghiệm tích lũy nhiều năm.&lt;/p&gt;

&lt;p&gt;Thống kê Bayes giải quyết bài toán này một cách nhất quán: prior giữ lại kiến thức ban đầu, likelihood đưa bằng chứng dữ liệu mới vào, còn posterior là trạng thái niềm tin sau khi hai nguồn thông tin đó được kết hợp theo quy tắc xác suất.&lt;/p&gt;

&lt;h2 id=&quot;1-posterior-là-gì&quot;&gt;1. Posterior là gì?&lt;/h2&gt;

&lt;p&gt;Posterior là phân phối xác suất của tham số \(\theta\) sau khi đã quan sát dữ liệu \(D\):&lt;/p&gt;

\[P(\theta \mid D).\]

&lt;p&gt;Theo định lý Bayes:&lt;/p&gt;

\[P(\theta \mid D) = \frac{P(D \mid \theta)P(\theta)}{P(D)},\]

&lt;p&gt;hay viết dưới dạng tỉ lệ:&lt;/p&gt;

\[\text{posterior} \propto \text{likelihood} \times \text{prior}.\]

&lt;p&gt;Do đó, một giá trị của \(\theta\) chỉ đạt mật độ posterior cao khi nó vừa được prior xem là khả dĩ vừa được dữ liệu ủng hộ đủ mạnh. Posterior không ưu ái những giá trị chỉ hợp với prior mà lệch xa dữ liệu, và cũng không tự động chạy theo những giá trị chỉ khớp dữ liệu nhưng mâu thuẫn mạnh với kiến thức nền.&lt;/p&gt;

&lt;h2 id=&quot;2-ví-dụ-từng-bước-đồng-xu-7-mặt-ngửa-trong-10-lần-tung&quot;&gt;2. Ví dụ từng bước: đồng xu 7 mặt ngửa trong 10 lần tung&lt;/h2&gt;

&lt;p&gt;Giả sử prior là Beta\((2,2)\) và dữ liệu quan sát là 7 mặt ngửa trong 10 lần tung. Likelihood Binomial có dạng:&lt;/p&gt;

\[P(D \mid \theta) \propto \theta^7(1-\theta)^3.\]

&lt;p&gt;Prior Beta\((2,2)\) có dạng:&lt;/p&gt;

\[P(\theta) \propto \theta^{2-1}(1-\theta)^{2-1}.\]

&lt;p&gt;Nhân hai biểu thức lại:&lt;/p&gt;

\[P(\theta \mid D) \propto \theta^{8}(1-\theta)^4.\]

&lt;p&gt;Đây chính là phần hạt nhân (kernel) của phân phối Beta\((9,5)\), suy ra:&lt;/p&gt;

\[\theta \mid D \sim \text{Beta}(9,5).\]

&lt;p&gt;Điểm đáng chú ý nằm ở ý nghĩa của kết quả: trung bình prior ban đầu là \(0.5\), dữ liệu mới kéo nhận định về phía \(0.7\), và trung bình posterior dịch lên khoảng \(0.643\). Posterior không đứng yên ở prior và cũng không nhảy thẳng tới MLE; nó là sự dung hòa có nguyên tắc giữa hai nguồn thông tin.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/prior_to_posterior.png&quot; alt=&quot;Từ prior sang posterior sau khi thấy dữ liệu&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;21-ví-dụ-liên-tục-thời-gian-chờ-theo-phân-phối-mũ&quot;&gt;2.1. Ví dụ liên tục: thời gian chờ theo phân phối mũ&lt;/h3&gt;

&lt;p&gt;Tiếp nối chuỗi bài toán thời gian chờ từ Bài 2.2 và 2.3 theo quy trình likelihood – prior – posterior:&lt;/p&gt;

\[X_i \mid \lambda \sim \text{Exp}(\lambda), \quad i=1,\dots,n,\]

&lt;p&gt;với \(\lambda&amp;gt;0\) là tốc độ xảy ra sự kiện. Khi đó:&lt;/p&gt;

\[\mathcal{L}(\lambda\mid x_{1:n}) \propto \lambda^n\exp\left(-\lambda\sum_{i=1}^n x_i\right).\]

&lt;p&gt;Đặt prior liên hợp Gamma theo tham số hóa shape–rate:&lt;/p&gt;

\[\lambda \sim \text{Gamma}(\alpha_0,\beta_0),\]

&lt;p&gt;với mật độ tỉ lệ:&lt;/p&gt;

\[p(\lambda) \propto \lambda^{\alpha_0-1}e^{-\beta_0\lambda}.\]

&lt;p&gt;Nhân likelihood với prior:&lt;/p&gt;

\[p(\lambda\mid x_{1:n}) \propto \lambda^{\alpha_0+n-1}
\exp\left[-(\beta_0+\sum x_i)\lambda\right],\]

&lt;p&gt;suy ra:&lt;/p&gt;

\[\lambda\mid x_{1:n} \sim \text{Gamma}(\alpha_0+n,\beta_0+\sum x_i).\]

&lt;p&gt;Giả sử ta chọn \(\alpha_0=2,\beta_0=20\) (trung bình prior \(0.1\) phút\(^{-1}\)) và quan sát 5 cuộc gọi có thời lượng:&lt;/p&gt;

\[x=(8,12,7,15,9),\quad \sum x_i=51.\]

&lt;p&gt;Khi đó posterior là:&lt;/p&gt;

\[\lambda\mid x \sim \text{Gamma}(7,71),\]

&lt;p&gt;với trung bình hậu nghiệm:&lt;/p&gt;

\[E[\lambda\mid x]=\frac{7}{71}\approx 0.0986.\]

&lt;p&gt;Nếu quan tâm đến xác suất thời gian chờ của một cuộc gọi mới vượt quá 10 phút, ta sử dụng phân phối dự báo hậu nghiệm (posterior predictive):&lt;/p&gt;

\[P(X_{new}&amp;gt;t\mid x)=\left(\frac{\beta_{post}}{\beta_{post}+t}\right)^{\alpha_{post}}.\]

&lt;p&gt;Thay \(t=10,\alpha_{post}=7,\beta_{post}=71\):&lt;/p&gt;

\[P(X_{new}&amp;gt;10\mid x)=\left(\frac{71}{81}\right)^7\approx 0.40.\]

&lt;p&gt;Ví dụ này thể hiện trọn vẹn một quy trình Bayes: kết hợp prior ban đầu với dữ liệu mới để cập nhật tham số, rồi dùng posterior trả lời câu hỏi dự báo thực tế.&lt;/p&gt;

&lt;h2 id=&quot;3-cách-đọc-thông-tin-từ-một-posterior&quot;&gt;3. Cách đọc thông tin từ một posterior&lt;/h2&gt;

&lt;p&gt;Khi đánh giá một phân phối hậu nghiệm, bạn nên trả lời lần lượt bốn câu hỏi sau.&lt;/p&gt;

&lt;h3 id=&quot;31-trung-tâm-nằm-ở-đâu&quot;&gt;3.1. Trung tâm nằm ở đâu?&lt;/h3&gt;

&lt;p&gt;Vùng giá trị nào của tham số đang hợp lý nhất sau khi cập nhật? Chẳng hạn, tỷ lệ chuyển đổi tập trung quanh \(4\%\), tỷ lệ qua môn quanh \(78\%\), hay tốc độ cuộc gọi quanh 12 cuộc mỗi giờ.&lt;/p&gt;

&lt;h3 id=&quot;32-phân-phối-rộng-hay-hẹp&quot;&gt;3.2. Phân phối rộng hay hẹp?&lt;/h3&gt;

&lt;p&gt;Posterior hẹp cho thấy dữ liệu đã giúp tăng độ chắc chắn. Ngược lại, posterior còn rộng thường báo hiệu dữ liệu còn ít, chưa đủ phân tách các giả thuyết cạnh tranh, hoặc prior ban đầu khá phân tán.&lt;/p&gt;

&lt;h3 id=&quot;33-phân-phối-có-bị-lệch-không&quot;&gt;3.3. Phân phối có bị lệch không?&lt;/h3&gt;

&lt;p&gt;Posterior không nhất thiết đối xứng; với xác suất gần 0 hoặc gần 1, hoặc với dữ liệu đếm nhỏ, độ lệch thường thể hiện rất rõ.&lt;/p&gt;

&lt;h3 id=&quot;34-phần-đuôi-nói-gì-về-rủi-ro&quot;&gt;3.4. Phần đuôi nói gì về rủi ro?&lt;/h3&gt;

&lt;p&gt;Trong thực hành, câu hỏi quan trọng thường không chỉ là “trung bình bằng bao nhiêu?” mà là xác suất tham số vượt qua một ngưỡng quyết định hoặc rơi vào vùng rủi ro. Những câu hỏi như “xác suất tỷ lệ lỗi vượt \(5\%\) là bao nhiêu?” hay “xác suất hiệu quả điều trị đạt chuẩn tối thiểu là bao nhiêu?” thường mang lại giá trị ra quyết định cao hơn nhiều so với một con số trung bình đơn lẻ.&lt;/p&gt;

&lt;h2 id=&quot;4-lợi-thế-của-posterior-so-với-ước-lượng-điểm&quot;&gt;4. Lợi thế của posterior so với ước lượng điểm&lt;/h2&gt;

&lt;p&gt;Với posterior, ta không dừng ở phát biểu “ước lượng là \(0.64\)”, mà có thể trả lời các câu hỏi giàu thông tin hơn nhiều: xác suất \(\theta &amp;gt; 0.5\) lớn đến đâu, khoảng nào chứa phần lớn khối lượng xác suất hậu nghiệm, hay dữ liệu tương lai sẽ phân bố như thế nào.&lt;/p&gt;

&lt;p&gt;Chẳng hạn, từ posterior Beta\((9,5)\), ta có thể tính trực tiếp xác suất \(0.6 \le \theta \le 0.7\), xác suất \(\theta &amp;gt; 0.5\), hoặc xác suất \(\theta &amp;gt; 0.8\) — những câu hỏi gắn trực tiếp với quyết định thực tế.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_posterior_probability_interval.png&quot; alt=&quot;Xác suất posterior cho một khoảng cụ thể&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_posterior_probability_above_half.png&quot; alt=&quot;Xác suất posterior vượt ngưỡng 0.5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_posterior_probability_above_eighty.png&quot; alt=&quot;Xác suất posterior cho một giả thuyết tham số khá mạnh&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;5-các-thống-kê-tóm-tắt-posterior&quot;&gt;5. Các thống kê tóm tắt posterior&lt;/h2&gt;

&lt;h3 id=&quot;51-trung-bình-hậu-nghiệm-posterior-mean&quot;&gt;5.1. Trung bình hậu nghiệm (Posterior mean)&lt;/h3&gt;

&lt;p&gt;Là kỳ vọng của phân phối hậu nghiệm:&lt;/p&gt;

\[E[\theta \mid D].\]

&lt;p&gt;Thống kê này phù hợp khi cần một ước lượng điểm đại diện dưới hàm tổn thất bình phương.&lt;/p&gt;

&lt;h3 id=&quot;52-trung-vị-hậu-nghiệm-posterior-median&quot;&gt;5.2. Trung vị hậu nghiệm (Posterior median)&lt;/h3&gt;

&lt;p&gt;Là giá trị chia diện tích posterior thành hai nửa bằng nhau, hữu ích khi posterior bị lệch và cần một thước đo bền vững hơn trước phần đuôi dài.&lt;/p&gt;

&lt;h3 id=&quot;53-yếu-vị-hậu-nghiệm-posterior-mode--map&quot;&gt;5.3. Yếu vị hậu nghiệm (Posterior mode / MAP)&lt;/h3&gt;

&lt;p&gt;Là giá trị đạt mật độ posterior cao nhất, cho biết điểm đơn lẻ nào được posterior ủng hộ mạnh nhất.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/posterior_point_estimates.png&quot; alt=&quot;Các thống kê tóm tắt posterior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ba giá trị này có thể gần nhau nhưng không nhất thiết trùng nhau.&lt;/p&gt;

&lt;h4 id=&quot;video-ngắn-mean-mmse-median--mode-map-tách-nhau-khi-lệch--chập-một-khi-đối-xứng&quot;&gt;Video ngắn: Mean (MMSE), Median &amp;amp; Mode (MAP): Tách nhau khi Lệch — Chập một khi Đối xứng&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch02-04a-mean-median-mode-skew.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 20 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): biến hình mượt hậu nghiệm từ lệch phải Beta(2,10) → đối xứng Beta(8,8) → lệch trái Beta(10,2) để nhìn rõ 3 ước lượng điểm dịch chuyển tương ứng với 3 hàm tổn thất.&lt;/p&gt;

&lt;h3 id=&quot;54-mmse-và-trung-bình-hậu-nghiệm-dưới-hàm-tổn-thất-bình-phương&quot;&gt;5.4. MMSE và trung bình hậu nghiệm dưới hàm tổn thất bình phương&lt;/h3&gt;

&lt;p&gt;Nếu sử dụng hàm tổn thất sai số bình phương:&lt;/p&gt;

\[L(\theta,a)=(\theta-a)^2,\]

&lt;p&gt;thì ước lượng Bayes tối ưu theo nghĩa cực tiểu hóa sai số bình phương trung bình (MMSE) chính là trung bình hậu nghiệm:&lt;/p&gt;

\[\hat\theta_{MMSE}=E[\theta\mid D].\]

&lt;p&gt;Về trực giác, do tổn thất bình phương phạt nặng sai lệch lớn, điểm cân bằng tối ưu trên toàn bộ phân phối hậu nghiệm chính là kỳ vọng hậu nghiệm.&lt;/p&gt;

&lt;h3 id=&quot;55-ví-dụ-map-với-prior-liên-tục-và-likelihood-geometric&quot;&gt;5.5. Ví dụ: MAP với prior liên tục và likelihood Geometric&lt;/h3&gt;

&lt;p&gt;Giả sử dữ liệu quan sát là “thành công ở lần thử thứ 4”:&lt;/p&gt;

\[Y\mid\theta\sim \text{Geometric}(\theta),\quad y=4,\]

&lt;p&gt;với likelihood:&lt;/p&gt;

\[p(y\mid\theta)=\theta(1-\theta)^{y-1}=\theta(1-\theta)^3.\]

&lt;p&gt;Đặt prior:&lt;/p&gt;

\[\theta\sim\text{Beta}(2,2).\]

&lt;p&gt;Posterior tương ứng là:&lt;/p&gt;

\[\theta\mid y\sim\text{Beta}(3,5).\]

&lt;p&gt;Vì cả hai tham số đều lớn hơn 1, MAP của Beta\((a,b)\) được tính bằng:&lt;/p&gt;

\[\hat\theta_{MAP}=\frac{a-1}{a+b-2}.\]

&lt;p&gt;Suy ra:&lt;/p&gt;

\[\hat\theta_{MAP}=\frac{3-1}{3+5-2}=\frac{2}{6}=0.333.\]

&lt;h3 id=&quot;56-ví-dụ-so-sánh-mle-map-và-mmse-trong-mô-hình-normalnormal&quot;&gt;5.6. Ví dụ: so sánh MLE, MAP và MMSE trong mô hình Normal–Normal&lt;/h3&gt;

&lt;p&gt;Xét mô hình quan sát Gaussian đơn giản:&lt;/p&gt;

\[Y\mid\theta\sim\mathcal N(\theta,\sigma^2),\quad \sigma^2=1,\]

&lt;p&gt;với prior:&lt;/p&gt;

\[\theta\sim\mathcal N(0,\tau^2),\quad \tau^2=1.\]

&lt;p&gt;Giả sử quan sát được \(y=2\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;MLE&lt;/strong&gt; từ likelihood Gaussian: \(\hat\theta_{MLE}=y=2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior&lt;/strong&gt;:&lt;/li&gt;
&lt;/ul&gt;

\[\theta\mid y\sim\mathcal N\left(\mu_n,\tau_n^2\right),
\quad \mu_n=\frac{\tau^2}{\tau^2+\sigma^2}y=1,
\quad \tau_n^2=\frac{\tau^2\sigma^2}{\tau^2+\sigma^2}=0.5.\]

&lt;p&gt;Do posterior Gaussian đối xứng:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;MAP&lt;/strong&gt; \(=\mu_n=1\),&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;MMSE&lt;/strong&gt; \(=E[\theta\mid y]=\mu_n=1\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So sánh ba ước lượng:&lt;/p&gt;

\[\hat\theta_{MLE}=2,\qquad \hat\theta_{MAP}=1,\qquad \hat\theta_{MMSE}=1.\]

&lt;p&gt;Trong khi MLE chỉ dựa hoàn toàn vào dữ liệu quan sát, prior tập trung quanh 0 đã kéo các ước lượng Bayes về phía 0.&lt;/p&gt;

&lt;h3 id=&quot;57-ví-dụ-khoảng-tin-cậy-bayes-từ-posterior-normal&quot;&gt;5.7. Ví dụ: khoảng tin cậy Bayes từ posterior Normal&lt;/h3&gt;

&lt;p&gt;Từ posterior ở ví dụ trên, khoảng tin cậy Bayes \(95\%\) là:&lt;/p&gt;

\[\mu_n \pm 1.96\sqrt{\tau_n^2}=1\pm 1.96\sqrt{0.5}
\approx 1\pm 1.386,\]

&lt;p&gt;suy ra:&lt;/p&gt;

\[CI_{95\%}\approx[-0.386,\;2.386].\]

&lt;p&gt;Như vậy, từ cùng một phân phối hậu nghiệm, ta có thể báo cáo đồng thời ước lượng điểm (MAP/MMSE) và vùng bất định (credible interval).&lt;/p&gt;

&lt;h2 id=&quot;6-khoảng-tin-cậy-bayes-credible-interval&quot;&gt;6. Khoảng tin cậy Bayes (Credible interval)&lt;/h2&gt;

&lt;p&gt;Một khoảng tin cậy Bayes \(95\%\) là khoảng \([a,b]\) thỏa mãn:&lt;/p&gt;

\[P(a \le \theta \le b \mid D) = 0.95.\]

&lt;p&gt;Diễn giải bằng lời rất trực tiếp: &lt;strong&gt;dựa trên dữ liệu và prior đã chọn, có \(95\%\) xác suất để tham số nằm trong khoảng này.&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-thực-tế&quot;&gt;Ví dụ thực tế&lt;/h3&gt;

&lt;p&gt;Nếu posterior cho tỷ lệ phản hồi email tiếp thị có khoảng tin cậy Bayes \(95\%\) là \([0.18, 0.29]\), ta biết vùng giá trị hợp lý nhất hiện tại nằm trong khoảng đó và các quyết định thực tế cần tính đến độ bất định mà khoảng này thể hiện.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_credible_interval_95.png&quot; alt=&quot;Khoảng tin cậy Bayes 95% trên posterior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_credible_interval_90.png&quot; alt=&quot;Khoảng tin cậy Bayes 90% trên posterior&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-độ-phủ-của-khoảng-tin-cậy-và-khoảng-đáng-tin&quot;&gt;Thử nghiệm: độ phủ của khoảng tin cậy và khoảng đáng tin&lt;/h3&gt;

&lt;p&gt;Chạy lặp thí nghiệm và đếm số lần mỗi loại khoảng chứa giá trị thật.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;interval-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;7-phân-biệt-credible-interval-và-confidence-interval&quot;&gt;7. Phân biệt credible interval và confidence interval&lt;/h2&gt;

&lt;h3 id=&quot;71-khoảng-tin-cậy-bayes-bayesian-credible-interval&quot;&gt;7.1. Khoảng tin cậy Bayes (Bayesian credible interval)&lt;/h3&gt;

&lt;p&gt;Khoảng tin cậy Bayes phát biểu trực tiếp về xác suất của tham số:&lt;/p&gt;

\[P(a \le \theta \le b \mid D) = 0.95.\]

&lt;h3 id=&quot;72-khoảng-tin-cậy-tần-suất-frequentist-confidence-interval&quot;&gt;7.2. Khoảng tin cậy tần suất (Frequentist confidence interval)&lt;/h3&gt;

&lt;p&gt;Diễn giải đúng là: nếu lặp lại thí nghiệm vô số lần và mỗi lần đều dựng khoảng theo cùng một thủ tục, thì khoảng sinh ra sẽ chứa giá trị tham số thực trong khoảng \(95\%\) số lần. Đây là phát biểu về &lt;strong&gt;quy trình tạo khoảng&lt;/strong&gt;, không phải xác suất của tham số trong một tập dữ liệu cụ thể.&lt;/p&gt;

&lt;p&gt;Vì lý do này, credible interval thường phù hợp hơn với cách diễn đạt trực giác mà người dùng mong đợi.&lt;/p&gt;

&lt;h2 id=&quot;8-sự-cân-bằng-giữa-prior-và-dữ-liệu&quot;&gt;8. Sự cân bằng giữa prior và dữ liệu&lt;/h2&gt;

&lt;p&gt;Posterior luôn phản ánh tương quan giữa độ mạnh của prior và lượng thông tin trong dữ liệu: nếu prior mạnh mà dữ liệu ít thì posterior nằm gần prior; nếu prior yếu mà dữ liệu nhiều thì posterior tiến sát về phía likelihood; còn nếu cả hai đều mạnh thì posterior nằm ở vùng dung hòa với độ rộng khá hẹp. Do đó, với 3 bệnh nhân đầu tiên trong một thử nghiệm lâm sàng, kinh nghiệm trước đó của bác sĩ có trọng lượng lớn; nhưng khi đã có 3000 bệnh nhân, dữ liệu mới sẽ đóng vai trò chi phối.&lt;/p&gt;

&lt;h3 id=&quot;81-ví-dụ-cụ-thể-cùng-prior-dữ-liệu-ít-và-dữ-liệu-nhiều&quot;&gt;8.1. Ví dụ cụ thể: cùng prior, dữ liệu ít và dữ liệu nhiều&lt;/h3&gt;

&lt;p&gt;Giả sử prior ban đầu là Beta\((20,80)\) (trung bình \(0.2\)):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Nếu dữ liệu mới là 8 thành công trên 20 lần thử, posterior là Beta\((28,92)\) với trung bình hậu nghiệm khoảng \(0.233\).&lt;/li&gt;
  &lt;li&gt;Nếu dữ liệu mới là 80 thành công trên 200 lần thử, posterior là Beta\((100,200)\) với trung bình hậu nghiệm khoảng \(0.333\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cả hai tập dữ liệu đều có cùng tỷ lệ mẫu là \(0.4\), nhưng tập dữ liệu lớn hơn kéo posterior về phía dữ liệu mạnh hơn nhiều đồng thời làm phân phối hậu nghiệm hẹp hơn rõ rệt.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-posterior-hôm-nay-là-prior-ngày-mai&quot;&gt;Thử nghiệm: posterior hôm nay là prior ngày mai&lt;/h3&gt;

&lt;p&gt;Từng lần tung cập nhật Beta(a + ngửa, b + sấp); đối chiếu với xấp xỉ lưới.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;conjugate-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;betabinom&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;9-cập-nhật-tuần-tự-posterior-hôm-nay-là-prior-ngày-mai&quot;&gt;9. Cập nhật tuần tự: posterior hôm nay là prior ngày mai&lt;/h2&gt;

&lt;p&gt;Một tính chất nhất quán của suy luận Bayes là khả năng cập nhật qua nhiều đợt dữ liệu. Ví dụ, ở tuần 1 bạn quan sát 4 khách mua trên 10 khách, và ở tuần 2 quan sát thêm 9 khách mua trên 15 khách. Việc cập nhật một lần bằng toàn bộ dữ liệu hay cập nhật tuần 1 để lấy posterior rồi dùng posterior đó làm prior cho tuần 2 đều cho ra cùng một kết quả cuối cùng miễn là mô hình không thay đổi.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_sequential_update_step1.png&quot; alt=&quot;Cập nhật tuần tự bước 1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_sequential_update_step2.png&quot; alt=&quot;Cập nhật tuần tự bước 2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_sequential_update_step3.png&quot; alt=&quot;Cập nhật tuần tự bước 3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_sequential_update_step4.png&quot; alt=&quot;Cập nhật tuần tự bước 4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Đặc điểm này khiến thống kê Bayes rất phù hợp với bảng điều khiển kinh doanh cập nhật hằng ngày, giám sát chất lượng theo lô, hay thử nghiệm lâm sàng thu thập dữ liệu theo từng giai đoạn.&lt;/p&gt;

&lt;h2 id=&quot;91-từ-posterior-sang-quyết-định-và-kiểm-định&quot;&gt;9.1. Từ posterior sang quyết định và kiểm định&lt;/h2&gt;

&lt;p&gt;Posterior không phải điểm dừng cuối cùng. Ta có thể dùng posterior để chọn hành động tối ưu dưới một hàm tổn thất \(L(a,\theta)\):&lt;/p&gt;

\[a^*=\arg\min_a\;\mathbb E[L(a,\theta)\mid D].\]

&lt;p&gt;Trong kiểm định Bayes giữa hai giả thuyết \(H_0\) và \(H_1\), ta sử dụng hệ số Bayes (Bayes factor):&lt;/p&gt;

\[BF_{10}=\frac{p(D\mid H_1)}{p(D\mid H_0)},\]

&lt;p&gt;rồi nhân với tỷ số tiền nghiệm (prior odds) để thu được tỷ số hậu nghiệm (posterior odds):&lt;/p&gt;

\[\frac{P(H_1\mid D)}{P(H_0\mid D)}=BF_{10}\times\frac{P(H_1)}{P(H_0)}.\]

&lt;p&gt;Như vậy, Chương 2 trang bị cách xây dựng posterior, còn Chương 8.4 sẽ sử dụng posterior đó để lựa chọn hành động tối ưu theo hàm tổn thất.&lt;/p&gt;

&lt;h2 id=&quot;10-phân-phối-dự-báo-hậu-nghiệm-posterior-predictive&quot;&gt;10. Phân phối dự báo hậu nghiệm (Posterior predictive)&lt;/h2&gt;

&lt;p&gt;Posterior không chỉ dùng để suy luận tham số mà còn để dự báo &lt;strong&gt;dữ liệu mới&lt;/strong&gt;. Sau khi có posterior về tỷ lệ chuyển đổi, ta có thể dự báo số đơn hàng ngày mai; từ posterior về tỷ lệ qua môn, ta dự báo số sinh viên đậu ở khóa tới; và từ posterior về tốc độ lỗi, ta ước lượng số lỗi trong tuần sau. Phân phối mô tả dữ liệu tương lai đó được gọi là &lt;strong&gt;posterior predictive distribution&lt;/strong&gt;, giúp chuyển kết quả suy luận tham số thành dự báo ứng dụng trực tiếp.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/posterior_predictive.png&quot; alt=&quot;Posterior predictive distribution&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-posterior-predictive-vì-sao-luôn-rộng-hơn-cắm-cứng-1-điểm-θ̂&quot;&gt;Video ngắn: Posterior Predictive: Vì sao luôn Rộng hơn Cắm cứng 1 Điểm θ̂?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch02-04b-posterior-predictive-spread.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): so sánh song song phân phối dự báo cắm cứng θ̂ = 0.64 (quá tự tin) với Posterior Predictive Beta–Binomial (đuôi dày hơn, phản ánh trung thực bất định của θ).&lt;/p&gt;

&lt;h2 id=&quot;11-những-nhầm-lẫn-phổ-biến-về-posterior&quot;&gt;11. Những nhầm lẫn phổ biến về posterior&lt;/h2&gt;

&lt;h3 id=&quot;111-posterior-chỉ-là-likelihood-được-chuẩn-hóa&quot;&gt;11.1. “Posterior chỉ là likelihood được chuẩn hóa”&lt;/h3&gt;

&lt;p&gt;Không hẳn. Posterior còn phụ thuộc vào prior; nếu prior thay đổi, posterior cũng có thể thay đổi, đặc biệt khi dữ liệu chưa nhiều.&lt;/p&gt;

&lt;h3 id=&quot;112-posterior-mean-là-câu-trả-lời-duy-nhất&quot;&gt;11.2. “Posterior mean là câu trả lời duy nhất”&lt;/h3&gt;

&lt;p&gt;Không đúng. Tùy vào mục tiêu quyết định, bạn có thể cần MAP, khoảng tin cậy Bayes, xác suất vượt ngưỡng hoặc phân phối dự báo hậu nghiệm thay vì chỉ nhìn vào trung bình hậu nghiệm.&lt;/p&gt;

&lt;h3 id=&quot;113-có-posterior-đẹp-là-hoàn-tất-phân-tích&quot;&gt;11.3. “Có posterior đẹp là hoàn tất phân tích”&lt;/h3&gt;

&lt;p&gt;Chưa đủ. Một posterior mượt mà không thể khắc phục một mô hình sinh dữ liệu sai lệch. Ở các chương sau, bạn sẽ học kỹ thuật kiểm tra mô hình (model checking) để đánh giá lại chính mô hình đã tạo ra posterior đó.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Posterior là niềm tin đã được cập nhật sau khi kết hợp prior với dữ liệu.&lt;/strong&gt; Đây là đối tượng trung tâm của suy luận Bayes vì từ posterior ta có thể tính xác suất trực tiếp cho các giả thuyết về tham số, xây dựng khoảng tin cậy Bayes, rút ra các tóm tắt như mean, median hay MAP, và mở rộng sang dự báo dữ liệu tương lai. Nói gọn lại, posterior kết hợp kiến thức ban đầu với bằng chứng mới, cho phép phát biểu xác suất trực tiếp về tham số và phát huy giá trị cao nhất khi phục vụ các câu hỏi thực tế như khoảng giá trị hợp lý, xác suất vượt ngưỡng và phân phối dự báo.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-công-thức-trung-bình-có-trọng-số-và-cách-tách-mean--mode--predictive&quot;&gt;Giải thích: Công thức trung bình có trọng số và cách tách Mean – Mode – Predictive&lt;/h2&gt;

&lt;p&gt;Với họ liên hợp Beta–Binomial, hậu nghiệm \(\text{Beta}(\alpha_{\text{post}}, \beta_{\text{post}})\) cho thấy cơ chế hoạt động tinh tế nhất của Bayes qua 3 tính chất:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kỳ vọng hậu nghiệm là trung bình có trọng số giữa Prior và MLE:&lt;/strong&gt;
\(\mathbb{E}[p \mid y] = \frac{\alpha + k}{\alpha + \beta + n} = \underbrace{\frac{\alpha+\beta}{\alpha+\beta+n}}_{w_{\text{prior}}} \cdot \mu_{\text{prior}} + \underbrace{\frac{n}{\alpha+\beta+n}}_{w_{\text{data}}} \cdot \hat p_{\text{MLE}}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ rộng bất định co lại theo \(1/\sqrt{\alpha+\beta+n}\):&lt;/strong&gt; Càng có nhiều dữ liệu, đỉnh hậu nghiệm càng nhọn và khoảng tin cậy càng hẹp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dự báo cho quan sát mới kế tiếp:&lt;/strong&gt; Xác suất thành công ở phép thử mới \(\tilde y = 1\) đúng bằng kỳ vọng hậu nghiệm \(\mathbb{E}[p \mid y]\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-đọc-đầy-đủ-hậu-nghiệm-textbeta8-4&quot;&gt;Ví dụ tính toán làm từng bước: Đọc đầy đủ hậu nghiệm \(\text{Beta}(8, 4)\)&lt;/h3&gt;

&lt;p&gt;Giả sử dùng prior \(\text{Beta}(1, 1)\) và quan sát \(k = 7\) Ngửa trong \(n = 10\) lần tung, ta thu được hậu nghiệm \(\text{Beta}(8, 4)\). Tính tay các đại lượng tóm tắt chính:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Đại lượng&lt;/th&gt;
      &lt;th&gt;Công thức cho \(\text{Beta}(\alpha, \beta)\)&lt;/th&gt;
      &lt;th&gt;Giá trị cho \(\text{Beta}(8, 4)\)&lt;/th&gt;
      &lt;th&gt;Ý nghĩa&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Trung bình hậu nghiệm (Mean)&lt;/td&gt;
      &lt;td&gt;\(\frac{\alpha}{\alpha+\beta}\)&lt;/td&gt;
      &lt;td&gt;\(8 / 12 \approx 0.6667\)&lt;/td&gt;
      &lt;td&gt;Ước lượng tối ưu dưới MSE và xác suất dự báo lần tung thứ 11 ra Ngửa&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Đỉnh hậu nghiệm (MAP / Mode)&lt;/td&gt;
      &lt;td&gt;\(\frac{\alpha - 1}{\alpha + \beta - 2}\)&lt;/td&gt;
      &lt;td&gt;\(7 / 10 = 0.7000\)&lt;/td&gt;
      &lt;td&gt;Giá trị đơn lẻ có mật độ cao nhất (trùng MLE vì prior phẳng)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Độ lệch chuẩn hậu nghiệm&lt;/td&gt;
      &lt;td&gt;\(\sqrt{\frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}}\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{\frac{32}{144 \times 13}} \approx 0.1307\)&lt;/td&gt;
      &lt;td&gt;Mức độ bất định còn lại quanh mức \(0.667\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Tỷ lệ trọng số Prior / Dữ liệu&lt;/td&gt;
      &lt;td&gt;\(\frac{2}{12}\) và \(\frac{10}{12}\)&lt;/td&gt;
      &lt;td&gt;\(16.7\%\) và \(83.3\%\)&lt;/td&gt;
      &lt;td&gt;\(0.167(0.5) + 0.833(0.7) = 0.6667\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhầm rằng một khoảng tin cậy 95% hậu nghiệm cho tham số \(p\) nghĩa là “95% các quan sát mới sẽ rơi vào khoảng đó”. Khoảng tin cậy hậu nghiệm mô tả bất định của &lt;strong&gt;tham số&lt;/strong&gt; \(p\); muốn nói về dữ liệu mới phải dùng &lt;strong&gt;khoảng dự báo hậu nghiệm (Posterior Predictive Interval)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Do \(\text{Beta}(8, 4)\) lệch trái (đuôi trái dài hơn), ta luôn có thứ tự \(\text{Mean} (0.6667) &amp;lt; \text{Median} (\approx 0.676) &amp;lt; \text{Mode} (0.7000)\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zXtcZ-2adK0&quot;&gt;P01.007 — Định lý Bayes cập nhật niềm tin của mô hình ra sao?&lt;/a&gt; — Phạm Thông, Tiếng Việt. &lt;strong&gt;xem trước&lt;/strong&gt;. Giải thích posterior như niềm tin đã được dữ liệu cập nhật, phù hợp với trọng tâm bài học.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Minh họa trực quan cách prior và likelihood kết hợp thành posterior chuẩn hóa, hỗ trợ đọc diện tích và khoảng.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YPceDssQFWo&quot;&gt;Bayesian Statistics: Credible vs Confidence Intervals&lt;/a&gt; — Academia Elevated, English. Trình bày cách diễn giải khoảng tin cậy Bayes thay vì chỉ dùng một ước lượng điểm.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao posterior trong ví dụ 7/10 mặt ngửa không nằm đúng tại \(0.7\)?&lt;/li&gt;
  &lt;li&gt;Hãy giải thích bằng lời sự khác nhau giữa credible interval và confidence interval.&lt;/li&gt;
  &lt;li&gt;Trong công việc của bạn, hãy nêu một câu hỏi dạng “xác suất vượt ngưỡng” có ý nghĩa hơn việc chỉ báo cáo trung bình.&lt;/li&gt;
  &lt;li&gt;Vì sao phân phối dự báo hậu nghiệm (posterior predictive) lại hữu ích hơn việc chỉ xem posterior của tham số?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 2.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 5-6.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2-3.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter02/02_05_conjugate_priors/&quot;&gt;2.5 Prior liên hợp và đại số của cập nhật Bayes&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 2.3: Prior - Mã hóa Kiến thức Ban đầu</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_03_prior/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_03_prior</id>
   <content type="html">&lt;p&gt;Trong các cuộc tranh luận về thống kê Bayes, &lt;strong&gt;phân phối tiên nghiệm (prior)&lt;/strong&gt; luôn là thành phần vừa gây nhiều tò mò vừa dễ bị hiểu lầm nhất. Nhiều người lo ngại rằng đặt prior đồng nghĩa với việc “áp đặt thiên kiến cá nhân” vào dữ liệu. Nhưng trên thực tế, mọi mô hình thống kê đều ẩn chứa giả định tiên nghiệm — ngay cả khi ta không viết ra. Khác biệt của thống kê Bayes là đặt mọi giả định ban đầu lên bàn ánh sáng một cách tường minh, định lượng được và kiểm tra được.&lt;/p&gt;

&lt;p&gt;Bài học này giúp bạn hiểu cách chuyển hóa tri thức miền thành toán học qua các loại prior (không thông tin, thông tin yếu, có thông tin, hỗn hợp) và cách kiểm chứng chúng bằng &lt;em&gt;prior predictive check&lt;/em&gt; cùng phân tích độ nhạy.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn cần nhìn nhận prior (phân phối tiền nghiệm) như một thành phần &lt;strong&gt;tự nhiên&lt;/strong&gt; của quá trình suy luận chứ không phải một “thành kiến tùy tiện”. Bạn cũng cần biết cách chuyển kiến thức định tính thành một prior cụ thể, phân biệt khi nào nên dùng prior yếu hay prior mạnh, và biết cách kiểm tra tính hợp lý của prior đã chọn.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ mini.&lt;/strong&gt; Trước khi chạy một chiến dịch mới, nhóm tiếp thị tin rằng tỷ lệ nhấp thường nằm trong khoảng \(2\%\) đến \(5\%\) và rất hiếm khi vượt quá \(10\%\). Đó chính là dạng thông tin mà prior dùng để mã hóa.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Nếu bạn biết một tham số không thể âm hoặc không thể lớn hơn 1, thông tin đó đã đủ để định hình prior chưa?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-phân-loại-prior-cỡ-mẫu-hiệu-dụng-và-phân-tích-độ-nhạy&quot;&gt;Kiến thức cần nhớ: Phân loại Prior, Cỡ mẫu hiệu dụng và Phân tích độ nhạy&lt;/h2&gt;

&lt;p&gt;Chọn prior một cách khoa học dựa trên ba trụ cột rõ ràng:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phổ cường độ thông tin (Flat → Weakly Informative → Informative):&lt;/strong&gt; Prior phẳng (flat/uniform) thường không thực sự “vô hại” (không bất biến khi đổi tham số và dễ sinh giá trị cực đoan trong mô hình nhiều chiều). Thực hành Bayes hiện đại (Gelman, McElreath) ưu tiên &lt;strong&gt;prior thông tin yếu (weakly informative)&lt;/strong&gt; giúp chặn các vùng phi lý mà vẫn để dữ liệu dẫn dắt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cỡ mẫu giả định của Prior (Effective Prior Sample Size):&lt;/strong&gt; Với các họ liên hợp như \(\text{Beta}(\alpha, \beta)\), tổng \(\alpha + \beta\) biểu thị trực tiếp “số quan sát ảo” mà prior đóng góp. So sánh \(\alpha + \beta\) với cỡ mẫu thật \(n\) cho thấy ngay prior mạnh hay yếu so với dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng bắt buộc (Prior Predictive &amp;amp; Sensitivity Analysis):&lt;/strong&gt; Trước khi khớp dữ liệu, ta mô phỏng từ prior để kiểm tra xem dữ liệu sinh ra có hợp lý về mặt vật lý/nghiệp vụ không; sau khi khớp, ta thay đổi prior hợp lý khác để đo mức độ nhạy của kết luận hậu nghiệm.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mở-đầu-ta-hiếm-khi-bắt-đầu-từ-con-số-0&quot;&gt;Mở đầu: ta hiếm khi bắt đầu từ con số 0&lt;/h2&gt;

&lt;p&gt;Giả sử bạn cần đánh giá hiệu quả của một chiến dịch quảng cáo mới. Dựa trên các chiến dịch trước đó, bạn đã biết tỷ lệ nhấp thường nằm quanh \(2\%\) đến \(5\%\), rất hiếm khi vượt quá \(10\%\) và cũng khó xuống sát 0 nếu tệp khách hàng đã được chọn lọc kỹ.&lt;/p&gt;

&lt;p&gt;Nếu hiện tại bạn mới quan sát được 3 lượt nhấp trên 20 lượt hiển thị, việc giả vờ như mình hoàn toàn không có thông tin gì từ trước có hợp lý không? Thống kê Bayes trả lời rằng &lt;strong&gt;không&lt;/strong&gt;: những kiến thức sẵn có nên được đưa vào mô hình một cách tường minh. Đó chính là vai trò của prior.&lt;/p&gt;

&lt;h2 id=&quot;1-prior-là-gì&quot;&gt;1. Prior là gì?&lt;/h2&gt;

&lt;p&gt;Prior \(P(\theta)\) là phân phối xác suất biểu diễn niềm tin về tham số \(\theta\) &lt;strong&gt;trước khi&lt;/strong&gt; quan sát dữ liệu hiện tại. Trong định lý Bayes:&lt;/p&gt;

\[P(\theta \mid D) \propto P(D \mid \theta)P(\theta),\]

&lt;p&gt;prior là điểm xuất phát, likelihood là tiếng nói của dữ liệu, còn posterior là niềm tin sau khi cập nhật. Nói gọn lại, prior không phải là “đoán mò”, mà là cách diễn đạt tường minh những gì đã biết — hoặc ít nhất là những ràng buộc hợp lý — trước khi tiếp nhận dữ liệu mới.&lt;/p&gt;

&lt;h3 id=&quot;11-ý-nghĩa-của-pd-trong-định-lý-bayes&quot;&gt;1.1. Ý nghĩa của \(P(D)\) trong định lý Bayes&lt;/h3&gt;

&lt;p&gt;Trong dạng đầy đủ của định lý Bayes:&lt;/p&gt;

\[P(\theta \mid D) = \frac{P(D \mid \theta)P(\theta)}{P(D)},\]

&lt;p&gt;ta thường viết gọn \(P(\theta \mid D) \propto P(D \mid \theta)P(\theta)\) và tạm bỏ qua \(P(D)\) vì nó không phụ thuộc vào \(\theta\). Tuy nhiên, \(P(D)\) thực chất đảm nhận hai vai trò quan trọng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vai trò 1: Hằng số chuẩn hóa (Normalizing constant)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Đại lượng \(P(D)\) đảm bảo posterior là một phân phối xác suất hợp lệ, tức là:&lt;/p&gt;

\[\int P(\theta \mid D) d\theta = 1.\]

&lt;p&gt;Nó được tính bằng cách tích phân (hoặc lấy tổng) qua mọi giá trị có thể của \(\theta\):&lt;/p&gt;

\[P(D) = \int P(D \mid \theta)P(\theta) d\theta.\]

&lt;p&gt;Trong nhiều bài toán suy luận tham số đơn lẻ, ta không cần tính tường minh \(P(D)\). Tuy nhiên, khi làm việc với prior hỗn hợp (mixture prior) hoặc so sánh mô hình, \(P(D)\) trở thành đại lượng trung tâm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vai trò 2: Đo mức độ phù hợp giữa prior và dữ liệu (Marginal likelihood)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;\(P(D)\) còn được gọi là &lt;strong&gt;hợp lý biên (marginal likelihood)&lt;/strong&gt; hay &lt;strong&gt;bằng chứng (evidence)&lt;/strong&gt;. Nó trả lời câu hỏi:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Xác suất quan sát được dữ liệu \(D\) là bao nhiêu khi tính trung bình trên &lt;strong&gt;mọi giá trị khả dĩ&lt;/strong&gt; của \(\theta\) theo prior?”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Nói cách khác, \(P(D)\) đo &lt;strong&gt;mức độ prior giải thích dữ liệu tốt đến đâu&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Nếu \(P(D)\) cao, prior đã phân bổ xác suất tốt vào vùng tham số phù hợp với dữ liệu quan sát.&lt;/li&gt;
  &lt;li&gt;Nếu \(P(D)\) thấp, prior đã đặt khối lượng xác suất lớn ở những vùng tham số kém phù hợp với dữ liệu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;ví-dụ-minh-họa-so-sánh-hai-prior&quot;&gt;Ví dụ minh họa: so sánh hai prior&lt;/h4&gt;

&lt;p&gt;Xét hai prior khác nhau cho cùng một bài toán:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Prior 1&lt;/strong&gt;: Beta\((20, 80)\) (tin khá chắc rằng \(\theta \approx 0.2\))&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prior 2&lt;/strong&gt;: Beta\((5, 5)\) (tin yếu, tập trung quanh \(\theta \approx 0.5\))&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Giả sử ta quan sát 15 thành công trong 50 lần thử (tỷ lệ mẫu là \(0.3\)). Marginal likelihood của mỗi mô hình là:&lt;/p&gt;

\[P(D \mid M_1) = \int_0^1 P(D \mid \theta) \cdot \text{Beta}(\theta; 20, 80) d\theta\]

\[P(D \mid M_2) = \int_0^1 P(D \mid \theta) \cdot \text{Beta}(\theta; 5, 5) d\theta\]

&lt;p&gt;Trong trường hợp này, Prior 1 tập trung quanh \(\theta = 0.2\), gần với tỷ lệ dữ liệu \(0.3\) hơn so với Prior 2, nên \(P(D \mid M_1)\) cao hơn \(P(D \mid M_2)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hệ số Bayes (Bayes factor)&lt;/strong&gt; giữa hai mô hình/prior được định nghĩa là:&lt;/p&gt;

\[\text{BF}_{12} = \frac{P(D \mid M_1)}{P(D \mid M_2)}.\]

&lt;p&gt;Nếu \(\text{BF}_{12} &amp;gt; 1\), dữ liệu ủng hộ mô hình 1 mạnh hơn mô hình 2.&lt;/p&gt;

&lt;h4 id=&quot;ứng-dụng-trong-so-sánh-mô-hình&quot;&gt;Ứng dụng trong so sánh mô hình&lt;/h4&gt;

&lt;p&gt;Marginal likelihood là nền tảng của &lt;strong&gt;so sánh mô hình theo Bayes (Bayesian model comparison)&lt;/strong&gt;. Khi so sánh hai mô hình \(M_1\) và \(M_2\):&lt;/p&gt;

\[\frac{P(M_1 \mid D)}{P(M_2 \mid D)} = \frac{P(D \mid M_1)}{P(D \mid M_2)} \times \frac{P(M_1)}{P(M_2)}.\]

&lt;p&gt;Nếu xác suất tiền nghiệm của hai mô hình bằng nhau (\(P(M_1) = P(M_2)\)), ta có:&lt;/p&gt;

\[\frac{P(M_1 \mid D)}{P(M_2 \mid D)} = \frac{P(D \mid M_1)}{P(D \mid M_2)} = \text{BF}_{12}.\]

&lt;p&gt;Bayes factor tự động cân bằng giữa &lt;strong&gt;độ khớp với dữ liệu&lt;/strong&gt; và &lt;strong&gt;độ phức tạp của mô hình&lt;/strong&gt;: mô hình phức tạp hơn sẽ bị “phạt” một cách tự nhiên vì phải dàn trải khối lượng xác suất prior trên một vùng tham số rộng hơn.&lt;/p&gt;

&lt;h4 id=&quot;ứng-dụng-trong-prior-hỗn-hợp-mixture-priors&quot;&gt;Ứng dụng trong prior hỗn hợp (Mixture priors)&lt;/h4&gt;

&lt;p&gt;Ở Mục 6 của bài này, khi sử dụng prior hỗn hợp:&lt;/p&gt;

\[p(\theta) = w_1 p_1(\theta) + w_2 p_2(\theta),\]

&lt;p&gt;trọng số của từng thành phần sau khi quan sát dữ liệu được cập nhật trực tiếp thông qua marginal likelihood:&lt;/p&gt;

\[\tilde w_k = \frac{w_k \cdot P(D \mid M_k)}{\sum_{j} w_j \cdot P(D \mid M_j)},\]

&lt;p&gt;trong đó \(P(D \mid M_k)\) là marginal likelihood của thành phần thứ \(k\). Dữ liệu sẽ tự động tăng trọng số cho thành phần giải thích dữ liệu tốt hơn.&lt;/p&gt;

&lt;h4 id=&quot;tóm-tắt-các-góc-nhìn-về-pd&quot;&gt;Tóm tắt các góc nhìn về \(P(D)\)&lt;/h4&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Góc nhìn&lt;/th&gt;
      &lt;th&gt;Ý nghĩa&lt;/th&gt;
      &lt;th&gt;Khi nào sử dụng&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Hằng số chuẩn hóa (Normalizing constant)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Đảm bảo \(\int P(\theta\mid D)d\theta = 1\)&lt;/td&gt;
      &lt;td&gt;Luôn có mặt (thường ngầm định)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Hợp lý biên (Marginal likelihood)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Đo mức độ prior giải thích dữ liệu&lt;/td&gt;
      &lt;td&gt;So sánh mô hình, tính Bayes factor&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Bằng chứng (Evidence)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Xác suất của dữ liệu dưới phân phối prior&lt;/td&gt;
      &lt;td&gt;Lựa chọn mô hình, prior hỗn hợp&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Như vậy, \(P(D)\) không chỉ là một hằng số kỹ thuật; nó là thước đo kết nối prior với khả năng giải thích dữ liệu và giữ vai trò then chốt trong so sánh mô hình Bayes.&lt;/p&gt;

&lt;h2 id=&quot;2-prior-đến-từ-đâu&quot;&gt;2. Prior đến từ đâu?&lt;/h2&gt;

&lt;p&gt;Prior có thể được xây dựng từ nhiều nguồn thực tế khác nhau.&lt;/p&gt;

&lt;h3 id=&quot;21-từ-dữ-liệu-lịch-sử&quot;&gt;2.1. Từ dữ liệu lịch sử&lt;/h3&gt;

&lt;p&gt;Prior có thể rút ra từ tỷ lệ sinh viên qua môn trong 5 học kỳ trước, tỷ lệ sản phẩm lỗi của các lô sản xuất trước, hay doanh số của các chiến dịch gần đây.&lt;/p&gt;

&lt;h3 id=&quot;22-từ-kiến-thức-chuyên-môn&quot;&gt;2.2. Từ kiến thức chuyên môn&lt;/h3&gt;

&lt;p&gt;Kiến thức miền chuyên môn cũng là nguồn thông tin quan trọng: bác sĩ biết hiệu quả của các thuốc tương tự thường nằm trong một khoảng nhất định; kỹ sư biết độ lệch của cảm biến khó vượt quá một ngưỡng vật lý; giảng viên biết tỷ lệ qua môn của một học phần khó hiếm khi đạt \(99\%\).&lt;/p&gt;

&lt;h3 id=&quot;23-từ-ràng-buộc-logic-hoặc-vật-lý&quot;&gt;2.3. Từ ràng buộc logic hoặc vật lý&lt;/h3&gt;

&lt;p&gt;Các ràng buộc tự nhiên như xác suất phải nằm trong đoạn \([0,1]\), phương sai phải dương, hay thời gian chờ không thể âm đều là thông tin tiền nghiệm.&lt;/p&gt;

&lt;h3 id=&quot;24-từ-lựa-chọn-thận-trọng-khi-chưa-có-nhiều-thông-tin&quot;&gt;2.4. Từ lựa chọn thận trọng khi chưa có nhiều thông tin&lt;/h3&gt;

&lt;p&gt;Ngay cả khi chưa có số liệu cụ thể, ta vẫn thường biết những giới hạn tối thiểu: chẳng hạn tỷ lệ sản phẩm lỗi khó thể lên tới \(95\%\) nếu sản phẩm vẫn đang được tiêu thụ bình thường, hoặc một hệ số hồi quy quá lớn là phi thực tế xét theo đơn vị đo lường. Những nhận định thận trọng đó đều có thể mã hóa vào prior.&lt;/p&gt;

&lt;h2 id=&quot;3-chuyển-nhận-định-bằng-lời-thành-phân-phối-prior&quot;&gt;3. Chuyển nhận định bằng lời thành phân phối prior&lt;/h2&gt;

&lt;p&gt;Đây là kỹ năng thực hành quan trọng nhất của bài học. Giả sử nhóm tiếp thị nhận định:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Tỷ lệ chuyển đổi của trang đích mới thường nằm quanh \(20\%\), hiếm khi dưới \(10\%\) và cũng khó vượt quá \(35\%\).”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ta cần chuyển phát biểu này thành một prior cho xác suất \(\theta\). Vì \(\theta \in [0,1]\), họ phân phối Beta là lựa chọn tự nhiên. Chẳng hạn, Beta\((8,32)\) có kỳ vọng:&lt;/p&gt;

\[\frac{8}{8+32} = 0.2.\]

&lt;p&gt;Prior này không khẳng định “\(\theta\) chắc chắn bằng \(0.2\)”; nó thể hiện rằng vùng trung tâm hợp lý nằm quanh \(0.2\), các giá trị lân cận như \(0.15\) hay \(0.25\) vẫn hoàn toàn khả dĩ, còn các giá trị quá cực đoan có xác suất thấp. Đây là cách thống kê Bayes chuyển kiến thức định tính thành cấu trúc định lượng.&lt;/p&gt;

&lt;h2 id=&quot;4-cùng-trung-bình-nhưng-độ-mạnh-khác-nhau&quot;&gt;4. Cùng trung bình nhưng độ mạnh khác nhau&lt;/h2&gt;

&lt;p&gt;Xét bốn prior khác nhau để thấy rõ prior thay đổi trên cả hai phương diện là &lt;strong&gt;trung tâm&lt;/strong&gt; và &lt;strong&gt;độ chắc chắn&lt;/strong&gt;: Beta\((1,1)\) gần như phẳng trên toàn đoạn \([0,1]\), Beta\((5,5)\) tập trung nhẹ quanh \(0.5\), Beta\((20,80)\) nghiêng về \(0.2\) với độ chắc chắn vừa phải, còn Beta\((100,400)\) cũng có trung bình \(0.2\) nhưng tập trung chặt hơn nhiều.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_flat_uniform.png&quot; alt=&quot;Prior gần như phẳng trên toàn khoảng [0,1]&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_centered_half.png&quot; alt=&quot;Prior tập trung nhẹ quanh 0.5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_centered_low_moderate.png&quot; alt=&quot;Prior nghiêng về vùng thấp với mức chắc chắn vừa&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_centered_low_strong.png&quot; alt=&quot;Prior nghiêng về vùng thấp với mức chắc chắn mạnh&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Như vậy, một prior luôn truyền tải đồng thời hai thông tin: &lt;strong&gt;trung tâm niềm tin&lt;/strong&gt; nằm ở đâu và &lt;strong&gt;mức độ tự tin&lt;/strong&gt; vào trung tâm đó mạnh đến mức nào.&lt;/p&gt;

&lt;h3 id=&quot;41-ví-dụ-cụ-thể-cùng-trung-bình-02-nhưng-khác-độ-mạnh&quot;&gt;4.1. Ví dụ cụ thể: cùng trung bình \(0.2\) nhưng khác độ mạnh&lt;/h3&gt;

&lt;p&gt;Giả sử ta quan sát 6 khách mua hàng trong 20 lượt truy cập (tỷ lệ mẫu là \(0.30\)):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Với prior Beta\((8,32)\), posterior là Beta\((14,46)\), có trung bình hậu nghiệm khoảng \(0.233\).&lt;/li&gt;
  &lt;li&gt;Với prior Beta\((40,160)\), posterior là Beta\((46,174)\), có trung bình hậu nghiệm khoảng \(0.209\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cả hai prior đều có cùng trung bình ban đầu là \(0.2\), nhưng prior thứ hai mạnh hơn nhiều nên posterior dịch chuyển ít hơn về phía dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;5-các-loại-prior-thường-gặp&quot;&gt;5. Các loại prior thường gặp&lt;/h2&gt;

&lt;h3 id=&quot;51-prior-ít-thông-tin-non-informative--flat-prior&quot;&gt;5.1. Prior ít thông tin (Non-informative / flat prior)&lt;/h3&gt;

&lt;p&gt;Ví dụ như Beta\((1,1)\) cho một xác suất. Prior này không đẩy niềm tin mạnh về vùng giá trị cụ thể nào, để dữ liệu đóng vai trò chính trong việc định hình posterior. Tuy nhiên, cần lưu ý rằng “ít thông tin” không đồng nghĩa với hoàn toàn trung tính dưới mọi phép biến đổi tham số.&lt;/p&gt;

&lt;h3 id=&quot;52-prior-thông-tin-yếu-weakly-informative-prior&quot;&gt;5.2. Prior thông tin yếu (Weakly informative prior)&lt;/h3&gt;

&lt;p&gt;Ví dụ như Beta\((2,2)\) hoặc phân phối Normal có độ lệch chuẩn khá lớn. Prior yếu giúp loại bớt các giá trị cực đoan phi thực tế nhưng vẫn để dữ liệu chi phối mạnh. Trong thực hành, đây thường là điểm khởi đầu an toàn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/weakly_informative_prior_example.png&quot; alt=&quot;Ví dụ prior yếu&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;53-prior-thông-tin-mạnh-strongly-informative-prior&quot;&gt;5.3. Prior thông tin mạnh (Strongly informative prior)&lt;/h3&gt;

&lt;p&gt;Ví dụ như Beta\((50,50)\) hay Beta\((80,20)\) khi đã có nhiều bằng chứng vững chắc từ trước. Prior mạnh mang lượng thông tin nền đáng kể vào mô hình, nên ảnh hưởng rõ rệt tới posterior, nhất là khi dữ liệu mới còn ít.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/strongly_informative_prior_example.png&quot; alt=&quot;Ví dụ prior mạnh&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;54-từ-posterior-đến-ước-lượng-điểm-vai-trò-của-hàm-tổn-thất-loss-functions&quot;&gt;5.4. Từ posterior đến ước lượng điểm: vai trò của hàm tổn thất (Loss functions)&lt;/h3&gt;

&lt;p&gt;Kết quả của suy luận Bayes là &lt;strong&gt;toàn bộ phân phối hậu nghiệm&lt;/strong&gt; \(p(\theta \mid D)\), chẳng hạn:&lt;/p&gt;

\[\theta \mid D \sim \text{Beta}(17, 103).\]

&lt;p&gt;Tuy nhiên, trong thực tế báo cáo và ra quyết định, ta thường cần chọn &lt;strong&gt;một giá trị đại diện duy nhất&lt;/strong&gt; (ước lượng điểm — point estimate) để trả lời các câu hỏi như tỷ lệ chuyển đổi là bao nhiêu hay số cuộc gọi trung bình mỗi giờ là bao nhiêu. Ba lựa chọn phổ biến gồm:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Trung bình hậu nghiệm (Posterior mean)&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trung vị hậu nghiệm (Posterior median)&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Yếu vị hậu nghiệm (Posterior mode hay MAP)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hàm tổn thất (loss function)&lt;/strong&gt; là công cụ giúp xác định ước lượng điểm nào tối ưu cho mục tiêu của bài toán.&lt;/p&gt;

&lt;h4 id=&quot;hàm-tổn-thất-là-gì&quot;&gt;Hàm tổn thất là gì?&lt;/h4&gt;

&lt;p&gt;Hàm tổn thất \(L(\theta, \hat{\theta})\) định lượng mức độ thiệt hại khi giá trị thực của tham số là \(\theta\) nhưng ta báo cáo ước lượng là \(\hat{\theta}\). Mục tiêu là chọn \(\hat{\theta}\) để &lt;strong&gt;cực tiểu hóa tổn thất kỳ vọng hậu nghiệm&lt;/strong&gt;:&lt;/p&gt;

\[\hat{\theta}_{\text{optimal}} = \arg\min_{\hat{\theta}} E[L(\theta, \hat{\theta}) \mid D] = \arg\min_{\hat{\theta}} \int L(\theta, \hat{\theta}) p(\theta \mid D) d\theta.\]

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Hàm tổn thất khác nhau dẫn tới ước lượng tối ưu khác nhau.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;ba-hàm-tổn-thất-phổ-biến&quot;&gt;Ba hàm tổn thất phổ biến&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;1. Hàm tổn thất bình phương (Squared loss)&lt;/strong&gt;&lt;/p&gt;

\[L(\theta, \hat{\theta}) = (\theta - \hat{\theta})^2\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ước lượng tối ưu:&lt;/strong&gt; &lt;strong&gt;Trung bình hậu nghiệm (Posterior mean)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

\[\hat{\theta} = E[\theta \mid D] = \int \theta \, p(\theta \mid D) d\theta\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ý nghĩa:&lt;/strong&gt; Phạt rất nặng sai số lớn (sai số tăng gấp đôi thì tổn thất tăng gấp bốn). Phù hợp khi cần tránh sai lệch lớn và quan tâm đến mức trung bình kỳ vọng (chẳng hạn dự báo doanh thu hoặc hoạch định nhân sự tổng đài).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; Với Beta\((17, 103)\), trung bình là \(\frac{17}{120} = 0.1417\); với Gamma\((38, 5.5)\), trung bình là \(\frac{38}{5.5} = 6.91\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Hàm tổn thất trị tuyệt đối (Absolute loss)&lt;/strong&gt;&lt;/p&gt;

\[L(\theta, \hat{\theta}) = |\theta - \hat{\theta}|\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ước lượng tối ưu:&lt;/strong&gt; &lt;strong&gt;Trung vị hậu nghiệm (Posterior median)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

\[P(\theta \leq \hat{\theta} \mid D) = 0.5\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ý nghĩa:&lt;/strong&gt; Phạt sai số theo tỷ lệ tuyến tính thay vì phóng đại sai số lớn như tổn thất bình phương, nên bền vững hơn trước phần đuôi dài và cân bằng khối lượng xác suất giữa hai phía của phân phối.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; Với Beta\((17, 103)\), trung vị vào khoảng \(0.1397\) (nằm giữa mode và mean).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. Hàm tổn thất 0–1 (0–1 loss)&lt;/strong&gt;&lt;/p&gt;

\[L(\theta, \hat{\theta}) = \begin{cases}
0 &amp;amp; \text{nếu } \theta = \hat{\theta} \\
1 &amp;amp; \text{nếu } \theta \neq \hat{\theta}
\end{cases}\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ước lượng tối ưu:&lt;/strong&gt; &lt;strong&gt;Yếu vị hậu nghiệm (Posterior mode / MAP)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

\[\hat{\theta} = \arg\max_{\theta} p(\theta \mid D)\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ý nghĩa:&lt;/strong&gt; Chỉ phân biệt đúng hoặc sai mà không phân biệt sai lệch lớn hay nhỏ. Phù hợp khi cần chọn giá trị đơn lẻ có mật độ hoặc xác suất hậu nghiệm cao nhất, tiêu biểu như bài toán phân loại (chọn lớp có xác suất hậu nghiệm cao nhất).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; Với Beta\((17, 103)\), mode là \(\frac{17-1}{120-2} = \frac{16}{118} = 0.1356\); với Gamma\((38, 5.5)\), mode là \(\frac{38-1}{5.5} = \frac{37}{5.5} = 6.73\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;vì-sao-ba-ước-lượng-điểm-này-khác-nhau&quot;&gt;Vì sao ba ước lượng điểm này khác nhau?&lt;/h4&gt;

&lt;p&gt;Với &lt;strong&gt;phân phối đối xứng&lt;/strong&gt; như Normal, ba giá trị này trùng nhau:&lt;/p&gt;

\[\text{Mode} = \text{Median} = \text{Mean}.\]

&lt;p&gt;Ngược lại, với &lt;strong&gt;phân phối lệch phải&lt;/strong&gt; như Beta\((17, 103)\) hoặc phân phối Gamma, phần đuôi dài bên phải kéo trung bình sang phải, còn yếu vị nằm tại đỉnh và trung vị chia đôi diện tích:&lt;/p&gt;

\[\text{Mode} &amp;lt; \text{Median} &amp;lt; \text{Mean}.\]

&lt;p&gt;Cụ thể với Beta\((17, 103)\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Mode (MAP) \(= 0.1356\) (đỉnh đường cong)&lt;/li&gt;
  &lt;li&gt;Median \(\approx 0.1397\) (điểm chia đôi diện tích)&lt;/li&gt;
  &lt;li&gt;Mean \(= 0.1417\) (bị kéo về phía đuôi phải)&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;hàm-tổn-thất-và-lý-thuyết-quyết-định-bayes&quot;&gt;Hàm tổn thất và lý thuyết quyết định Bayes&lt;/h4&gt;

&lt;p&gt;Hàm tổn thất là nền tảng của &lt;strong&gt;lý thuyết quyết định Bayes (Bayesian decision theory)&lt;/strong&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Posterior chưa phải bước cuối cùng.&lt;/strong&gt; Quyết định tối ưu phụ thuộc vào cả &lt;strong&gt;posterior&lt;/strong&gt; (từ dữ liệu và prior) lẫn &lt;strong&gt;hàm tổn thất&lt;/strong&gt; (từ bối cảnh và mục tiêu thực tế).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Đây là điểm khác biệt quan trọng so với MLE cổ điển: thống kê Bayes cung cấp toàn bộ phân phối hậu nghiệm và cho phép chọn ước lượng điểm tối ưu theo đúng hàm tổn thất của bài toán.&lt;/p&gt;

&lt;h4 id=&quot;ví-dụ-thực-tế-thử-nghiệm-ab&quot;&gt;Ví dụ thực tế: thử nghiệm A/B&lt;/h4&gt;

&lt;p&gt;Giả sử sau thử nghiệm A/B, ta thu được posterior:&lt;/p&gt;

\[\theta \mid D \sim \text{Beta}(17, 103).\]

&lt;p&gt;Khi cần báo cáo một con số cho tỷ lệ chuyển đổi:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Nếu cần báo cáo &lt;strong&gt;hiệu suất trung bình kỳ vọng&lt;/strong&gt; cho quản lý, chọn &lt;strong&gt;Mean&lt;/strong&gt; (\(0.1417\), tương ứng tổn thất bình phương).&lt;/li&gt;
  &lt;li&gt;Nếu cần một &lt;strong&gt;ước lượng bền vững&lt;/strong&gt; ít chịu ảnh hưởng của phần đuôi, chọn &lt;strong&gt;Median&lt;/strong&gt; (\(0.1397\), tương ứng tổn thất trị tuyệt đối).&lt;/li&gt;
  &lt;li&gt;Nếu chỉ cần &lt;strong&gt;giá trị có mật độ cao nhất&lt;/strong&gt;, chọn &lt;strong&gt;Mode / MAP&lt;/strong&gt; (\(0.1356\), tương ứng tổn thất 0–1).&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;bảng-tóm-tắt&quot;&gt;Bảng tóm tắt&lt;/h4&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Hàm tổn thất&lt;/th&gt;
      &lt;th&gt;Ước lượng tối ưu&lt;/th&gt;
      &lt;th&gt;Bối cảnh phù hợp&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Bình phương&lt;/strong&gt; \((\theta-\hat{\theta})^2\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Mean&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Phạt nặng sai số lớn, quan tâm giá trị kỳ vọng&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Trị tuyệt đối&lt;/strong&gt; \(\Vert\theta-\hat{\theta}\Vert\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Median&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Bền vững trước đuôi dài, cân bằng hai phía&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;0–1&lt;/strong&gt; (đúng/sai)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Mode (MAP)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Cần giá trị đơn lẻ có khả năng cao nhất&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Quy tắc chọn ước lượng điểm tương ứng với từng hàm tổn thất không phải quy ước tùy tiện, mà là kết quả toán học trực tiếp từ việc cực tiểu hóa tổn thất kỳ vọng hậu nghiệm.&lt;/p&gt;

&lt;h2 id=&quot;6-prior-hỗn-hợp-khi-một-phân-phối-đơn-là-chưa-đủ&quot;&gt;6. Prior hỗn hợp: khi một phân phối đơn là chưa đủ&lt;/h2&gt;

&lt;p&gt;Đôi khi kiến thức ban đầu không thể gói gọn trong một phân phối đơn lẻ. Giả sử bạn cần suy luận tỷ lệ mua hàng \(\theta\) của một chiến dịch mới. Nhóm vận hành cho biết chiến dịch có thể rơi vào một trong hai kịch bản: khá yếu với tỷ lệ quanh \(10\%\), hoặc khá tốt với tỷ lệ quanh \(30\%\), và trước khi có dữ liệu cả hai kịch bản đều đáng cân nhắc.&lt;/p&gt;

&lt;p&gt;Thay vì ép vào một phân phối Beta duy nhất, ta dùng &lt;strong&gt;prior hỗn hợp (mixture prior)&lt;/strong&gt;:&lt;/p&gt;

\[p(\theta) = w_1 p_1(\theta) + w_2 p_2(\theta), \qquad w_1 + w_2 = 1.\]

&lt;p&gt;Ví dụ:&lt;/p&gt;

\[p(\theta) = 0.6 \,\text{Beta}(2,18) + 0.4 \,\text{Beta}(6,14).\]

&lt;p&gt;Prior này diễn đạt rằng trước khi có dữ liệu, ta đặt xác suất \(0.6\) cho kịch bản “yếu hơn” và \(0.4\) cho kịch bản “tốt hơn”, đồng thời mô tả \(\theta\) trong từng kịch bản bằng một phân phối Beta tương ứng. Như vậy, mixture prior không chỉ biểu diễn việc \(\theta\) có thể nằm ở nhiều vùng, mà còn thể hiện sự phân vân giữa nhiều kịch bản ban đầu khác nhau.&lt;/p&gt;

&lt;p&gt;Sau khi quan sát dữ liệu, posterior thực hiện đồng thời hai phép cập nhật: cập nhật từng phân phối thành phần như bình thường và cập nhật lại trọng số của các kịch bản dựa trên mức độ ủng hộ của dữ liệu. Tổng quát, nếu:&lt;/p&gt;

\[p(\theta)=\sum_{k=1}^K w_k p_k(\theta),\]

&lt;p&gt;thì posterior cũng là một phân phối hỗn hợp:&lt;/p&gt;

\[p(\theta\mid D)=\sum_{k=1}^K \tilde w_k\,p_k(\theta\mid D),\]

&lt;p&gt;với trọng số hậu nghiệm:&lt;/p&gt;

\[\tilde w_k=\frac{w_k\,p(D\mid M_k)}{\sum_{j=1}^K w_j\,p(D\mid M_j)},\]

&lt;p&gt;trong đó \(p(D\mid M_k)\) là marginal likelihood của nhánh prior thứ \(k\).&lt;/p&gt;

&lt;p&gt;Xét ví dụ nhanh với hai kịch bản:&lt;/p&gt;

\[w_1=0.6,\; w_2=0.4,
\quad p(D\mid M_1)=0.10,\; p(D\mid M_2)=0.30.\]

&lt;p&gt;Khi đó:&lt;/p&gt;

\[\tilde w_1=\frac{0.6\times0.10}{0.6\times0.10+0.4\times0.30}=\frac{1}{3},
\quad
\tilde w_2=\frac{2}{3}.\]

&lt;p&gt;Dữ liệu đã kéo trọng số niềm tin từ kịch bản 1 sang kịch bản 2. Khác biệt cốt lõi giữa prior đơn và prior hỗn hợp là: với prior đơn, dữ liệu chỉ cập nhật tham số; còn với prior hỗn hợp, dữ liệu cập nhật cả &lt;strong&gt;tham số&lt;/strong&gt; lẫn &lt;strong&gt;mức độ tin cậy tương đối giữa các kịch bản&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;61-tính-kỳ-vọng-và-phương-sai-của-phân-phối-hỗn-hợp&quot;&gt;6.1. Tính kỳ vọng và phương sai của phân phối hỗn hợp&lt;/h3&gt;

&lt;p&gt;Xét phân phối hỗn hợp gồm \(K\) thành phần:&lt;/p&gt;

\[p(\theta) = \sum_{k=1}^K w_k p_k(\theta),\]

&lt;p&gt;trong đó thành phần thứ \(k\) có kỳ vọng \(\mu_k\) và phương sai \(\sigma_k^2\).&lt;/p&gt;

&lt;h4 id=&quot;công-thức-kỳ-vọng&quot;&gt;Công thức kỳ vọng&lt;/h4&gt;

&lt;p&gt;Kỳ vọng của phân phối hỗn hợp là trung bình có trọng số của các kỳ vọng thành phần:&lt;/p&gt;

\[E[\theta] = \sum_{k=1}^K w_k \mu_k.\]

&lt;h4 id=&quot;công-thức-phương-sai&quot;&gt;Công thức phương sai&lt;/h4&gt;

&lt;p&gt;Áp dụng định lý phương sai toàn phần (law of total variance):&lt;/p&gt;

\[\text{Var}(\theta) = E[\theta^2] - (E[\theta])^2,\]

&lt;p&gt;trong đó mô-men bậc hai là trung bình có trọng số của các mô-men bậc hai thành phần (\(E[\theta^2 \mid k] = \sigma_k^2 + \mu_k^2\)):&lt;/p&gt;

\[E[\theta^2] = \sum_{k=1}^K w_k (\sigma_k^2 + \mu_k^2).\]

&lt;p&gt;Kết hợp lại, ta thu được:&lt;/p&gt;

\[\text{Var}(\theta) = \sum_{k=1}^K w_k (\sigma_k^2 + \mu_k^2) - \left(\sum_{k=1}^K w_k \mu_k\right)^2.\]

&lt;h4 id=&quot;ví-dụ-1-phân-phối-hỗn-hợp-2-thành-phần-beta&quot;&gt;Ví dụ 1: phân phối hỗn hợp 2 thành phần Beta&lt;/h4&gt;

&lt;p&gt;Nhắc lại ví dụ trên:&lt;/p&gt;

\[p(\theta) = 0.6 \,\text{Beta}(2,18) + 0.4 \,\text{Beta}(6,14).\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thành phần 1:&lt;/strong&gt; Beta\((2,18)\)&lt;/li&gt;
&lt;/ul&gt;

\[\mu_1 = \frac{2}{2+18} = 0.1, \quad \sigma_1^2 = \frac{2 \times 18}{(2+18)^2(2+18+1)} = \frac{36}{400 \times 21} = 0.00429\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thành phần 2:&lt;/strong&gt; Beta\((6,14)\)&lt;/li&gt;
&lt;/ul&gt;

\[\mu_2 = \frac{6}{6+14} = 0.3, \quad \sigma_2^2 = \frac{6 \times 14}{(6+14)^2(6+14+1)} = \frac{84}{400 \times 21} = 0.01\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Kỳ vọng của phân phối hỗn hợp:&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

\[E[\theta] = 0.6 \times 0.1 + 0.4 \times 0.3 = 0.06 + 0.12 = 0.18\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô-men bậc hai \(E[\theta^2]\):&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

\[E[\theta^2] = 0.6 \times (0.00429 + 0.1^2) + 0.4 \times (0.01 + 0.3^2)\]

\[= 0.6 \times 0.01429 + 0.4 \times 0.1 = 0.00857 + 0.04 = 0.04857\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phương sai và độ lệch chuẩn:&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

\[\text{Var}(\theta) = 0.04857 - 0.18^2 = 0.04857 - 0.0324 = 0.01617\]

\[\text{SD}(\theta) = \sqrt{0.01617} \approx 0.127\]

&lt;h4 id=&quot;ví-dụ-2-phân-phối-hỗn-hợp-3-thành-phần-normal&quot;&gt;Ví dụ 2: phân phối hỗn hợp 3 thành phần Normal&lt;/h4&gt;

&lt;p&gt;Xét prior hỗn hợp cho tham số trung bình \(\mu\):&lt;/p&gt;

\[p(\mu) = 0.25 \, N(1.4, 0.4^2) + 0.45 \, N(2.1, 0.5^2) + 0.30 \, N(2.8, 0.6^2).\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Kỳ vọng:&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

\[E[\mu] = 0.25 \times 1.4 + 0.45 \times 2.1 + 0.30 \times 2.8\]

\[= 0.35 + 0.945 + 0.84 = 2.135\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô-men bậc hai \(E[\mu^2]\):&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

\[E[\mu^2] = 0.25 \times (0.4^2 + 1.4^2) + 0.45 \times (0.5^2 + 2.1^2) + 0.30 \times (0.6^2 + 2.8^2)\]

\[= 0.25 \times 2.12 + 0.45 \times 4.66 + 0.30 \times 8.2\]

\[= 0.53 + 2.097 + 2.46 = 5.087\]

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phương sai và độ lệch chuẩn:&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

\[\text{Var}(\mu) = 5.087 - 2.135^2 = 5.087 - 4.558 = 0.529\]

\[\text{SD}(\mu) = \sqrt{0.529} \approx 0.727\]

&lt;h4 id=&quot;vì-sao-phương-sai-của-phân-phối-hỗn-hợp-lớn-hơn&quot;&gt;Vì sao phương sai của phân phối hỗn hợp lớn hơn?&lt;/h4&gt;

&lt;p&gt;Phương sai của phân phối hỗn hợp thường lớn hơn trung bình phương sai của các thành phần, vì nó cộng gộp cả độ bất định &lt;strong&gt;bên trong&lt;/strong&gt; mỗi thành phần (\(\sigma_k^2\)) lẫn độ bất định &lt;strong&gt;giữa&lt;/strong&gt; các thành phần (do các kỳ vọng \(\mu_k\) khác nhau). Trong Ví dụ 2:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Trung bình phương sai các thành phần: \(0.25 \times 0.16 + 0.45 \times 0.25 + 0.30 \times 0.36 = 0.26\)&lt;/li&gt;
  &lt;li&gt;Phương sai của phân phối hỗn hợp: \(0.529\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Phương sai tổng lớn hơn gấp đôi phương sai trung bình của các thành phần; phần chênh lệch này là &lt;strong&gt;phương sai giữa các thành phần (between-component variance)&lt;/strong&gt;, phản ánh sự không chắc chắn về việc thực tế thuộc kịch bản nào trong ba kịch bản có trung bình khác nhau.&lt;/p&gt;

&lt;p&gt;Khi làm việc với prior hỗn hợp, cần phân biệt rõ hai đại lượng: phương sai từng thành phần \(\sigma_k^2\) (bất định nội tại của thành phần \(k\)) và phương sai toàn phần \(\text{Var}(\theta)\) (bất định tổng thể bao gồm cả bất định trong việc chọn thành phần).&lt;/p&gt;

&lt;h2 id=&quot;7-vì-sao-prior-hữu-ích-trong-thực-hành&quot;&gt;7. Vì sao prior hữu ích trong thực hành?&lt;/h2&gt;

&lt;h3 id=&quot;71-hạn-chế-ước-lượng-cực-đoan-khi-dữ-liệu-ít&quot;&gt;7.1. Hạn chế ước lượng cực đoan khi dữ liệu ít&lt;/h3&gt;

&lt;p&gt;Giả sử bạn tung đồng xu 3 lần và cả 3 lần đều ra mặt ngửa. Ước lượng MLE cho \(\hat{\theta} = 1\), nhưng kết luận “đồng xu chắc chắn ra ngửa 100%” là quá cực đoan với cỡ mẫu nhỏ như vậy. Một prior hợp lý như Beta\((2,2)\) sẽ kéo ước lượng về mức thận trọng hơn. Điều này phù hợp với thực tế: 3 khách hàng đầu tiên đều mua không có nghĩa tỷ lệ chuyển đổi là 100%, và 2 tuần đầu không có sự cố không đồng nghĩa dây chuyền hoàn hảo tuyệt đối.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_regularization_likelihood.png&quot; alt=&quot;Likelihood chỉ nhìn dữ liệu 3 trên 3 lần thành công&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_regularization_prior.png&quot; alt=&quot;Prior Beta(2,2) kéo suy luận về vùng hợp lý hơn&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_regularization_posterior.png&quot; alt=&quot;Posterior là kết quả dung hòa giữa prior và dữ liệu ít&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;video-ngắn-tung-3-lần-ra-cả-3-ngửa-prior-yếu-beta2-2-cứu-mô-hình-khỏi-cực-đoan-100&quot;&gt;Video ngắn: Tung 3 lần ra cả 3 Ngửa: Prior yếu Beta(2, 2) cứu mô hình khỏi cực đoan 100%!&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch02-03a-prior-regularization-3of3.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 17 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): Likelihood thuần đẩy MLE về đúng 1.00 (cho rằng mặt Sấp bất khả thi), còn Prior yếu Beta(2,2) kéo hậu nghiệm về Beta(5,2) có trung bình hợp lý 0.71.&lt;/p&gt;

&lt;h3 id=&quot;72-cho-phép-tích-lũy-tri-thức-liên-tục&quot;&gt;7.2. Cho phép tích lũy tri thức liên tục&lt;/h3&gt;

&lt;p&gt;Posterior từ nghiên cứu trước có thể trở thành prior cho nghiên cứu sau. Cơ chế này phù hợp với cách khoa học và kinh doanh vận hành: thông tin đã học được ở giai đoạn trước được kế thừa thay vì bỏ đi để bắt đầu lại từ đầu.&lt;/p&gt;

&lt;h3 id=&quot;73-minh-bạch-hóa-giả-định&quot;&gt;7.3. Minh bạch hóa giả định&lt;/h3&gt;

&lt;p&gt;Khi bạn sử dụng một prior mạnh, người đọc có thể nhận ra ngay, thảo luận, kiểm tra hoặc thử thay bằng một prior khác để đối chiếu. Sự minh bạch này là một giá trị quan trọng trong phân tích dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;8-kiểm-tra-dự-báo-tiền-nghiệm-prior-predictive-check&quot;&gt;8. Kiểm tra dự báo tiền nghiệm (Prior predictive check)&lt;/h2&gt;

&lt;p&gt;Một prior hợp lý không chỉ cần “nghe có vẻ đúng” ở cấp độ tham số, mà còn phải sinh ra dữ liệu mô phỏng hợp lý. Cách làm là lấy mẫu \(\theta\) từ prior, sau đó từ mỗi giá trị \(\theta\) sinh ra dữ liệu giả lập rồi kiểm tra xem dữ liệu giả lập có phi lý hay không.&lt;/p&gt;

&lt;p&gt;Ví dụ, nếu prior cho tỷ lệ qua môn thường xuyên sinh ra các lớp “gần như trượt hết” hoặc “gần như đậu toàn bộ” trong khi thực tế hiếm xảy ra điều đó, thì prior đang có vấn đề; tương tự, nếu prior cho chiều cao trung bình của lớp học sinh ra các giá trị như 120 cm hoặc 230 cm, prior đó rõ ràng không thực tế. Thói quen này buộc ta kiểm chứng prior bằng hệ quả dữ liệu cụ thể thay vì chỉ dựa vào cảm tính.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/prior_predictive_check.png&quot; alt=&quot;Kiểm tra prior predictive&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-prior-predictive--prior-này-mong-đợi-dữ-liệu-nào&quot;&gt;Thử nghiệm: prior predictive — prior này mong đợi dữ liệu nào?&lt;/h3&gt;

&lt;p&gt;Mô phỏng dữ liệu từ prior và so với công thức đóng; chọn k quan sát để xem prior có “bất ngờ” không.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;likelihood-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;predictive&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;thử-nghiệm-prior-mạnh-hay-yếu-dữ-liệu-kéo-posterior-đi-đâu&quot;&gt;Thử nghiệm: prior mạnh hay yếu, dữ liệu kéo posterior đi đâu?&lt;/h3&gt;

&lt;p&gt;Chọn prior Beta(1,1), Beta(2,2), Beta(10,10) hoặc Beta(8,2) và xem posterior thay đổi sau từng lần tung.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;conjugate-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;betabinom&quot; data-a=&quot;10&quot; data-b=&quot;10&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;video-ngắn-prior-predictive-check-thử-nghiệm-prior-trước-khi-chạm-dữ-liệu-thật&quot;&gt;Video ngắn: Prior Predictive Check: Thử nghiệm Prior TRƯỚC khi chạm Dữ liệu thật&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch02-03b-prior-predictive-sim.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): mô phỏng trực tiếp 80 thế giới giả lập: rút θ từ Prior Beta(5,5) rồi sinh số thành công k/100 để kiểm chứng Prior không tạo ra dự báo phi lý.&lt;/p&gt;

&lt;h2 id=&quot;9-phân-tích-độ-nhạy-sensitivity-analysis-posterior-phụ-thuộc-vào-prior-đến-mức-nào&quot;&gt;9. Phân tích độ nhạy (Sensitivity analysis): posterior phụ thuộc vào prior đến mức nào?&lt;/h2&gt;

&lt;p&gt;Một câu hỏi quan trọng trong thực hành Bayes là: &lt;strong&gt;nếu thay đổi prior trong phạm vi hợp lý, kết luận có thay đổi đáng kể không?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Nếu kết luận thay đổi mạnh, điều đó không nhất thiết là lỗi mô hình; nó cho thấy dữ liệu hiện có còn ít hoặc prior đang đóng vai trò lớn, nên cần báo cáo kết quả một cách minh bạch và thận trọng. Khi dữ liệu ngày càng nhiều, các prior hợp lý khác nhau thường hội tụ về những posterior khá tương đồng: dữ liệu ít thì prior có trọng lượng lớn, dữ liệu nhiều thì likelihood dần chi phối.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/prior_sensitivity_weak_data.png&quot; alt=&quot;Độ nhạy với prior khi dữ liệu yếu&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/prior_sensitivity_strong_data.png&quot; alt=&quot;Độ nhạy với prior khi dữ liệu mạnh&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;10-những-phản-đối-thường-gặp-về-prior&quot;&gt;10. Những phản đối thường gặp về prior&lt;/h2&gt;

&lt;h3 id=&quot;101-prior-quá-chủ-quan&quot;&gt;10.1. “Prior quá chủ quan”&lt;/h3&gt;

&lt;p&gt;Mọi phân tích thống kê đều chứa giả định — từ việc chọn mô hình, chọn biến đến cách đo lường. Prior không tự tạo ra tính chủ quan, mà buộc ta công khai các giả định đó để người khác có thể kiểm tra và phản biện.&lt;/p&gt;

&lt;h3 id=&quot;102-cứ-để-dữ-liệu-tự-nói-là-đủ&quot;&gt;10.2. “Cứ để dữ liệu tự nói là đủ”&lt;/h3&gt;

&lt;p&gt;Dữ liệu không thể tự đưa ra kết luận nếu thiếu mô hình và giả định. Ngay cả việc chọn phân phối Binomial, Poisson hay Normal cũng đã là một hình thức đưa kiến thức nền vào phân tích.&lt;/p&gt;

&lt;h3 id=&quot;103-prior-mạnh-là-thiếu-công-bằng&quot;&gt;10.3. “Prior mạnh là thiếu công bằng”&lt;/h3&gt;

&lt;p&gt;Prior mạnh chỉ gây vấn đề khi không có cơ sở rõ ràng hoặc không được báo cáo minh bạch. Nếu bạn thực sự có bằng chứng vững chắc từ nhiều nghiên cứu trước, việc sử dụng prior mạnh là hoàn toàn hợp lý.&lt;/p&gt;

&lt;h2 id=&quot;11-nguyên-tắc-thực-hành-khi-chọn-prior&quot;&gt;11. Nguyên tắc thực hành khi chọn prior&lt;/h2&gt;

&lt;p&gt;Một quy trình chọn prior chặt chẽ nên bắt đầu từ bối cảnh bài toán thay vì công thức: chọn họ phân phối phù hợp với miền giá trị của tham số, diễn đạt prior bằng lời trước khi chốt các tham số số học, thực hiện prior predictive check, tiến hành phân tích độ nhạy với một vài prior hợp lý khác nhau, và cuối cùng báo cáo rõ prior đã chọn cùng căn cứ của lựa chọn đó.&lt;/p&gt;

&lt;h2 id=&quot;12-prior-trong-quy-trình-likelihood--prior--posterior-ví-dụ-phân-phối-mũ&quot;&gt;12. Prior trong quy trình likelihood – prior – posterior: ví dụ phân phối mũ&lt;/h2&gt;

&lt;p&gt;Tiếp nối ví dụ thời gian chờ cuộc gọi theo phân phối mũ ở Bài 2.2:&lt;/p&gt;

\[X_i \mid \lambda \sim \text{Exp}(\lambda), \quad i=1,\dots,n.\]

&lt;p&gt;Likelihood theo tham số tốc độ \(\lambda\) là:&lt;/p&gt;

\[\mathcal{L}(\lambda\mid x_{1:n}) \propto \lambda^n \exp\left(-\lambda\sum x_i\right).\]

&lt;p&gt;Vì \(\lambda&amp;gt;0\), một prior tự nhiên là phân phối Gamma theo tham số hóa shape–rate:&lt;/p&gt;

\[\lambda \sim \text{Gamma}(\alpha_0,\beta_0),\]

&lt;p&gt;với mật độ tỉ lệ:&lt;/p&gt;

\[p(\lambda) \propto \lambda^{\alpha_0-1}e^{-\beta_0\lambda}.\]

&lt;p&gt;Điểm quan trọng là đọc được ý nghĩa của mô hình:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Hai tham số \(\alpha_0,\beta_0\) mã hóa kiến thức ban đầu về tốc độ xảy ra sự kiện.&lt;/li&gt;
  &lt;li&gt;Prior thể hiện nhận định trước dữ liệu về việc thời gian chờ thường ngắn hay dài.&lt;/li&gt;
  &lt;li&gt;Sự kết hợp giữa prior này và likelihood ở trên sẽ trực tiếp tạo thành posterior ở bài học tiếp theo.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Khung tư duy này kết nối ba bài 2.2, 2.3 và 2.4 thành một chuỗi cập nhật liên tục thay vì ba phần kiến thức rời rạc.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Prior là cách biểu diễn kiến thức ban đầu một cách minh bạch.&lt;/strong&gt; Một prior tốt không cần “đúng tuyệt đối”, nhưng phải phù hợp với miền giá trị tham số, phản ánh hợp lý mức độ hiểu biết hiện có, không tạo ra dữ liệu giả lập phi thực tế và cần được kiểm tra độ nhạy. Nói ngắn gọn, prior không phải là đoán mò mà là cách mã hóa kiến thức, ràng buộc và mức độ bất định trước dữ liệu; một prior tốt phải diễn giải được bằng lời; và prior predictive check cùng phân tích độ nhạy là hai thói quen thiết yếu để kiểm chứng prior.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-chuyển-lời-nói-chuyên-gia-thành-tham-số-prior-và-kiểm-tra-độ-nhạy&quot;&gt;Giải thích: Chuyển lời nói chuyên gia thành tham số Prior và kiểm tra độ nhạy&lt;/h2&gt;

&lt;p&gt;Khi cần đặt một prior cho tỷ lệ \(p \in (0, 1)\), hãy thực hiện chậm rãi theo 4 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Xác định tâm kỳ vọng \(\mu\) từ kiến thức miền:&lt;/strong&gt; Ví dụ chuyên gia ước lượng tỷ lệ nhấp chuột quanh mức \(20\%\) (\(\mu = 0.20\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chọn cỡ mẫu ảo \(M = \alpha + \beta\) theo mức độ chắc chắn:&lt;/strong&gt; Nếu chỉ khá mơ hồ, chọn \(M = 10\); nếu có nhiều lịch sử tương tự, chọn \(M = 50\) hoặc \(100\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy đổi thành tham số Beta:&lt;/strong&gt; \(\alpha = \mu M\) và \(\beta = (1 - \mu) M\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chạy phân tích độ nhạy sau khi có dữ liệu:&lt;/strong&gt; So sánh hậu nghiệm dưới 2–3 lựa chọn prior khác nhau để xem kết luận có bền vững không.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-phân-tích-độ-nhạy-với-dữ-liệu-k--6-thành-công-trên-n--20-lần-thử&quot;&gt;Ví dụ tính toán làm từng bước: Phân tích độ nhạy với dữ liệu \(k = 6\) thành công trên \(n = 20\) lần thử&lt;/h3&gt;

&lt;p&gt;Quan sát tỷ lệ mẫu \(\hat p = 6/20 = 0.300\). Hãy so sánh hậu nghiệm \(\text{Beta}(\alpha + 6, \beta + 14)\) dưới ba lựa chọn prior khác nhau:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Loại Prior&lt;/th&gt;
      &lt;th&gt;Công thức Prior&lt;/th&gt;
      &lt;th&gt;Cỡ mẫu ảo \(M\)&lt;/th&gt;
      &lt;th&gt;Hậu nghiệm&lt;/th&gt;
      &lt;th&gt;Kỳ vọng hậu nghiệm \(\mathbb{E}[p \vert y]\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Phẳng (Flat)&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(1, 1)\)&lt;/td&gt;
      &lt;td&gt;\(2\)&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(7, 15)\)&lt;/td&gt;
      &lt;td&gt;\(7 / 22 \approx 0.318\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Thông tin yếu quanh 0.2&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(2, 8)\)&lt;/td&gt;
      &lt;td&gt;\(10\)&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(8, 22)\)&lt;/td&gt;
      &lt;td&gt;\(8 / 30 \approx 0.267\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Rất mạnh quanh 0.2&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(20, 80)\)&lt;/td&gt;
      &lt;td&gt;\(100\)&lt;/td&gt;
      &lt;td&gt;\(\text{Beta}(26, 94)\)&lt;/td&gt;
      &lt;td&gt;\(26 / 120 \approx 0.217\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Bảng trên cho thấy rõ vai trò cân bằng: với prior thông tin yếu (\(M = 10\)), dữ liệu (\(n = 20\)) chiếm \(2/3\) trọng số nên kỳ vọng dịch chuyển hợp lý từ \(0.200\) lên \(0.267\); trong khi prior quá mạnh (\(M = 100\)) áp đảo dữ liệu gấp 5 lần và giữ chặt kỳ vọng ở \(0.217\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nghĩ rằng chọn prior đều \(\text{Uniform}(0,1)\) là luôn “khách quan tuyệt đối”. Nếu bạn biến đổi sang thang log-odds \(\eta = \log\frac{p}{1-p}\), một prior đều trên \(p\) tương ứng với phân phối Logistic trên \(\eta\), còn một prior đều trên \(\eta\) lại chất đống xác suất vào hai cực \(p=0\) và \(p=1\)!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu cỡ mẫu thật tăng lên \(n = 200\) với \(k = 60\) (vẫn 30%), ngay cả dưới prior thông tin yếu \(\text{Beta}(2, 8)\), kỳ vọng hậu nghiệm trở thành \(62 / 210 \approx 0.295\) — dữ liệu đã hoàn toàn áp đảo prior.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=brt2J5VgAHs&quot;&gt;Bayesian Statistics: What Are Priors?&lt;/a&gt; — Academia Elevated, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Giới thiệu prior như niềm tin được phát biểu trước dữ liệu, hỗ trợ bước chuyển kiến thức bằng lời thành phân phối.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Bayesian Priors Explained&lt;/td&gt;
          &lt;td&gt;Prior Modelling &amp;amp; Prior Predictive Checks](https://www.youtube.com/watch?v=G3ludfAUAng) — stats 4 good, English. Minh họa prior predictive check như công cụ kiểm tra xem prior có sinh ra dữ liệu phi lý hay không.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=UH6-9FU6bRg&quot;&gt;Keynote 2: Weakly Informative Priors – Andrew Gelman&lt;/a&gt; — AISTATS 2014, English. Bài trình bày của Andrew Gelman về prior thông tin yếu, bổ trợ cho phần lựa chọn prior cân bằng.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Hãy chọn một bài toán thực tế của bạn và viết ba câu mô tả kiến thức ban đầu về tham số quan tâm.&lt;/li&gt;
  &lt;li&gt;Với tỷ lệ sinh viên qua môn, vì sao họ phân phối Beta là lựa chọn prior tự nhiên?&lt;/li&gt;
  &lt;li&gt;Trong những tình huống nào bạn nên dùng prior yếu thay vì prior mạnh?&lt;/li&gt;
  &lt;li&gt;Hãy giải thích bằng lời mục đích của prior predictive check.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 2.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2-3.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 6.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter02/02_04_posterior/&quot;&gt;2.4 Posterior - Cập nhật Niềm tin với Dữ liệu&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 2.2: Likelihood - Câu chuyện về Dữ liệu và Mô hình</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_02_likelihood/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_02_likelihood</id>
   <content type="html">&lt;p&gt;Năm 1921, Ronald Fisher đưa ra một sự phân biệt tinh tế nhưng làm thay đổi toàn bộ ngôn ngữ thống kê hiện đại: ông tách riêng từ &lt;strong&gt;xác suất (probability)&lt;/strong&gt; khỏi từ &lt;strong&gt;hàm hợp lý (likelihood)&lt;/strong&gt;. Cùng một biểu thức toán học \(p(y \mid \theta)\), nhưng khi ta cố định tham số \(\theta\) để dự đoán dữ liệu \(y\), đó là xác suất; còn khi dữ liệu \(y\) đã nằm trên bàn và ta cho \(\theta\) chạy để xem giả thuyết nào giải thích dữ liệu tốt nhất, đó chính là &lt;strong&gt;likelihood&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Trong định lý Bayes, likelihood đóng vai trò &lt;strong&gt;cỗ máy chuyển hóa dữ liệu thành bằng chứng&lt;/strong&gt;: nó kéo phân phối prior về phía những vùng tham số làm cho dữ liệu quan sát được trở nên hợp lý nhất.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn cần hiểu likelihood (hàm hợp lý) như công cụ &lt;strong&gt;so sánh các giả thuyết dựa trên dữ liệu&lt;/strong&gt;. Bạn cũng cần tránh nhầm lẫn phổ biến nhất: likelihood không phải là xác suất của tham số. Cuối cùng, bạn cần biết cách xây dựng likelihood từ một câu chuyện sinh dữ liệu đơn giản.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ mini.&lt;/strong&gt; Bạn tung đồng xu 10 lần và thấy 7 mặt ngửa. Dữ liệu này phù hợp hơn với đồng xu cân bằng \(\theta=0.5\) hay với đồng xu thiên lệch \(\theta=0.7\)?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Likelihood trả lời về “xác suất của dữ liệu” hay “xác suất của tham số”?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hàm-hợp-lý-nguyên-lý-hợp-lý-và-tối-đa-hóa-log-likelihood&quot;&gt;Kiến thức cần nhớ: Hàm hợp lý, Nguyên lý hợp lý và Tối đa hóa Log-Likelihood&lt;/h2&gt;

&lt;p&gt;Để không bao giờ nhầm lẫn giữa likelihood và xác suất hậu nghiệm, hãy nắm vững ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đối ngẫu Xác suất – Hợp lý (Probability vs. Likelihood):&lt;/strong&gt; Với \(\theta\) cố định, \(y \mapsto p(y \mid \theta)\) là một phân phối xác suất có tổng/tích phân bằng 1 theo \(y\). Với \(y\) cố định, \(\theta \mapsto L(\theta; y) = p(y \mid \theta)\) là hàm hợp lý — &lt;strong&gt;không&lt;/strong&gt; phải phân phối xác suất theo \(\theta\) và tích phân theo \(\theta\) nói chung không bằng 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hằng số tỷ lệ và Log-Likelihood:&lt;/strong&gt; Trong suy diễn Bayes lẫn MLE, mọi thừa số không phụ thuộc \(\theta\) (như hệ số tổ hợp \(\binom{n}{k}\)) đều rút gọn khi chuẩn hóa hoặc đạo hàm. Làm việc trên log-likelihood \(\ell(\theta) = \sum_{i=1}^n \log p(y_i \mid \theta)\) giúp chuyển tích thành tổng và tìm cực đại dễ dàng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Thống kê Bayes (MLE vs. Posterior):&lt;/strong&gt; MLE chỉ tìm một điểm đỉnh duy nhất \(\hat\theta_{\text{MLE}} = \arg\max_\theta \ell(\theta)\), còn thống kê Bayes giữ toàn bộ đường cong \(L(\theta; y)\), nhân với prior \(p(\theta)\) và chuẩn hóa để giữ trọn vẹn độ bất định.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mở-đầu-dữ-liệu-đang-ủng-hộ-giả-thuyết-nào&quot;&gt;Mở đầu: dữ liệu đang ủng hộ giả thuyết nào?&lt;/h2&gt;

&lt;p&gt;Giả sử bạn muốn kiểm tra xem một đồng xu có bị lệch hay không; bạn tung 10 lần và thu được 7 mặt ngửa. Lúc này, câu hỏi trọng tâm không phải là “xác suất của dữ liệu là bao nhiêu?” một cách chung chung, mà là những câu hỏi cụ thể gắn với từng giả thuyết: nếu \(\theta = 0.5\) thì dữ liệu này hợp lý đến mức nào, nếu \(\theta = 0.7\) thì sao, và nếu \(\theta = 0.1\) thì dữ liệu ấy có còn khả dĩ không. Likelihood được xây dựng để trả lời đúng kiểu câu hỏi này.&lt;/p&gt;

&lt;h2 id=&quot;1-likelihood-là-gì&quot;&gt;1. Likelihood là gì?&lt;/h2&gt;

&lt;p&gt;Với dữ liệu đã quan sát \(D\), likelihood của tham số \(\theta\) được định nghĩa là:&lt;/p&gt;

\[\mathcal{L}(\theta \mid D) = P(D \mid \theta).\]

&lt;p&gt;Điểm cốt lõi là dữ liệu \(D\) giờ đây &lt;strong&gt;được giữ cố định&lt;/strong&gt;, còn ta cho \(\theta\) thay đổi để đánh giá xem giá trị tham số nào làm cho chính bộ dữ liệu đã quan sát trở nên hợp lý hơn. Nói một cách ngắn gọn: &lt;strong&gt;likelihood đo mức độ giải thích dữ liệu của từng giả thuyết về tham số.&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-ví-dụ-trực-giác-đồng-xu-7-mặt-ngửa-trong-10-lần-tung&quot;&gt;2. Ví dụ trực giác: đồng xu 7 mặt ngửa trong 10 lần tung&lt;/h2&gt;

&lt;p&gt;Gọi \(\theta\) là xác suất ra mặt ngửa. Với dữ liệu 7 mặt ngửa trong 10 lần tung độc lập:&lt;/p&gt;

\[\mathcal{L}(\theta \mid D) = \binom{10}{7}\theta^7(1-\theta)^3.\]

&lt;p&gt;Khi thử các giá trị khác nhau của \(\theta\), ta thấy \(\theta = 0.7\) giải thích dữ liệu khá tốt, \(\theta = 0.5\) vẫn hợp lý nhưng kém hơn, còn \(\theta = 0.1\) khiến dữ liệu trở nên rất khó xảy ra. Điều ta quan tâm nhất không phải là một giá trị likelihood đứng riêng lẻ, mà là giả thuyết nào có likelihood cao hơn, cao hơn bao nhiêu lần, và vùng giá trị nào của tham số đang được dữ liệu ủng hộ rõ nhất.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/likelihood_function.png&quot; alt=&quot;Hàm likelihood cho dữ liệu 7 ngửa trong 10 lần tung&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;21-đọc-ví-dụ-bằng-con-số&quot;&gt;2.1. Đọc ví dụ bằng con số&lt;/h3&gt;

&lt;p&gt;Tính trực tiếp tại ba giá trị ứng viên:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
\[\mathcal{L}(0.7 \mid D) \approx 0.267\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathcal{L}(0.5 \mid D) \approx 0.117\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathcal{L}(0.9 \mid D) \approx 0.057\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Như vậy, dữ liệu 7 ngửa trong 10 lần tung ủng hộ giả thuyết \(\theta=0.7\) mạnh gấp khoảng \(2.28\) lần so với \(\theta=0.5\), và gấp khoảng \(4.65\) lần so với \(\theta=0.9\). Quan sát 7/10 không có nghĩa là tham số thực chắc chắn bằng \(0.7\), mà chỉ cho thấy vùng quanh \(0.7\) giải thích dữ liệu tốt hơn đáng kể so với các giá trị ứng viên khác.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-likelihood--xác-suất-quét-giả-thuyết-θ-trên-dữ-liệu-710-ngửa&quot;&gt;Video ngắn: Likelihood ≠ Xác suất: Quét Giả thuyết θ trên Dữ liệu 7/10 Ngửa&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch02-02a-likelihood-vs-probability.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 23 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): trượt mượt θ từ 0.20 → 0.90 trên cùng dữ liệu 7/10 Ngửa, đọc trực tiếp Tỷ số Hợp lý LR = 2.28× và chứng minh diện tích dưới đường Likelihood bằng 1/11 ≠ 1.&lt;/p&gt;

&lt;h2 id=&quot;3-likelihood-là-so-sánh-tương-đối-không-phải-xác-suất-tuyệt-đối&quot;&gt;3. Likelihood là so sánh tương đối, không phải xác suất tuyệt đối&lt;/h2&gt;

&lt;p&gt;Một cách diễn giải rõ ràng hơn là sử dụng &lt;strong&gt;tỷ số likelihood (likelihood ratio)&lt;/strong&gt;. Trong ví dụ trên, khi so sánh \(\theta = 0.7\) với \(\theta = 0.5\):&lt;/p&gt;

\[\frac{\mathcal{L}(0.7 \mid D)}{\mathcal{L}(0.5 \mid D)} \approx 2.28.\]

&lt;p&gt;Tỷ số này cho biết dữ liệu 7/10 làm cho giả thuyết \(\theta = 0.7\) hợp lý hơn khoảng 2.28 lần so với \(\theta = 0.5\). Đây là bản chất của likelihood: nó không cho biết “xác suất để \(\theta = 0.7\) là bao nhiêu”, mà cho biết dữ liệu ủng hộ \(\theta = 0.7\) mạnh hay yếu hơn bao nhiêu so với các giá trị khác.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/likelihood_ratio.png&quot; alt=&quot;Tỷ số likelihood giúp so sánh giả thuyết&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;4-phân-biệt-likelihood-và-xác-suất&quot;&gt;4. Phân biệt likelihood và xác suất&lt;/h2&gt;

&lt;p&gt;Đây là khái niệm thường khiến người học dễ nhầm lẫn.&lt;/p&gt;

&lt;h3 id=&quot;41-xác-suất&quot;&gt;4.1. Xác suất&lt;/h3&gt;

&lt;p&gt;Khi giữ \(\theta\) cố định và để dữ liệu \(D\) thay đổi, biểu thức:&lt;/p&gt;

\[P(D \mid \theta)\]

&lt;p&gt;là xác suất của dữ liệu — chẳng hạn: nếu đồng xu cân bằng (\(\theta = 0.5\)) thì xác suất quan sát đúng 7 mặt ngửa trong 10 lần tung là bao nhiêu.&lt;/p&gt;

&lt;h3 id=&quot;42-likelihood&quot;&gt;4.2. Likelihood&lt;/h3&gt;

&lt;p&gt;Khi giữ dữ liệu \(D\) cố định và để \(\theta\) thay đổi, cùng biểu thức đó được đọc như hàm likelihood:&lt;/p&gt;

\[\mathcal{L}(\theta \mid D).\]

&lt;p&gt;Lúc này nó là một hàm theo \(\theta\) chứ không phải phân phối xác suất của \(\theta\).&lt;/p&gt;

&lt;h3 id=&quot;43-vì-sao-likelihood-không-phải-là-xác-suất-của-tham-số&quot;&gt;4.3. Vì sao likelihood không phải là xác suất của tham số?&lt;/h3&gt;

&lt;p&gt;Khi lấy tích phân likelihood theo \(\theta\), kết quả nhìn chung &lt;strong&gt;không bằng 1&lt;/strong&gt;, nên nó không phải một phân phối xác suất hợp lệ trên không gian tham số. Điều này hoàn toàn tự nhiên: likelihood dùng để &lt;strong&gt;xếp hạng và so sánh mức độ phù hợp của dữ liệu&lt;/strong&gt;, không phải để thay thế cho phân phối hậu nghiệm (posterior).&lt;/p&gt;

&lt;h2 id=&quot;5-ba-ví-dụ-thực-tế-về-likelihood&quot;&gt;5. Ba ví dụ thực tế về likelihood&lt;/h2&gt;

&lt;h3 id=&quot;51-ví-dụ-1-tỷ-lệ-hồi-phục-sau-điều-trị&quot;&gt;5.1. Ví dụ 1: tỷ lệ hồi phục sau điều trị&lt;/h3&gt;

&lt;p&gt;Một nhóm bác sĩ thử nghiệm thuốc mới trên 15 bệnh nhân và ghi nhận 12 người hồi phục. Gọi \(\theta\) là xác suất hồi phục của thuốc, likelihood là:&lt;/p&gt;

\[\mathcal{L}(\theta \mid D) = \binom{15}{12}\theta^{12}(1-\theta)^3.\]

&lt;p&gt;Các giá trị \(\theta\) gần \(0.8\) được dữ liệu ủng hộ mạnh nhất, trong khi các giá trị thấp như \(0.2\) ít phù hợp với quan sát này.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/binomial_likelihood_recovery.png&quot; alt=&quot;Likelihood cho dữ liệu hồi phục&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;52-ví-dụ-2-số-cuộc-gọi-đến-tổng-đài-mỗi-giờ&quot;&gt;5.2. Ví dụ 2: số cuộc gọi đến tổng đài mỗi giờ&lt;/h3&gt;

&lt;p&gt;Một tổng đài tiếp nhận 8 cuộc gọi trong 1 giờ. Nếu \(\lambda\) là số cuộc gọi trung bình mỗi giờ theo mô hình Poisson:&lt;/p&gt;

\[\mathcal{L}(\lambda \mid D) = \frac{\lambda^8 e^{-\lambda}}{8!}.\]

&lt;p&gt;Likelihood cho phép ta đánh giá xem dữ liệu “8 cuộc gọi” phù hợp đến mức nào với các giả thuyết như \(\lambda = 3\), \(\lambda = 8\) hay \(\lambda = 15\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/poisson_likelihood_calls.png&quot; alt=&quot;Likelihood cho dữ liệu Poisson&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-likelihood-poisson-cho-số-cuộc-gọi&quot;&gt;Thử nghiệm: likelihood Poisson cho số cuộc gọi&lt;/h3&gt;

&lt;p&gt;Mỗi quan sát nhân thêm một thừa số; đỉnh quanh trung bình mẫu hẹp dần.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;likelihood-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;poisson&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;53-ví-dụ-3-chiều-cao-sinh-viên&quot;&gt;5.3. Ví dụ 3: chiều cao sinh viên&lt;/h3&gt;

&lt;p&gt;Giả sử bạn đo chiều cao của 5 sinh viên và muốn suy luận chiều cao trung bình \(\mu\) của cả lớp. Với mô hình Normal có độ lệch chuẩn đã biết, likelihood theo \(\mu\) cho biết giá trị trung bình nào làm cho bộ dữ liệu vừa đo trở nên hợp lý nhất và giá trị nào ít phù hợp nhất.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/normal_likelihood_heights.png&quot; alt=&quot;Likelihood cho dữ liệu chiều cao&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-ba-bước-xây-dựng-likelihood-từ-bài-toán-thực-tế&quot;&gt;6. Ba bước xây dựng likelihood từ bài toán thực tế&lt;/h2&gt;

&lt;h3 id=&quot;bước-1-mô-tả-cơ-chế-sinh-dữ-liệu&quot;&gt;Bước 1. Mô tả cơ chế sinh dữ liệu&lt;/h3&gt;

&lt;p&gt;Bắt đầu bằng việc xác định bản chất của dữ liệu: đó là số lần thành công/thất bại, số sự kiện xảy ra trong một khoảng thời gian, hay một phép đo liên tục dao động quanh giá trị trung bình.&lt;/p&gt;

&lt;h3 id=&quot;bước-2-chọn-họ-phân-phối-tương-ứng&quot;&gt;Bước 2. Chọn họ phân phối tương ứng&lt;/h3&gt;

&lt;p&gt;Dựa trên cơ chế sinh dữ liệu, chọn mô hình phù hợp: Binomial cho số lần thành công trong \(n\) phép thử, Poisson cho số sự kiện đếm được, hay Normal cho các phép đo liên tục.&lt;/p&gt;

&lt;h3 id=&quot;bước-3-viết-pd-mid-theta-và-đọc-như-hàm-của-tham-số&quot;&gt;Bước 3. Viết \(P(D \mid \theta)\) và đọc như hàm của tham số&lt;/h3&gt;

&lt;p&gt;Sau khi chọn mô hình, viết biểu thức \(P(D \mid \theta)\) và xem nó là hàm theo \(\theta\). Ví dụ, 12 bệnh nhân hồi phục trên 15 người dẫn tới mô hình Binomial, 8 cuộc gọi mỗi giờ dẫn tới Poisson, còn 5 phép đo chiều cao dẫn tới Normal.&lt;/p&gt;

&lt;h2 id=&quot;7-khi-likelihood-phụ-thuộc-vào-cơ-chế-thu-thập-thông-tin&quot;&gt;7. Khi likelihood phụ thuộc vào cơ chế thu thập thông tin&lt;/h2&gt;

&lt;p&gt;Trong nhiều bài toán thực hành, điều quan trọng không chỉ là “con số quan sát được là bao nhiêu”, mà còn là &lt;strong&gt;dữ liệu được tạo ra và tiết lộ theo quy tắc nào&lt;/strong&gt;. Khi đó, viết đúng likelihood đòi hỏi phải mô tả chính xác cơ chế sinh dữ liệu thay vì chỉ chọn một họ phân phối theo thói quen.&lt;/p&gt;

&lt;h3 id=&quot;71-thành-công-ở-lần-thử-thứ-ba&quot;&gt;7.1. Thành công ở lần thử thứ ba&lt;/h3&gt;

&lt;p&gt;Giả sử một thí sinh thi cho đến khi đậu và kết quả là “đậu đúng ở lần thứ ba”. Nếu \(\theta\) là xác suất đậu ở mỗi lần thi, dữ liệu thực chất là chuỗi có thứ tự: trượt lần 1, trượt lần 2, rồi đậu lần 3. Do đó likelihood là:&lt;/p&gt;

\[P(Y=3 \mid \theta) = \theta(1-\theta)^2.\]

&lt;p&gt;Nếu nhầm bài này với mô hình Binomial “3 lần thử có 1 lần thành công”, ta sẽ viết sai likelihood ngay từ đầu vì bỏ qua &lt;strong&gt;thứ tự thời gian của dữ liệu&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;72-lấy-mẫu-không-hoàn-lại&quot;&gt;7.2. Lấy mẫu không hoàn lại&lt;/h3&gt;

&lt;p&gt;Nếu một chiếc hộp có tỷ lệ các loại bi chưa biết và ta bốc từng viên không hoàn lại, likelihood ở mỗi lượt bốc không chỉ phụ thuộc vào giả thuyết về chiếc hộp mà còn phụ thuộc vào lịch sử các viên đã bốc trước đó. Các quan sát không còn độc lập có điều kiện theo tham số như trong Binomial, bởi cơ chế “không hoàn lại” làm thay đổi xác suất ở từng bước.&lt;/p&gt;

&lt;h3 id=&quot;73-thông-tin-được-tiết-lộ-có-chủ-đích&quot;&gt;7.3. Thông tin được tiết lộ có chủ đích&lt;/h3&gt;

&lt;p&gt;Trong bài toán kiểu Monty Hall, dữ liệu không đơn giản là “một cánh cửa tình cờ mở ra”, mà là người dẫn chương trình biết vị trí chiếc xe và chủ đích chỉ mở cánh cửa có dê. Nếu bỏ qua cơ chế này, mô hình sẽ sai; likelihood đúng phải phản ánh việc thông tin được tiết lộ &lt;strong&gt;có điều kiện theo trạng thái ẩn của thế giới&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Bài học chung là likelihood không chỉ phụ thuộc vào giá trị quan sát cuối cùng, mà còn phụ thuộc vào &lt;strong&gt;quy tắc đã tạo ra giá trị đó&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-likelihood-của-từng-lần-tung-đồng-xu&quot;&gt;Thử nghiệm: likelihood của từng lần tung đồng xu&lt;/h3&gt;

&lt;p&gt;Thêm từng lần tung và xem likelihood tương đối, MLE và khoảng likelihood.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;likelihood-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;binom&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;8-likelihood-khi-có-nhiều-quan-sát&quot;&gt;8. Likelihood khi có nhiều quan sát&lt;/h2&gt;

&lt;p&gt;Nếu các quan sát độc lập có điều kiện khi biết tham số \(\theta\), likelihood tổng hợp bằng tích likelihood của từng quan sát:&lt;/p&gt;

\[\mathcal{L}(\theta \mid y_1,\dots,y_n) = \prod_{i=1}^n P(y_i \mid \theta).\]

&lt;p&gt;Về mặt trực giác, mỗi quan sát mới đều bổ sung thêm bằng chứng và được “nhân tiếp” vào likelihood hiện có. Vì vậy, càng có thêm nhiều ngày doanh số, thêm bệnh nhân theo dõi hay thêm lần tung đồng xu, đường cong likelihood càng trở nên sắc nét hơn.&lt;/p&gt;

&lt;h2 id=&quot;9-vì-sao-thường-dùng-log-likelihood&quot;&gt;9. Vì sao thường dùng log-likelihood?&lt;/h2&gt;

&lt;p&gt;Khi cỡ mẫu lớn, likelihood là tích của rất nhiều số nhỏ nên dễ gây tràn số dưới (underflow) trên máy tính. Do đó, ta thường lấy logarit để chuyển sang log-likelihood:&lt;/p&gt;

\[\ell(\theta \mid D) = \log \mathcal{L}(\theta \mid D)
= \sum_{i=1}^n \log P(y_i \mid \theta).\]

&lt;p&gt;Log-likelihood biến tích thành tổng, giúp việc tối ưu thuận tiện hơn và đảm bảo ổn định số học. Trong phần mềm thống kê hiện đại, hầu hết phép tính đều thực hiện trên thang log-likelihood.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_likelihood_curve_large_n.png&quot; alt=&quot;Likelihood với nhiều dữ liệu thường rất nhỏ về mặt số học&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_log_likelihood_curve_large_n.png&quot; alt=&quot;Log-likelihood giữ cùng thông tin nhưng ổn định hơn về mặt tính toán&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-likelihood-vs-log-likelihood-đỉnh-giữ-nguyên--không-bao-giờ-tràn-số&quot;&gt;Video ngắn: Likelihood vs Log-Likelihood: Đỉnh Giữ nguyên — Không bao giờ Tràn số!&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch02-02b-log-likelihood-stability.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): khi n tăng từ 10 → 100 (60% Ngửa), Likelihood gốc sụp xuống 10⁻³⁰ còn Log-Likelihood giữ nguyên dáng parabol trơn mượt với cùng đỉnh MLE θ = 0.60.&lt;/p&gt;

&lt;h2 id=&quot;10-mle-là-gì-và-vì-sao-bayes-không-dừng-ở-đó&quot;&gt;10. MLE là gì và vì sao Bayes không dừng ở đó?&lt;/h2&gt;

&lt;p&gt;Giá trị tham số làm cực đại hàm likelihood gọi là &lt;strong&gt;ước lượng hợp lý cực đại (Maximum Likelihood Estimate — MLE)&lt;/strong&gt;:&lt;/p&gt;

\[\hat{\theta}_{MLE} = \arg\max_{\theta}\mathcal{L}(\theta \mid D).\]

&lt;p&gt;Với mô hình Binomial, MLE rất trực quan:&lt;/p&gt;

\[\hat{\theta}_{MLE} = \frac{k}{n}.\]

&lt;p&gt;Chẳng hạn, với 7 mặt ngửa trong 10 lần tung thì:&lt;/p&gt;

\[\hat{\theta}_{MLE} = 0.7.\]

&lt;p&gt;MLE hữu ích nhưng có hai giới hạn: nó chỉ trả về &lt;strong&gt;một giá trị điểm duy nhất&lt;/strong&gt; và không tích hợp trực tiếp kiến thức nền có sẵn. Thống kê Bayes đi xa hơn: thay vì chỉ tìm đỉnh cao nhất của likelihood, ta kết hợp likelihood với prior để thu được toàn bộ phân phối hậu nghiệm trên không gian tham số.&lt;/p&gt;

&lt;h3 id=&quot;101-map-và-mối-liên-hệ-với-mle&quot;&gt;10.1. MAP và mối liên hệ với MLE&lt;/h3&gt;

&lt;p&gt;Khi cần một ước lượng điểm theo hướng Bayes, lựa chọn phổ biến là &lt;strong&gt;ước lượng hậu nghiệm cực đại (Maximum A Posteriori — MAP)&lt;/strong&gt;:&lt;/p&gt;

\[\hat\theta_{MAP}=\arg\max_\theta\; p(\theta\mid D)
=\arg\max_\theta\; p(D\mid\theta)p(\theta).\]

&lt;p&gt;So với MLE:&lt;/p&gt;

\[\hat\theta_{MLE}=\arg\max_\theta\; p(D\mid\theta),\]

&lt;p&gt;MAP có thêm thành phần prior đóng vai trò điều chuẩn (regularization). Do đó:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Nếu prior yếu hoặc gần như đều trên miền tham số, MAP thường rất gần MLE.&lt;/li&gt;
  &lt;li&gt;Nếu prior mạnh, MAP có thể dịch chuyển đáng kể khỏi MLE về phía vùng mà prior ưu tiên.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nguyên tắc chung cần nhớ là dữ liệu nhiều sẽ kéo MAP về gần MLE, còn prior mạnh sẽ kéo MAP về gần niềm tin ban đầu.&lt;/p&gt;

&lt;h2 id=&quot;11-vai-trò-của-likelihood-trong-định-lý-bayes&quot;&gt;11. Vai trò của likelihood trong định lý Bayes&lt;/h2&gt;

&lt;p&gt;Trong công thức Bayes:&lt;/p&gt;

\[P(\theta \mid D) \propto P(D \mid \theta)P(\theta),\]

&lt;p&gt;likelihood là thành phần đưa tiếng nói của dữ liệu vào suy luận. Nếu prior là niềm tin trước dữ liệu thì likelihood là bằng chứng mới, còn posterior là kết quả sau khi hai nguồn thông tin đó kết hợp với nhau. Hiểu rõ likelihood là điều kiện tiên quyết để hiểu đúng posterior.&lt;/p&gt;

&lt;h2 id=&quot;12-những-nhầm-lẫn-phổ-biến-cần-tránh&quot;&gt;12. Những nhầm lẫn phổ biến cần tránh&lt;/h2&gt;

&lt;h3 id=&quot;121-likelihood-cao-nghĩa-là-xác-suất-của-tham-số-cao&quot;&gt;12.1. “Likelihood cao nghĩa là xác suất của tham số cao”&lt;/h3&gt;

&lt;p&gt;Không đúng. Muốn nói về xác suất của tham số, ta cần đến posterior chứ không chỉ riêng likelihood.&lt;/p&gt;

&lt;h3 id=&quot;122-likelihood-chỉ-dùng-trong-thống-kê-bayes&quot;&gt;12.2. “Likelihood chỉ dùng trong thống kê Bayes”&lt;/h3&gt;

&lt;p&gt;Không đúng. Trường phái tần suất cũng sử dụng likelihood rất rộng rãi, tiêu biểu là phương pháp MLE.&lt;/p&gt;

&lt;h3 id=&quot;123-likelihood-cao-nhất-đồng-nghĩa-với-mô-hình-đúng&quot;&gt;12.3. “Likelihood cao nhất đồng nghĩa với mô hình đúng”&lt;/h3&gt;

&lt;p&gt;Không đúng. Likelihood chỉ xếp hạng các giá trị tham số trong phạm vi lớp mô hình đã chọn. Nếu bản thân mô hình sinh dữ liệu bị chọn sai, giá trị có likelihood cao nhất vẫn có thể dẫn tới kết luận sai lệch.&lt;/p&gt;

&lt;h2 id=&quot;13-cầu-nối-sang-prior-và-posterior-trong-cùng-một-quy-trình&quot;&gt;13. Cầu nối sang prior và posterior trong cùng một quy trình&lt;/h2&gt;

&lt;p&gt;Để theo dõi Chương 2 một cách liền mạch, bạn có thể giữ khung đọc ba bước:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Likelihood&lt;/strong&gt; trả lời: dữ liệu hiện tại ủng hộ giá trị tham số nào?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prior&lt;/strong&gt; trả lời: trước khi thấy dữ liệu, ta tin tham số nằm ở đâu?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior&lt;/strong&gt; trả lời: sau khi kết hợp hai nguồn thông tin, ta nên tin gì?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Xét ví dụ quen thuộc về thời gian chờ theo phân phối mũ: nếu \(X_1,\dots,X_n \sim \text{Exp}(\lambda)\) (với tham số tốc độ \(\lambda &amp;gt; 0\)), thì likelihood theo \(\lambda\) là:&lt;/p&gt;

\[\mathcal{L}(\lambda\mid x_{1:n}) \propto \lambda^n \exp\left(-\lambda\sum_{i=1}^n x_i\right).\]

&lt;p&gt;Biểu thức này là cầu nối trực tiếp sang Bài 2.3 (chọn prior cho \(\lambda\)) và Bài 2.4 (cập nhật thành phân phối hậu nghiệm), giúp ba bài 2.2, 2.3 và 2.4 tạo thành một quy trình cập nhật Bayes thống nhất. Nếu muốn xem đầy đủ cách tính MAP, MMSE và khoảng tin cậy Bayes trên cùng một posterior, bạn có thể tham khảo ví dụ tích hợp ở &lt;a href=&quot;/vi/chapter02/posterior/&quot;&gt;Bài 2.4 Posterior&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Likelihood là cách dữ liệu chấm điểm mức độ phù hợp của các giả thuyết về tham số.&lt;/strong&gt; Ba ý cốt lõi cần nhớ gồm: likelihood là \(P(D \mid \theta)\) khi đọc như một hàm theo \(\theta\); likelihood dùng để so sánh tương đối giữa các giá trị tham số; và likelihood không phải là posterior hay xác suất của tham số. Nắm vững bài này sẽ giúp việc tiếp cận prior và posterior ở các bài sau trở nên mạch lạc hơn.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Likelihood giữ dữ liệu cố định và thay đổi tham số để đánh giá giả thuyết nào giải thích dữ liệu tốt hơn; giá trị cốt lõi của likelihood nằm ở so sánh tương đối giữa các tham số chứ không phải một con số tuyệt đối; và likelihood là đầu vào của định lý Bayes chứ chưa phải phân phối hậu nghiệm.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;giải-thích-đọc-độ-mạnh-bằng-chứng-bằng-tỷ-số-hợp-lý-likelihood-ratio&quot;&gt;Giải thích: Đọc độ mạnh bằng chứng bằng Tỷ số Hợp lý (Likelihood Ratio)&lt;/h2&gt;

&lt;p&gt;Bản thân giá trị tuyệt đối của một likelihood (ví dụ \(L(\theta) = 0.002\)) không có ý nghĩa độc lập vì nó giảm nhỏ dần khi cỡ mẫu tăng. Điều thực sự có ý nghĩa là &lt;strong&gt;tỷ số giữa hai giá trị likelihood&lt;/strong&gt;. Hãy đọc chậm 3 bước sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Viết lõi likelihood (bỏ hằng số không chứa \(\theta\)):&lt;/strong&gt; Ví dụ với \(k\) thành công trong \(n\) phép thử độc lập, \(L(p) \propto p^k (1-p)^{n-k}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh giá \(L(\theta)\) tại các giả thuyết cạnh tranh:&lt;/strong&gt; So sánh \(L(\theta_1)\) với \(L(\theta_2)\) qua tỷ số \(\mathrm{LR} = L(\theta_1) / L(\theta_2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diễn giải theo sức mạnh bằng chứng:&lt;/strong&gt; Nếu \(\mathrm{LR} = 5\), dữ liệu quan sát được có khả năng xảy ra dưới \(\theta_1\) cao gấp 5 lần dưới \(\theta_2\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-7-mặt-ngửa-trong-10-lần-tung-đồng-xu&quot;&gt;Ví dụ tính toán làm từng bước: 7 mặt Ngửa trong 10 lần tung đồng xu&lt;/h3&gt;

&lt;p&gt;Quan sát \(k = 7\) mặt Ngửa trong \(n = 10\) lần tung độc lập. Với \(L(p) = \binom{10}{7} p^7 (1-p)^3 = 120\,p^7(1-p)^3\), ta tính tại 3 giả thuyết:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Giả thuyết \(p\)&lt;/th&gt;
      &lt;th&gt;\(p^7 (1-p)^3\)&lt;/th&gt;
      &lt;th&gt;Likelihood \(L(p) = 120\,p^7(1-p)^3\)&lt;/th&gt;
      &lt;th&gt;Tỷ số hợp lý so với \(p=0.5\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(p = 0.5\) (công bằng)&lt;/td&gt;
      &lt;td&gt;\(0.5^{10} \approx 0.000977\)&lt;/td&gt;
      &lt;td&gt;\(0.1172\)&lt;/td&gt;
      &lt;td&gt;\(1.00\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(p = 0.7\) (MLE)&lt;/td&gt;
      &lt;td&gt;\(0.7^7 \times 0.3^3 \approx 0.002224\)&lt;/td&gt;
      &lt;td&gt;\(0.2668\)&lt;/td&gt;
      &lt;td&gt;\(0.2668 / 0.1172 \approx 2.28\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(p = 0.9\) (rất thiên lệch)&lt;/td&gt;
      &lt;td&gt;\(0.9^7 \times 0.1^3 \approx 0.000478\)&lt;/td&gt;
      &lt;td&gt;\(0.0574\)&lt;/td&gt;
      &lt;td&gt;\(0.0574 / 0.1172 \approx 0.49\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Kết quả cho thấy: dù \(p = 0.7\) là ước lượng hợp lý cực đại (MLE), dữ liệu chỉ ủng hộ \(p = 0.7\) mạnh gấp \(2.28\) lần so với \(p = 0.5\) — bằng chứng còn khá khiêm tốn trên cỡ mẫu \(n = 10\)!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhìn \(L(0.7) = 0.2668\) rồi kết luận “có 26.68% xác suất đồng xu có \(p = 0.7\)”. Con số \(0.2668\) là xác suất ra đúng 7 Ngửa &lt;em&gt;nếu&lt;/em&gt; \(p = 0.7\), hoàn toàn không phải xác suất của giả thuyết \(p = 0.7\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu cùng tỷ lệ 70% nhưng cỡ mẫu tăng gấp 10 lần (\(k = 70, n = 100\)), tỷ số hợp lý giữa \(p = 0.7\) và \(p = 0.5\) là \((0.7/0.5)^{70}(0.3/0.5)^{30} = (2.277)^{10} \approx 3\,718\) lần — sức mạnh bằng chứng tăng theo hàm mũ theo cỡ mẫu.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pYxNSUDSFH4&quot;&gt;In Statistics, Probability is not Likelihood.&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Giải thích rõ sự khác biệt giữa xác suất và likelihood, giúp tránh nhầm lẫn phổ biến nhất trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=XepXtl9YKwc&quot;&gt;Maximum Likelihood, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Minh họa cách xây dựng likelihood từ mô hình sinh dữ liệu và so sánh các giá trị tham số.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R1vcdhPBlXA&quot;&gt;Statistical Rethinking 2023 - 02 - The Garden of Forking Data&lt;/a&gt; — Richard McElreath, English. Trình bày cách likelihood của số lần gặp nước trên quả địa cầu biến thiên theo tỷ lệ nước giả định.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Một quán cà phê bán được 18 ly trong 1 giờ. Nếu dùng mô hình Poisson, hãy mô tả likelihood của \(\lambda\) đang trả lời câu hỏi gì.&lt;/li&gt;
  &lt;li&gt;Với dữ liệu 8 thành công trên 10 lần thử, vì sao \(\theta = 0.8\) có likelihood cao hơn \(\theta = 0.3\)?&lt;/li&gt;
  &lt;li&gt;Hãy giải thích bằng lời sự khác nhau giữa \(P(D \mid \theta)\) và \(P(\theta \mid D)\).&lt;/li&gt;
  &lt;li&gt;Trong công việc của bạn, hãy nêu một ví dụ mà tỷ số likelihood hữu ích để so sánh hai giả thuyết.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 2.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 5.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter02/02_03_prior/&quot;&gt;2.3 Prior - Mã hóa Kiến thức Ban đầu&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 2.1: Phân phối Xác suất - Ngôn ngữ của Sự Không chắc chắn</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_01_probability_distributions/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter02/02_01_probability_distributions</id>
   <content type="html">&lt;p&gt;Nếu ai đó nói với bạn &lt;em&gt;“thời gian giao hàng trung bình là 30 phút”&lt;/em&gt;, bạn vẫn chưa biết liệu đơn hàng sẽ luôn đến trong khoảng 28–32 phút hay lúc thì 10 phút lúc lại trễ hẳn 2 tiếng. Một con số trung bình đơn lẻ xóa sạch toàn bộ câu chuyện về rủi ro. Chính vì vậy, ngôn ngữ thực sự của thống kê Bayes không phải là &lt;strong&gt;con số đơn&lt;/strong&gt;, mà là &lt;strong&gt;phân phối xác suất&lt;/strong&gt; — đối tượng toán học ghi trọn vẹn cả vị trí trung tâm, độ phân tán lẫn hình dạng đuôi của sự không chắc chắn.&lt;/p&gt;

&lt;p&gt;Bài mở đầu Chương 2 này giúp bạn nhìn các họ phân phối quen thuộc không như danh mục công thức phải thuộc, mà như những viên gạch để viết nên câu chuyện prior, likelihood và posterior.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn cần nắm được ba nội dung chính. Thứ nhất, đọc một phân phối xác suất như cách mô tả mức độ chắc chắn. Thứ hai, phân biệt rõ khi nào nên dùng phân phối rời rạc và khi nào nên dùng phân phối liên tục. Thứ ba, hiểu vì sao thống kê Bayes luôn ưu tiên giữ &lt;strong&gt;toàn bộ phân phối&lt;/strong&gt; thay vì chỉ rút gọn về một con số trung bình.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ mini.&lt;/strong&gt; Hai lớp học đều có tỷ lệ qua môn là \(75\%\), nhưng một lớp có 8 sinh viên còn lớp kia có 800 sinh viên. Cùng một tỷ lệ, nhưng mức độ chắc chắn về kết quả không hề giống nhau.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Nếu chỉ báo cáo một con số \(75\%\), bạn đã bỏ sót thông tin quan trọng nào?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-pmfpdf-họ-phân-phối-và-ba-vai-trò-trong-suy-diễn-bayes&quot;&gt;Kiến thức cần nhớ: PMF/PDF, Họ phân phối và Ba vai trò trong Suy diễn Bayes&lt;/h2&gt;

&lt;p&gt;Để đọc và chọn phân phối thành thạo trong mô hình hóa Bayes, hãy gắn kết ba trụ cột sau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Rời rạc (PMF) và Liên tục (PDF):&lt;/strong&gt; Với biến rời rạc, \(P(X = x)\) là xác suất thực sự tại điểm \(x\). Với biến liên tục, hàm mật độ \(f(x)\) có thể lớn hơn 1 (ví dụ \(\text{Uniform}(0, 0.5)\) có \(f(x) = 2\)); chỉ có &lt;strong&gt;tích phân trên một khoảng&lt;/strong&gt; \(\int_a^b f(x)\,dx\) mới là xác suất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khớp miền giá trị (Support Matching):&lt;/strong&gt; Chọn phân phối trước hết là khớp miền giá trị của đại lượng cần mô hình hóa: \([0, 1]\) cho tỷ lệ (Beta), \((0, \infty)\) cho tốc độ/phương sai (Gamma, Exponential, Log-Normal), \(\{0, 1, 2, \dots\}\) cho số đếm (Poisson, Negative Binomial) và \((-\infty, \infty)\) cho giá trị thực không chặn (Normal, Student-\(t\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ba vai trò trong một mô hình Bayes:&lt;/strong&gt; Cùng một hệ phân phối có thể xuất hiện ở ba tầng: &lt;strong&gt;Prior&lt;/strong&gt; (niềm tin về tham số), &lt;strong&gt;Likelihood&lt;/strong&gt; (cơ chế sinh dữ liệu khi biết tham số) và &lt;strong&gt;Posterior / Posterior Predictive&lt;/strong&gt; (niềm tin và dự báo sau khi thấy dữ liệu).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mở-đầu-vì-sao-một-con-số-thường-là-chưa-đủ&quot;&gt;Mở đầu: vì sao một con số thường là chưa đủ?&lt;/h2&gt;

&lt;p&gt;Giả sử bạn phụ trách theo dõi hiệu quả của một nút mua hàng mới trên website. Ở tuần 1, bạn ghi nhận 25 đơn hàng trên 100 lượt truy cập; ở tuần 2, bạn ghi nhận 250 đơn hàng trên 1000 lượt truy cập.&lt;/p&gt;

&lt;p&gt;Cả hai tuần đều cho tỷ lệ chuyển đổi là \(25\%\). Nếu chỉ nhìn vào &lt;strong&gt;ước lượng điểm&lt;/strong&gt;, ta sẽ xem hai tuần là như nhau. Tuy nhiên, trực giác cho thấy điều đó không chính xác: ở tuần 2, ta chắc chắn hơn nhiều rằng tỷ lệ thực sự nằm gần \(25\%\); còn ở tuần 1, cỡ mẫu nhỏ nên các giá trị lân cận như \(18\%\) hay \(32\%\) vẫn hoàn toàn khả dĩ. Chính vì vậy, thống kê Bayes không dừng lại ở câu “ước lượng là \(0.25\)”, mà làm việc với một đối tượng giàu thông tin hơn: &lt;strong&gt;phân phối xác suất&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;1-phân-phối-xác-suất-là-gì&quot;&gt;1. Phân phối xác suất là gì?&lt;/h2&gt;

&lt;p&gt;Nói một cách trực quan, phân phối xác suất là &lt;strong&gt;bản đồ niềm tin&lt;/strong&gt; trên tập các giá trị có thể xảy ra. Khi một giá trị được gán xác suất hoặc mật độ cao, điều đó thể hiện rằng giá trị ấy phù hợp hơn với kiến thức sẵn có, được dữ liệu ủng hộ mạnh hơn, hoặc cả hai.&lt;/p&gt;

&lt;p&gt;Trong thống kê Bayes, phân phối không chỉ mô tả dữ liệu mà còn biểu diễn độ bất định về tham số chưa biết (chẳng hạn \(\theta\) là tỷ lệ khách mua hàng), về dữ liệu tương lai (như số đơn hàng tuần tới), hay về các đại lượng cần dự đoán (như chiều cao trung bình của một lớp học).&lt;/p&gt;

&lt;h3 id=&quot;cách-đọc-một-phân-phối-trong-thực-hành&quot;&gt;Cách đọc một phân phối trong thực hành&lt;/h3&gt;

&lt;p&gt;Khi nhìn vào một phân phối, bạn có thể tự đặt ba câu hỏi: giá trị trung tâm hợp lý nhất nằm ở đâu, mức độ chắc chắn cao hay thấp, và các giá trị cực đoan có còn đáng kể hay không. Ba câu hỏi này biến một đồ thị xác suất thành công cụ hỗ trợ tư duy và ra quyết định.&lt;/p&gt;

&lt;h2 id=&quot;2-rời-rạc-và-liên-tục-hai-dạng-bất-định-phổ-biến&quot;&gt;2. Rời rạc và liên tục: hai dạng bất định phổ biến&lt;/h2&gt;

&lt;h3 id=&quot;21-phân-phối-rời-rạc&quot;&gt;2.1. Phân phối rời rạc&lt;/h3&gt;

&lt;p&gt;Ta dùng phân phối rời rạc khi đại lượng chỉ nhận một tập giá trị đếm được, chẳng hạn số sinh viên vắng học hôm nay, số thư rác nhận được trong 1 giờ, hay số mặt ngửa trong 10 lần tung đồng xu. Khi đó ta làm việc với hàm khối xác suất:&lt;/p&gt;

\[P(X = x).\]

&lt;p&gt;Ví dụ, nếu \(X\) là số lượt khách hàng nhấp vào quảng cáo, thì \(P(X=3)\) là xác suất xảy ra đúng 3 lượt nhấp.&lt;/p&gt;

&lt;h3 id=&quot;22-phân-phối-liên-tục&quot;&gt;2.2. Phân phối liên tục&lt;/h3&gt;

&lt;p&gt;Ta dùng phân phối liên tục khi đại lượng có thể nhận vô số giá trị trên một khoảng, ví dụ như chiều cao, thời gian giao hàng, nhiệt độ, hay tỷ lệ chuyển đổi thực sự của một quảng cáo. Lúc này ta làm việc với hàm mật độ \(p(x)\). Với biến ngẫu nhiên liên tục, xác suất tại đúng một điểm đơn lẻ bằng 0; đại lượng có ý nghĩa là xác suất rơi vào một khoảng:&lt;/p&gt;

\[P(a &amp;lt; X &amp;lt; b) = \int_a^b p(x)\,dx.\]

&lt;p&gt;Ví dụ, thay vì hỏi “xác suất thời gian giao hàng đúng bằng 32.000 phút là bao nhiêu?”, ta hỏi “xác suất thời gian giao hàng nằm trong khoảng từ 30 đến 35 phút là bao nhiêu?”.&lt;/p&gt;

&lt;h2 id=&quot;3-cùng-trung-bình-nhưng-khác-mức-độ-chắc-chắn&quot;&gt;3. Cùng trung bình nhưng khác mức độ chắc chắn&lt;/h2&gt;

&lt;p&gt;Đây là điểm giúp người học thấy rõ giá trị của việc làm việc với cả phân phối. Giả sử hai người cùng nhận định: “Tôi cho rằng tỷ lệ khách hàng mua hàng khoảng \(0.25\)”, nhưng họ biểu diễn niềm tin bằng hai phân phối tiền nghiệm khác nhau: người A dùng Beta\((3,9)\) còn người B dùng Beta\((30,90)\).&lt;/p&gt;

&lt;p&gt;Cả hai phân phối đều có cùng kỳ vọng:&lt;/p&gt;

\[\frac{\alpha}{\alpha+\beta} = \frac{1}{4}.\]

&lt;p&gt;Tuy nhiên, ý nghĩa của chúng rất khác nhau. Beta\((3,9)\) trải khá rộng, tương ứng với phát biểu “tôi nghĩ trung tâm nằm quanh \(0.25\), nhưng vẫn để ngỏ nhiều khả năng lân cận”; ngược lại, Beta\((30,90)\) tập trung hẹp hơn nhiều, thể hiện rằng “tôi khá chắc chắn giá trị thực không lệch xa \(0.25\)”. Một con số trung bình đơn lẻ không phản ánh được sự khác biệt này, còn phân phối xác suất thì thể hiện rất rõ.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-cùng-trung-bình-25-nhưng-mức-độ-chắc-chắn-khác-hẳn&quot;&gt;Video ngắn: Cùng Trung bình 25% nhưng Mức độ Chắc chắn Khác hẳn!&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch02-01a-narrow-vs-wide-belief.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 19 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): trượt cỡ mẫu n từ 20 → 400 giữ nguyên trung bình 25%: phân phối co hẹp dần từ khoảng mơ hồ [6%, 44%] xuống sắc nét [21%, 29%].&lt;/p&gt;

&lt;h2 id=&quot;4-ba-vai-trò-của-phân-phối-trong-thống-kê-bayes&quot;&gt;4. Ba vai trò của phân phối trong thống kê Bayes&lt;/h2&gt;

&lt;p&gt;Trong Chương 2, bạn sẽ gặp phân phối xác suất ở ba vị trí chính.&lt;/p&gt;

&lt;h3 id=&quot;41-prior-tiền-nghiệm&quot;&gt;4.1. Prior (Tiền nghiệm)&lt;/h3&gt;

&lt;p&gt;Prior \(P(\theta)\) mô tả niềm tin về tham số &lt;strong&gt;trước khi&lt;/strong&gt; quan sát dữ liệu hiện tại. Ví dụ, trước khi chạy chiến dịch quảng cáo mới, nhóm tiếp thị có thể tin rằng tỷ lệ mua hàng thường nằm trong khoảng \(2\%\) đến \(5\%\); hoặc trước khi kiểm thử dây chuyền mới, kỹ sư có thể tin rằng tỷ lệ lỗi khó vượt quá \(10\%\).&lt;/p&gt;

&lt;h3 id=&quot;42-likelihood-hàm-hợp-lý&quot;&gt;4.2. Likelihood (Hàm hợp lý)&lt;/h3&gt;

&lt;p&gt;Likelihood \(P(D \mid \theta)\) mô tả mức độ hợp lý của dữ liệu quan sát được nếu tham số thực sự bằng \(\theta\). Ví dụ, nếu tỷ lệ mở email thực là \(0.4\) thì việc quan sát 41 email được mở trên 100 email gửi đi là khá hợp lý; còn nếu tỷ lệ thực chỉ là \(0.05\) thì dữ liệu đó rất khó xảy ra.&lt;/p&gt;

&lt;h3 id=&quot;43-posterior-hậu-nghiệm&quot;&gt;4.3. Posterior (Hậu nghiệm)&lt;/h3&gt;

&lt;p&gt;Posterior \(P(\theta \mid D)\) là niềm tin &lt;strong&gt;sau khi&lt;/strong&gt; kết hợp prior với dữ liệu thông qua định lý Bayes:&lt;/p&gt;

\[P(\theta \mid D) = \frac{P(D \mid \theta)P(\theta)}{P(D)}.\]

&lt;p&gt;Nói gọn lại, prior là điểm xuất phát, likelihood là tiếng nói của dữ liệu, còn posterior là niềm tin đã được cập nhật sau khi kết hợp hai nguồn thông tin đó.&lt;/p&gt;

&lt;h2 id=&quot;5-cách-đọc-hình-dạng-của-một-phân-phối&quot;&gt;5. Cách đọc hình dạng của một phân phối&lt;/h2&gt;

&lt;p&gt;Khi quan sát đồ thị của một phân phối, bạn nên rèn thói quen kiểm tra bốn đặc trưng sau.&lt;/p&gt;

&lt;h3 id=&quot;51-trung-tâm&quot;&gt;5.1. Trung tâm&lt;/h3&gt;

&lt;p&gt;Trung tâm cho biết vùng giá trị hợp lý nhất. Ví dụ, một phân phối tập trung quanh \(0.7\) cho thấy tỷ lệ thành công khả dĩ nhất đang ở mức cao, còn phân phối tập trung quanh \(170\) cho thấy chiều cao trung bình hợp lý nhất vào khoảng 170 cm.&lt;/p&gt;

&lt;h3 id=&quot;52-độ-rộng&quot;&gt;5.2. Độ rộng&lt;/h3&gt;

&lt;p&gt;Độ rộng phản ánh mức độ bất định: phân phối hẹp cho thấy ta khá chắc chắn, còn phân phối rộng cho thấy độ mơ hồ vẫn còn lớn. Chẳng hạn, nếu 5 ngày đo nhiệt độ trong phòng máy chủ đều cho kết quả ổn định thì posterior sẽ hẹp; ngược lại, nếu mới đo trong 2 ngày đầu, posterior thường vẫn còn rộng.&lt;/p&gt;

&lt;h3 id=&quot;53-độ-lệch&quot;&gt;5.3. Độ lệch&lt;/h3&gt;

&lt;p&gt;Phân phối có thể lệch trái hoặc lệch phải, đặc biệt thường gặp với xác suất, tỷ lệ hiếm hoặc dữ liệu đếm. Ví dụ, tỷ lệ khách trả hàng thường nhỏ nên phân phối hay lệch về phía gần 0; số cuộc gọi mỗi phút ở tổng đài cũng thường không đối xứng như phân phối chuẩn (Normal).&lt;/p&gt;

&lt;h3 id=&quot;54-phần-đuôi&quot;&gt;5.4. Phần đuôi&lt;/h3&gt;

&lt;p&gt;Phần đuôi cho biết các khả năng cực đoan còn đáng kể đến mức nào. Trong quyết định kinh doanh hay y khoa, phần đuôi có ý nghĩa lớn vì nó gắn với rủi ro xấu nhất. Ví dụ, một chiến dịch quảng cáo có thể có doanh thu kỳ vọng tốt nhưng đuôi trái dày, nghĩa là khả năng thua lỗ nặng chưa thể xem nhẹ; tương tự, một phác đồ điều trị có thể cho hiệu quả trung bình khá nhưng đuôi phải của tác dụng phụ lại lớn đến mức bác sĩ cần hết sức thận trọng.&lt;/p&gt;

&lt;h2 id=&quot;6-một-số-họ-phân-phối-thường-gặp&quot;&gt;6. Một số họ phân phối thường gặp&lt;/h2&gt;

&lt;h3 id=&quot;61-beta-cho-đại-lượng-nằm-trong-khoảng-0-1&quot;&gt;6.1. Beta: cho đại lượng nằm trong khoảng \((0, 1)\)&lt;/h3&gt;

&lt;p&gt;Phân phối Beta phù hợp khi đại lượng cần mô tả là xác suất hoặc tỷ lệ, chẳng hạn tỷ lệ chuyển đổi, tỷ lệ qua môn, tỷ lệ sản phẩm lỗi, tỷ lệ bệnh nhân hồi phục, tỷ lệ nhấp quảng cáo hay xác suất đồng xu ra mặt ngửa.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/beta_distribution_family.png&quot; alt=&quot;Họ phân phối Beta với nhiều hình dạng khác nhau&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;62-binomial-nhị-thức-đếm-số-lần-thành-công-trong-n-lần-thử&quot;&gt;6.2. Binomial (Nhị thức): đếm số lần thành công trong \(n\) lần thử&lt;/h3&gt;

&lt;p&gt;Phân phối Binomial dùng khi có \(n\) phép thử độc lập, mỗi phép thử chỉ có hai kết quả (thành công hoặc thất bại), và ta đếm tổng số lần thành công — ví dụ như số khách mua hàng trong \(n\) lượt truy cập, số sinh viên qua môn trong lớp 40 người, hay số email được mở trong 100 email đã gửi.&lt;/p&gt;

&lt;h3 id=&quot;63-poisson-đếm-số-sự-kiện-trong-một-khoảng&quot;&gt;6.3. Poisson: đếm số sự kiện trong một khoảng&lt;/h3&gt;

&lt;p&gt;Phân phối Poisson phù hợp với dữ liệu đếm như số cuộc gọi đến trong 1 giờ, số đơn hàng trong 10 phút, hay số lỗi hệ thống mỗi ngày. Họ phân phối này đặc biệt hữu ích khi ta quan tâm đến &lt;strong&gt;tốc độ (cường độ) xảy ra sự kiện&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;64-normal-chuẩn-cho-đại-lượng-liên-tục-xoay-quanh-một-trung-tâm&quot;&gt;6.4. Normal (Chuẩn): cho đại lượng liên tục xoay quanh một trung tâm&lt;/h3&gt;

&lt;p&gt;Phân phối Normal thường gặp với chiều cao, điểm số, sai số đo lường hay thời gian hoàn thành một tác vụ khi có nhiều nguồn dao động nhỏ cộng gộp lại.&lt;/p&gt;

&lt;h3 id=&quot;65-vai-trò-của-hàm-gamma-trong-các-phân-phối-liên-hợp&quot;&gt;6.5. Vai trò của hàm Gamma trong các phân phối liên hợp&lt;/h3&gt;

&lt;p&gt;Khi học về prior liên hợp ở Bài 2.5, bạn sẽ thấy hai họ Beta và Gamma xuất hiện rất thường xuyên. Cả hai đều có hằng số chuẩn hóa biểu diễn qua hàm Gamma:&lt;/p&gt;

\[\Gamma(a)=\int_0^{\infty} x^{a-1}e^{-x}dx,\]

&lt;p&gt;trong đó với số nguyên dương \(n\) thì \(\Gamma(n)=(n-1)!\). Nhờ đó, ta viết được dạng tỉ lệ (hạt nhân):&lt;/p&gt;

\[\text{Beta}(\alpha,\beta)\propto \theta^{\alpha-1}(1-\theta)^{\beta-1},\quad 0&amp;lt;\theta&amp;lt;1,\]

\[\text{Gamma}(\alpha,\beta)\propto \lambda^{\alpha-1}e^{-\beta\lambda},\quad \lambda&amp;gt;0,\]

&lt;p&gt;theo tham số hóa shape–rate (hình dạng – tốc độ). Điểm chính cần nhớ là hàm Gamma đóng vai trò chuẩn hóa giúp hai họ phân phối này có tích phân bằng 1 và cho phép cập nhật tham số gọn gàng trong các cặp liên hợp.&lt;/p&gt;

&lt;h3 id=&quot;66-bảng-tóm-tắt-hằng-số-chuẩn-hóa-của-các-họ-phân-phối-phổ-biến&quot;&gt;6.6. Bảng tóm tắt hằng số chuẩn hóa của các họ phân phối phổ biến&lt;/h3&gt;

&lt;p&gt;Trong thực hành, ta thường viết phần “hạt nhân” (kernel) trước rồi bổ sung hằng số chuẩn hóa để thu được phân phối hợp lệ.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Họ phân phối&lt;/th&gt;
      &lt;th&gt;Miền giá trị&lt;/th&gt;
      &lt;th&gt;Dạng chuẩn hóa&lt;/th&gt;
      &lt;th&gt;Hằng số chuẩn hóa chính&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Bernoulli\((p)\)&lt;/td&gt;
      &lt;td&gt;\(x\in\{0,1\}\)&lt;/td&gt;
      &lt;td&gt;\(P(X=x)=p^x(1-p)^{1-x}\)&lt;/td&gt;
      &lt;td&gt;Tổng trên \(x=0,1\) tự bằng 1&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Binomial\((n,p)\)&lt;/td&gt;
      &lt;td&gt;\(k=0,\dots,n\)&lt;/td&gt;
      &lt;td&gt;\(P(K=k)=\binom{n}{k}p^k(1-p)^{n-k}\)&lt;/td&gt;
      &lt;td&gt;\(\binom{n}{k}\) (đếm số cách)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Poisson\((\lambda)\)&lt;/td&gt;
      &lt;td&gt;\(k=0,1,2,\dots\)&lt;/td&gt;
      &lt;td&gt;\(P(Y=k)=\frac{\lambda^k e^{-\lambda}}{k!}\)&lt;/td&gt;
      &lt;td&gt;\(e^{-\lambda}\) và \(k!\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Normal\((\mu,\sigma^2)\)&lt;/td&gt;
      &lt;td&gt;\(x\in\mathbb{R}\)&lt;/td&gt;
      &lt;td&gt;\(f(x)=\frac{1}{\sigma\sqrt{2\pi}}\exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)\)&lt;/td&gt;
      &lt;td&gt;\(\frac{1}{\sigma\sqrt{2\pi}}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Exponential\((\lambda)\)&lt;/td&gt;
      &lt;td&gt;\(t\ge 0\)&lt;/td&gt;
      &lt;td&gt;\(f(t)=\lambda e^{-\lambda t}\)&lt;/td&gt;
      &lt;td&gt;\(\lambda\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Gamma\((\alpha,\beta)\) (shape-rate)&lt;/td&gt;
      &lt;td&gt;\(\lambda&amp;gt;0\)&lt;/td&gt;
      &lt;td&gt;\(f(\lambda)=\frac{\beta^\alpha}{\Gamma(\alpha)}\lambda^{\alpha-1}e^{-\beta\lambda}\)&lt;/td&gt;
      &lt;td&gt;\(\frac{\beta^\alpha}{\Gamma(\alpha)}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Beta\((\alpha,\beta)\)&lt;/td&gt;
      &lt;td&gt;\(\theta\in(0,1)\)&lt;/td&gt;
      &lt;td&gt;\(f(\theta)=\frac{1}{B(\alpha,\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}\)&lt;/td&gt;
      &lt;td&gt;\(\frac{1}{B(\alpha,\beta)}\), với \(B=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Lưu ý: khi dùng ký hiệu \(\propto\), ta đang làm việc với phần chưa chuẩn hóa; khi cần xác suất hoặc mật độ có tổng (hay tích phân) bằng 1, ta phải nhân thêm hằng số chuẩn hóa.&lt;/p&gt;

&lt;h3 id=&quot;67-miền-tham-số-và-quy-ước-tham-số-hóa&quot;&gt;6.7. Miền tham số và quy ước tham số hóa&lt;/h3&gt;

&lt;p&gt;Để tránh nhầm lẫn khi đọc các công thức liên hợp:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Beta dùng cho tham số xác suất \(\theta\in(0,1)\).&lt;/li&gt;
  &lt;li&gt;Gamma dùng cho tham số dương \(\lambda&amp;gt;0\) (tốc độ hoặc cường độ).&lt;/li&gt;
  &lt;li&gt;Normal thường dùng cho trung bình \(\mu\in\mathbb{R}\) của dữ liệu liên tục.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Riêng với phân phối Gamma, cần luôn ghi rõ cách tham số hóa. Trong khóa học này, ta mặc định dùng tham số hóa shape–rate:&lt;/p&gt;

\[E[\lambda]=\frac{\alpha}{\beta},\qquad \mathrm{Var}(\lambda)=\frac{\alpha}{\beta^2}.\]

&lt;p&gt;Nếu tham khảo tài liệu dùng tham số hóa shape–scale, bạn cần quy đổi tham số về cùng một hệ để tránh sai lệch kết quả số.&lt;/p&gt;

&lt;h3 id=&quot;68-lưu-ý-về-xấp-xỉ-normal&quot;&gt;6.8. Lưu ý về xấp xỉ Normal&lt;/h3&gt;

&lt;p&gt;Trong thực hành, ta thường gặp xấp xỉ Normal cho tổng nhiều biến ngẫu nhiên hoặc cho một posterior đủ tập trung:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hợp lý hơn&lt;/strong&gt; khi cỡ mẫu đủ lớn, phân phối không quá lệch và tham số không nằm sát biên.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kém hợp lý&lt;/strong&gt; với tỷ lệ quá gần 0 hoặc 1, dữ liệu đếm rất nhỏ, hoặc posterior lệch mạnh.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Chẳng hạn với posterior Beta, xấp xỉ Normal thường chấp nhận được khi cả hai tham số hậu nghiệm đều không quá nhỏ (thực hành hay dùng quy tắc kinh nghiệm \(\alpha_{post},\beta_{post}&amp;gt;5\)) và khối lượng xác suất không dồn sát về 0 hoặc 1.&lt;/p&gt;

&lt;h2 id=&quot;7-vì-sao-bayes-giữ-toàn-bộ-phân-phối-thay-vì-một-con-số&quot;&gt;7. Vì sao Bayes giữ toàn bộ phân phối thay vì một con số?&lt;/h2&gt;

&lt;p&gt;Khi giữ lại toàn bộ phân phối, ta có thể trả lời nhiều câu hỏi thực tế hơn hẳn. Chẳng hạn, với posterior của tỷ lệ hoàn thành khóa học trực tuyến, ta có thể tính xác suất tỷ lệ hoàn thành vượt \(60\%\), xác định khoảng giá trị hợp lý nhất của tỷ lệ đó, hoặc dự báo khoảng số người hoàn thành nếu mời thêm 100 học viên mới. Nếu chỉ có một ước lượng điểm duy nhất như \(0.58\), ta không thể trả lời nghiêm túc các câu hỏi đó.&lt;/p&gt;

&lt;h2 id=&quot;8-minh-họa-qua-ba-bối-cảnh-thực-tế&quot;&gt;8. Minh họa qua ba bối cảnh thực tế&lt;/h2&gt;

&lt;h3 id=&quot;81-kinh-doanh&quot;&gt;8.1. Kinh doanh&lt;/h3&gt;

&lt;p&gt;Một doanh nghiệp chạy thử nghiệm A/B cho hai phiên bản trang đích (landing page). Điều họ cần không chỉ là “phiên bản B cao hơn 1.2 điểm phần trăm”, mà còn là độ bất định của ước lượng đó, xác suất B thực sự tốt hơn A, và rủi ro còn lại nếu triển khai đại trà.&lt;/p&gt;

&lt;h3 id=&quot;82-giáo-dục&quot;&gt;8.2. Giáo dục&lt;/h3&gt;

&lt;p&gt;Một giảng viên muốn đánh giá tỷ lệ sinh viên qua môn ở khóa mới. Khi lớp chỉ có 18 sinh viên, độ bất định là rất lớn; báo cáo một phân phối posterior sẽ trung thực hơn nhiều so với việc chỉ nêu con số “tỷ lệ qua môn là \(72\%\)”.&lt;/p&gt;

&lt;h3 id=&quot;83-y-tế&quot;&gt;8.3. Y tế&lt;/h3&gt;

&lt;p&gt;Một bác sĩ theo dõi tỷ lệ đáp ứng của phác đồ điều trị mới. Với 12 bệnh nhân đầu tiên, mọi kết luận chắc chắn đều còn quá sớm; phân phối xác suất cho phép bác sĩ nêu rõ vùng giá trị hợp lý hiện tại thay vì một con số tạo cảm giác chính xác quá mức.&lt;/p&gt;

&lt;h2 id=&quot;9-những-ngộ-nhận-phổ-biến&quot;&gt;9. Những ngộ nhận phổ biến&lt;/h2&gt;

&lt;h3 id=&quot;91-phân-phối-chỉ-là-đồ-thị-minh-họa&quot;&gt;9.1. “Phân phối chỉ là đồ thị minh họa”&lt;/h3&gt;

&lt;p&gt;Không đúng. Phân phối chứa toàn bộ thông tin về giá trị trung tâm, độ bất định, rủi ro ở hai đuôi và xác suất của các giả thuyết cụ thể mà ta quan tâm.&lt;/p&gt;

&lt;h3 id=&quot;92-chỉ-cần-giá-trị-trung-bình-là-đủ&quot;&gt;9.2. “Chỉ cần giá trị trung bình là đủ”&lt;/h3&gt;

&lt;p&gt;Không đúng. Hai phân phối có thể có cùng trung bình nhưng dẫn tới hai quyết định hoàn toàn khác nhau do độ rộng và phần đuôi khác nhau.&lt;/p&gt;

&lt;h3 id=&quot;93-dữ-liệu-lớn-rồi-thì-không-cần-phân-phối&quot;&gt;9.3. “Dữ liệu lớn rồi thì không cần phân phối”&lt;/h3&gt;

&lt;p&gt;Ngay cả khi dữ liệu rất lớn, phân phối vẫn cần thiết để diễn đạt mức độ chắc chắn, so sánh giả thuyết, dự báo dữ liệu mới và kiểm soát các rủi ro cực đoan vốn bị che khuất bởi một con số trung bình.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Phân phối xác suất là ngôn ngữ cốt lõi của thống kê Bayes.&lt;/strong&gt; Nó cho phép ta biểu diễn đồng thời giá trị hợp lý nhất, mức độ chắc chắn và khả năng xảy ra của các kịch bản cực đoan. Trong Chương 2, bạn cần ghi nhớ ba vai trò: prior là phân phối của niềm tin ban đầu, likelihood mô tả mức độ phù hợp của dữ liệu với từng giả thuyết, còn posterior là phân phối niềm tin sau khi đã cập nhật bằng dữ liệu. Nắm vững vai trò của phân phối sẽ giúp các bài học tiếp theo về likelihood, prior và posterior trở nên dễ tiếp thu hơn nhiều.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Phân phối luôn giàu thông tin hơn ước lượng điểm vì nó giữ lại toàn bộ độ bất định; hai phân phối có cùng trung tâm vẫn mang ý nghĩa rất khác nếu độ rộng khác nhau; và trong thống kê Bayes, prior, likelihood và posterior đều là những phân phối đảm nhận các vai trò riêng biệt trong suy luận.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;giải-thích-đọc-một-phân-phối-qua-4-câu-hỏi-thay-vì-chỉ-nhìn-trung-bình&quot;&gt;Giải thích: Đọc một phân phối qua 4 câu hỏi thay vì chỉ nhìn trung bình&lt;/h2&gt;

&lt;p&gt;Mỗi khi gặp một phân phối xác suất trong mô hình Bayes, hãy đọc chậm qua 4 câu hỏi sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Miền giá trị (Support) là gì?&lt;/strong&gt; Tham số hay dữ liệu có bị chặn dương, chặn trong \([0,1]\), hay nhận giá trị nguyên không?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tâm phân phối ở đâu?&lt;/strong&gt; Trung bình, trung vị và mode có trùng nhau không (đối xứng hay lệch)?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ phân tán và độ dày đuôi thế nào?&lt;/strong&gt; Hai phân phối cùng trung bình nhưng khác phương sai hoặc độ dày đuôi dẫn đến quyết định rủi ro rất khác nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mật độ có mang ý nghĩa vật lý/sinh dữ liệu gì?&lt;/strong&gt; Ví dụ: tổng \(n\) phép thử Bernoulli sinh ra Binomial; thời gian chờ giữa các sự kiện Poisson sinh ra Exponential.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-so-sánh-hai-phân-phối-beta-có-cùng-trung-bình-05&quot;&gt;Ví dụ tính toán làm từng bước: So sánh hai phân phối Beta có cùng trung bình \(0.5\)&lt;/h3&gt;

&lt;p&gt;Xét hai phân phối mô tả niềm tin về tỷ lệ chuyển đổi \(p \in [0, 1]\): \(\text{Beta}(2, 2)\) và \(\text{Beta}(20, 20)\). Sử dụng công thức kỳ vọng \(\mu = \frac{\alpha}{\alpha+\beta}\) và phương sai \(\sigma^2 = \frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Phân phối&lt;/th&gt;
      &lt;th&gt;Kỳ vọng \(\mathbb{E}[p]\)&lt;/th&gt;
      &lt;th&gt;Phương sai \(\mathrm{Var}(p)\)&lt;/th&gt;
      &lt;th&gt;Độ lệch chuẩn \(\mathrm{SD}(p)\)&lt;/th&gt;
      &lt;th&gt;Ý nghĩa mức độ tự tin&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\text{Beta}(2, 2)\)&lt;/td&gt;
      &lt;td&gt;\(2 / 4 = 0.500\)&lt;/td&gt;
      &lt;td&gt;\(\frac{4}{16 \times 5} = 0.0500\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{0.0500} \approx 0.2236\)&lt;/td&gt;
      &lt;td&gt;Rất mờ nhạt (tương đương chỉ 4 quan sát giả định)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\text{Beta}(20, 20)\)&lt;/td&gt;
      &lt;td&gt;\(20 / 40 = 0.500\)&lt;/td&gt;
      &lt;td&gt;\(\frac{400}{1600 \times 41} \approx 0.0061\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{0.0061} \approx 0.0781\)&lt;/td&gt;
      &lt;td&gt;Khá tập trung (tương đương 40 quan sát giả định)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Cả hai đều có đúng trung bình \(0.500\), nhưng độ lệch chuẩn của \(\text{Beta}(2, 2)\) lớn gần gấp &lt;strong&gt;3 lần&lt;/strong&gt; \(\text{Beta}(20, 20)\). Đó là lý do chỉ báo cáo một con số trung bình là hoàn toàn không đủ trong thống kê Bayes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhầm giá trị mật độ \(f(x)\) của biến liên tục với xác suất \(P(X = x)\). Với mọi biến liên tục, xác suất tại đúng một điểm đơn lẻ luôn bằng \(0\), còn mật độ \(f(x)\) hoàn toàn có thể lớn hơn \(1\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Với phân phối đều \(X \sim \text{Uniform}(0, 0.25)\), mật độ trên đoạn \([0, 0.25]\) là \(f(x) = 1/0.25 = 4 &amp;gt; 1\), nhưng xác suất rơi vào nửa đầu \([0, 0.125]\) là \(\int_0^{0.125} 4\,dx = 0.5 \in [0, 1]\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=oI3hZJqXJuc&quot;&gt;The Main Ideas behind Probability Distributions&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Trình bày các ý tưởng cốt lõi của phân phối xác suất, phù hợp với mục tiêu đọc phân phối như một mô tả về độ bất định.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pvkhK03aFDM&quot;&gt;Random variables and probability distributions.&lt;/a&gt; — Ben Lambert, English. Phân biệt rõ biến ngẫu nhiên rời rạc và liên tục, hỗ trợ phần lựa chọn họ phân phối.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Why “probability of 0” does not mean “impossible”&lt;/td&gt;
          &lt;td&gt;Probabilities of probabilities, part 2](https://www.youtube.com/watch?v=ZA4JkHKZM50) — 3Blue1Brown, English. Giải thích vì sao cần giữ toàn bộ hình dạng phân phối thay vì chỉ một điểm, gắn liền với tinh thần của thống kê Bayes.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Một lớp có 8 sinh viên và 6 người qua môn; lớp khác có 800 sinh viên và 600 người qua môn. Vì sao cùng tỷ lệ \(75\%\) nhưng mức độ chắc chắn lại khác nhau?&lt;/li&gt;
  &lt;li&gt;Hãy nêu ba ví dụ biến rời rạc và ba ví dụ biến liên tục trong đời sống hoặc công việc của bạn.&lt;/li&gt;
  &lt;li&gt;Hai prior Beta\((4,16)\) và Beta\((40,160)\) có cùng trung bình. Chúng khác nhau ở điểm nào về mặt diễn giải?&lt;/li&gt;
  &lt;li&gt;Nếu bạn là quản lý một quán cà phê, đại lượng nào bạn muốn dự báo bằng &lt;strong&gt;phân phối&lt;/strong&gt; thay vì chỉ một con số duy nhất?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 1-2.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 4-5.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter02/02_02_likelihood/&quot;&gt;2.2 Likelihood - Câu chuyện về Dữ liệu và Mô hình&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 1.4: Bayesian vs Frequentist - So Sánh và Lựa Chọn</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_04_bayesian_vs_frequentist/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_04_bayesian_vs_frequentist</id>
   <content type="html">&lt;p&gt;Trong suốt gần một thế kỷ, cuộc tranh luận giữa trường phái Tần suất (&lt;em&gt;Frequentist&lt;/em&gt;) và trường phái Bayes (&lt;em&gt;Bayesian&lt;/em&gt;) đôi khi nóng bỏng chẳng kém một cuộc tranh luận ý thức hệ. Nhưng với nhà khoa học dữ liệu hiện đại, đây không phải chuyện “chọn phe”, mà là hiểu rõ &lt;strong&gt;bản chất câu hỏi mà mỗi hệ thống công cụ đang trả lời&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Khi một bác sĩ hỏi &lt;em&gt;“xác suất thuốc mới tốt hơn thuốc cũ là bao nhiêu?”&lt;/em&gt; hay một kỹ sư sản phẩm muốn biết &lt;em&gt;“rủi ro doanh thu sụt giảm nếu tung tính năng này?”&lt;/em&gt;, sự khác biệt giữa khoảng tin cậy tần suất (Confidence Interval) và khoảng tin cậy Bayes (Credible Interval) không còn là câu chữ học thuật — nó quyết định trực tiếp cách ta ra quyết định dưới bất định.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn cần hiểu rằng sự khác nhau giữa hai trường phái không chỉ nằm ở kỹ thuật tính toán mà nằm ở chính câu hỏi mỗi bên lựa chọn để trả lời. Bạn cũng cần nhận ra vì sao cách tiếp cận Bayes thường cho diễn giải trực tiếp hơn, đồng thời hiểu rõ những bối cảnh mà phương pháp tần suất vẫn giữ vai trò quan trọng.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ mini.&lt;/strong&gt; Với cùng dữ liệu 7 mặt ngửa trong 10 lần tung, nhà thống kê tần suất hỏi: “Nếu đồng xu cân bằng thì dữ liệu này bất thường đến mức nào?”, còn nhà thống kê Bayes hỏi: “Sau khi quan sát dữ liệu này, xác suất ra ngửa thực sự có khả năng nằm ở đâu?”.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Hai trường phái này khác nhau chủ yếu ở công thức tính toán, hay ở chính câu hỏi mà họ đặt ra?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hai-hệ-quy-chiếu-của-suy-luận-thống-kê&quot;&gt;Kiến thức cần nhớ: Hai hệ quy chiếu của Suy luận Thống kê&lt;/h2&gt;

&lt;p&gt;Để so sánh hai trường phái một cách công bằng và sắc bén ở trình độ đại học, hãy đối chiếu trên ba trục:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đối tượng ngẫu nhiên (What is Random?):&lt;/strong&gt; Frequentist coi tham số \(\theta\) là hằng số cố định và dữ liệu \(y\) là ngẫu nhiên (xét lặp mẫu vô hạn). Bayesian coi dữ liệu quan sát \(y\) đã cố định và mô tả bất định về tham số \(\theta\) bằng phân phối xác suất \(p(\theta \mid y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diễn giải khoảng ước lượng (Confidence vs. Credible Interval):&lt;/strong&gt; Khoảng tin cậy 95% tần suất nói về tỷ lệ bao phủ dài hạn của &lt;em&gt;quy trình&lt;/em&gt; tạo khoảng; khoảng tin cậy 95% Bayes nói trực tiếp rằng \(P(L \le \theta \le U \mid y) = 0.95\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sự hội tụ khi dữ liệu lớn &amp;amp; Khác biệt khi dữ liệu nhỏ:&lt;/strong&gt; Khi cỡ mẫu lớn và mô hình đơn giản, hai phương pháp thường cho kết quả số rất gần nhau. Nhưng khi cỡ mẫu nhỏ, mô hình phân cấp nhiều tầng, hoặc cần gộp tri thức chuyên gia và hàm chi phí quyết định, khung Bayes tỏ ra tự nhiên và linh hoạt hơn hẳn.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-vì-sao-cần-so-sánh-hai-trường-phái-này&quot;&gt;1. Vì sao cần so sánh hai trường phái này?&lt;/h2&gt;

&lt;p&gt;Nhiều người học thống kê cảm thấy lúng túng vì trường phái tần suất (frequentist) và trường phái Bayes (Bayesian) đôi khi sử dụng cùng dữ liệu, cùng mô hình, thậm chí cùng một số công cụ toán học, nhưng lại diễn giải kết quả rất khác nhau. Sự khác biệt này nằm sâu hơn mức kỹ thuật: nó xuất phát từ cách định nghĩa xác suất, cách nhìn nhận tham số và loại câu trả lời cuối cùng mà mỗi bên hướng tới.&lt;/p&gt;

&lt;h2 id=&quot;2-cùng-một-bài-toán-hai-cách-đặt-câu-hỏi&quot;&gt;2. Cùng một bài toán, hai cách đặt câu hỏi&lt;/h2&gt;

&lt;p&gt;Xét lại ví dụ tung đồng xu 10 lần thu được 7 mặt ngửa để kiểm tra xem đồng xu có thiên lệch hay không.&lt;/p&gt;

&lt;h3 id=&quot;câu-hỏi-theo-hướng-frequentist&quot;&gt;Câu hỏi theo hướng Frequentist&lt;/h3&gt;

&lt;p&gt;Nếu đồng xu thực sự cân bằng, dữ liệu như thế này có bất thường không?&lt;/p&gt;

&lt;h3 id=&quot;câu-hỏi-theo-hướng-bayesian&quot;&gt;Câu hỏi theo hướng Bayesian&lt;/h3&gt;

&lt;p&gt;Sau khi thấy dữ liệu này, vùng giá trị hợp lý của xác suất ra ngửa là gì?&lt;/p&gt;

&lt;p&gt;Chỉ riêng sự khác biệt trong cách đặt câu hỏi đã dẫn đến cách diễn giải hoàn toàn khác nhau.&lt;/p&gt;

&lt;h2 id=&quot;3-khác-biệt-ở-định-nghĩa-xác-suất-và-vai-trò-của-tham-số&quot;&gt;3. Khác biệt ở định nghĩa xác suất và vai trò của tham số&lt;/h2&gt;

&lt;h3 id=&quot;trường-phái-frequentist&quot;&gt;Trường phái Frequentist&lt;/h3&gt;

&lt;p&gt;Xác suất được hiểu là tần suất dài hạn của một kết quả qua nhiều lần lặp lại. Do đó, tham số được xem là cố định nhưng chưa biết, còn dữ liệu là đại lượng ngẫu nhiên.&lt;/p&gt;

&lt;h3 id=&quot;trường-phái-bayesian&quot;&gt;Trường phái Bayesian&lt;/h3&gt;

&lt;p&gt;Xác suất được hiểu là mức độ tin cậy hợp lý đối với một mệnh đề dựa trên thông tin hiện có. Do đó, dữ liệu đã quan sát được xem là cố định, còn tham số chưa biết được mô tả bằng phân phối xác suất.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_philosophy_frequentist.png&quot; alt=&quot;Frequentist: tham số cố định, dữ liệu ngẫu nhiên&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_philosophy_bayesian.png&quot; alt=&quot;Bayesian: dữ liệu đã thấy, tham số còn bất định&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;4-khoảng-tin-cậy-confidence-interval-và-khoảng-tin-cậy-bayes-credible-interval&quot;&gt;4. Khoảng tin cậy (Confidence interval) và khoảng tin cậy Bayes (Credible interval)&lt;/h2&gt;

&lt;p&gt;Đây là điểm dễ gây nhầm lẫn nhất với người học. Giả sử ta thu được một khoảng \([0.46, 0.86]\).&lt;/p&gt;

&lt;h3 id=&quot;frequentist-confidence-interval&quot;&gt;Frequentist confidence interval&lt;/h3&gt;

&lt;p&gt;Diễn giải đúng là nếu lặp lại quy trình lấy mẫu và dựng khoảng rất nhiều lần, thì 95% các khoảng được tạo ra sẽ chứa giá trị tham số thực. Điều này &lt;strong&gt;không&lt;/strong&gt; có nghĩa là “có 95% xác suất tham số nằm trong khoảng cụ thể đang có”.&lt;/p&gt;

&lt;h3 id=&quot;bayesian-credible-interval&quot;&gt;Bayesian credible interval&lt;/h3&gt;

&lt;p&gt;Diễn giải Bayes trực tiếp hơn: với dữ liệu hiện tại và prior đã chọn, xác suất để tham số nằm trong khoảng đó là 95%. Cách phát biểu này sát với câu hỏi mà người dùng thực sự muốn đặt ra.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-khoảng-tin-cậy-và-khoảng-đáng-tin-khi-lặp-thí-nghiệm&quot;&gt;Thử nghiệm: khoảng tin cậy và khoảng đáng tin khi lặp thí nghiệm&lt;/h3&gt;

&lt;p&gt;Mỗi hàng là một thí nghiệm; xem khoảng tin cậy 95% phủ μ cố định đúng 95% số lần, còn khoảng đáng tin phụ thuộc prior.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;interval-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;video-ngắn-điệu-nhảy-20-khoảng-tin-cậy-ci-vs-khoảng-đáng-tin-bayes-credible&quot;&gt;Video ngắn: Điệu nhảy 20 Khoảng Tin cậy (CI) vs Khoảng Đáng tin Bayes (Credible)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-04a-ci-dance-vs-credible.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 20 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): 20 khoảng CI 95% nhảy quanh θ cố định (19 xanh trúng, 1 đỏ trượt) đối chiếu với 1 đường hậu nghiệm Bayes duy nhất chứa trực tiếp 95% xác suất trên [0.50, 0.83].&lt;/p&gt;

&lt;h2 id=&quot;5-p-value-và-xác-suất-hậu-nghiệm-posterior-probability&quot;&gt;5. P-value và xác suất hậu nghiệm (Posterior probability)&lt;/h2&gt;

&lt;h3 id=&quot;theo-góc-nhìn-frequentist&quot;&gt;Theo góc nhìn Frequentist&lt;/h3&gt;

&lt;p&gt;P-value đánh giá rằng nếu giả thuyết không là đúng thì dữ liệu quan sát được bất thường đến mức nào.&lt;/p&gt;

&lt;h3 id=&quot;theo-góc-nhìn-bayesian&quot;&gt;Theo góc nhìn Bayesian&lt;/h3&gt;

&lt;p&gt;Xác suất hậu nghiệm cho biết sau khi thấy dữ liệu, giả thuyết hoặc tham số có khả năng nằm ở đâu.&lt;/p&gt;

&lt;p&gt;Đây là khác biệt giữa việc đánh giá &lt;strong&gt;độ bất thường của dữ liệu&lt;/strong&gt; và việc đánh giá &lt;strong&gt;độ tin cậy của giả thuyết&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_vs_posterior_frequentist.png&quot; alt=&quot;P-value ở góc nhìn Frequentist&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_vs_posterior_bayesian.png&quot; alt=&quot;Posterior probability ở góc nhìn Bayesian&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-ví-dụ-y-khoa-minh-họa-sự-khác-biệt&quot;&gt;6. Ví dụ y khoa minh họa sự khác biệt&lt;/h2&gt;

&lt;p&gt;Giả sử một xét nghiệm trả về kết quả dương tính.&lt;/p&gt;

&lt;h3 id=&quot;theo-góc-nhìn-frequentist-1&quot;&gt;Theo góc nhìn Frequentist&lt;/h3&gt;

&lt;p&gt;Câu hỏi thường đặt ra là: nếu bệnh nhân không mắc bệnh, xác suất xét nghiệm vẫn cho kết quả dương tính là bao nhiêu?&lt;/p&gt;

&lt;h3 id=&quot;theo-góc-nhìn-bayesian-1&quot;&gt;Theo góc nhìn Bayesian&lt;/h3&gt;

&lt;p&gt;Câu hỏi trực tiếp hơn: sau khi nhận kết quả dương tính, xác suất bệnh nhân thực sự mắc bệnh là bao nhiêu?&lt;/p&gt;

&lt;p&gt;Trong thực hành y khoa, câu hỏi thứ hai sát với nhu cầu của cả bác sĩ lẫn bệnh nhân hơn.&lt;/p&gt;

&lt;h3 id=&quot;một-ví-dụ-bằng-con-số&quot;&gt;Một ví dụ bằng con số&lt;/h3&gt;

&lt;p&gt;Giả sử tỷ lệ mắc bệnh trong dân số là \(1\%\), xét nghiệm có độ nhạy \(99\%\) và tỷ lệ dương tính giả là \(5\%\). Khi một người có kết quả dương tính, theo định lý Bayes:&lt;/p&gt;

\[P(\text{bệnh}\mid +)
=\frac{0.99\times 0.01}{0.99\times 0.01 + 0.05\times 0.99}
\approx 0.167.\]

&lt;p&gt;Nghĩa là sau khi có kết quả dương tính, xác suất thực sự mắc bệnh mới chỉ vào khoảng \(16.7\%\) chứ không phải gần \(99\%\). Ví dụ này cho thấy rõ: phương pháp tần suất thường báo cáo đặc tính của xét nghiệm dưới một giả thuyết cho trước, còn phương pháp Bayes trả lời trực tiếp xác suất mắc bệnh mà bác sĩ và bệnh nhân cần biết.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-thử-nghiệm-lâm-sàng-1620-vs-1220-frequentist-bác-bỏ-hay-bayes-giữ-lại&quot;&gt;Video ngắn: Thử nghiệm Lâm sàng (16/20 vs 12/20): Frequentist bác bỏ hay Bayes giữ lại?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-04b-clinical-trial-8-of-10.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): cùng một dữ liệu thử thuốc: kiểm định Frequentist cho p = 0.134 (&amp;gt; 0.05) trong khi phân phối hậu nghiệm Bayes chỉ ra P(thuốc tốt hơn) = 89.8%.&lt;/p&gt;

&lt;h2 id=&quot;7-thế-mạnh-của-trường-phái-frequentist&quot;&gt;7. Thế mạnh của trường phái Frequentist&lt;/h2&gt;

&lt;p&gt;Sẽ không công bằng nếu coi thống kê tần suất là “sai hoàn toàn”. Trường phái này có ưu thế rõ rệt trong các thiết kế thử nghiệm chuẩn hóa với quy tắc quyết định cố định, các bài toán có cỡ mẫu rất lớn, những lĩnh vực hay cơ quan quản lý đã quen với khung kiểm định truyền thống, và các quy trình đòi hỏi bảo đảm tính chất thống kê dài hạn. Các ví dụ tiêu biểu gồm thử nghiệm lâm sàng giai đoạn cuối, kiểm soát chất lượng sản xuất hay những quy trình ra quyết định cần chuẩn hóa nghiêm ngặt.&lt;/p&gt;

&lt;h2 id=&quot;8-thế-mạnh-của-trường-phái-bayesian&quot;&gt;8. Thế mạnh của trường phái Bayesian&lt;/h2&gt;

&lt;p&gt;Thống kê Bayes đặc biệt phù hợp khi cần diễn giải trực tiếp về tham số hoặc giả thuyết, khi có kiến thức ban đầu (prior) đáng tin cậy, khi cỡ mẫu còn nhỏ, khi cần cập nhật tuần tự theo từng đợt dữ liệu, khi mô hình có cấu trúc phân cấp hoặc phức tạp, hay khi cần dự báo đi kèm định lượng bất định. Những ứng dụng tiêu biểu gồm thử nghiệm A/B ở các doanh nghiệp mới có lưu lượng chưa lớn, hỗ trợ quyết định y khoa từ nhiều nguồn thông tin, hệ gợi ý, dự báo chuỗi thời gian và các phân tích khoa học có prior từ nghiên cứu trước.&lt;/p&gt;

&lt;h2 id=&quot;9-hạn-chế-thường-gặp-của-mỗi-bên&quot;&gt;9. Hạn chế thường gặp của mỗi bên&lt;/h2&gt;

&lt;h3 id=&quot;hạn-chế-của-frequentist&quot;&gt;Hạn chế của Frequentist&lt;/h3&gt;

&lt;p&gt;Thống kê tần suất thường gặp khó khăn trong việc diễn giải đúng p-value và khoảng tin cậy, khó tích hợp kiến thức ban đầu, không cho phép phát biểu trực tiếp về xác suất của tham số, và không thuận tiện khi cập nhật liên tục theo từng đợt dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;hạn-chế-của-bayesian&quot;&gt;Hạn chế của Bayesian&lt;/h3&gt;

&lt;p&gt;Thống kê Bayes đòi hỏi phải lựa chọn prior, chi phí tính toán đôi khi cao hơn và cần người đọc chấp nhận cách hiểu xác suất như mức độ tin cậy. Tuy vậy, với các công cụ hiện đại như PyMC và Stan, rào cản tính toán đã giảm đi đáng kể.&lt;/p&gt;

&lt;h2 id=&quot;10-lựa-chọn-theo-bài-toán-thay-vì-theo-phe-phái&quot;&gt;10. Lựa chọn theo bài toán thay vì theo phe phái&lt;/h2&gt;

&lt;p&gt;Trong thực hành hiện đại, nhiều nhà phân tích kết hợp cả hai cách tiếp cận: dùng tư duy tần suất cho một số kiểm tra nhanh hoặc mốc so sánh cơ sở, và dùng Bayes cho mô hình chính cũng như phần diễn giải kết quả. Điều quan trọng không phải là chọn phe một cách cứng nhắc, mà là dùng đúng công cụ cho câu hỏi đặt ra và diễn giải kết quả trung thực với phương pháp đã chọn.&lt;/p&gt;

&lt;h2 id=&quot;11-vì-sao-khóa-học-này-tập-trung-vào-bayes&quot;&gt;11. Vì sao khóa học này tập trung vào Bayes?&lt;/h2&gt;

&lt;p&gt;Trong phần lớn các bài toán hiện đại mà người học quan tâm, thống kê Bayes trả lời trực tiếp hơn những câu hỏi cốt lõi: tham số có khả năng nằm ở đâu, độ bất định còn lại lớn đến mức nào, xác suất giả thuyết này vượt trội hơn giả thuyết kia là bao nhiêu, và dự báo tương lai nên được hiểu ra sao. Nói gọn lại, kết quả Bayes thường sát với thông tin mà nhà nghiên cứu, bác sĩ, kỹ sư hay chuyên viên phân tích sản phẩm thực sự cần.&lt;/p&gt;

&lt;h2 id=&quot;12-tóm-lược-dễ-nhớ&quot;&gt;12. Tóm lược dễ nhớ&lt;/h2&gt;

&lt;p&gt;Nếu cần một cách phân biệt ngắn gọn: trường phái tần suất đánh giá dữ liệu dưới một giả thuyết cho trước, còn trường phái Bayes đánh giá giả thuyết sau khi đã quan sát dữ liệu. Chính điểm này khiến cách diễn giải Bayes thường tự nhiên hơn trong các bài toán thực tế.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt;&lt;/p&gt;
  &lt;ol&gt;
    &lt;li&gt;Frequentist và Bayesian khác nhau từ nền tảng triết học: đại lượng nào ngẫu nhiên, đại lượng nào cố định và xác suất biểu thị điều gì.&lt;/li&gt;
    &lt;li&gt;Frequentist thường trả lời câu hỏi về dữ liệu giả định dưới một giả thuyết, còn Bayesian trả lời trực tiếp về tham số hoặc giả thuyết sau khi thấy dữ liệu.&lt;/li&gt;
    &lt;li&gt;Trong nhiều bài toán thực tế, câu trả lời theo hướng Bayes gần hơn với câu hỏi mà người dùng thực sự muốn đặt ra.&lt;/li&gt;
  &lt;/ol&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;giải-thích-cùng-một-bảng-số-liệu-hai-cách-phát-biểu-khác-nhau-ra-sao&quot;&gt;Giải thích: Cùng một bảng số liệu, hai cách phát biểu khác nhau ra sao?&lt;/h2&gt;

&lt;p&gt;Hãy đọc chậm ba câu hỏi sau mỗi khi phải chọn giữa cách tiếp cận Frequentist và Bayesian:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Ta muốn trả lời câu hỏi nào?&lt;/strong&gt; Nếu cần tính xác suất trực tiếp cho giả thuyết (ví dụ \(P(\text{hiệu ứng} &amp;gt; 0 \mid y)\)), chỉ có khung Bayes trả lời trực tiếp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dữ liệu hiện có ít hay nhiều, có cấu trúc phân cấp không?&lt;/strong&gt; Với mẫu nhỏ hoặc nhiều nhóm lồng nhau, prior có thông tin yếu và &lt;em&gt;partial pooling&lt;/em&gt; của Bayes giúp ổn định ước lượng rõ rệt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chi phí tính toán cho phép đến đâu?&lt;/strong&gt; Ước lượng tần suất thường có công thức đóng cực nhanh; suy diễn Bayes tổng quát cần MCMC hoặc xấp xỉ biến phân nhưng đổi lại cho toàn bộ phân phối bất định.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-thử-nghiệm-ab-nhỏ-với-810-ca-thành-công&quot;&gt;Ví dụ tính toán làm từng bước: Thử nghiệm A/B nhỏ với 8/10 ca thành công&lt;/h3&gt;

&lt;p&gt;Giả sử bạn thử một quy trình điều trị mới trên \(n = 10\) bệnh nhân và có \(k = 8\) ca đáp ứng tốt. Hãy so sánh hai báo cáo:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Khía cạnh&lt;/th&gt;
      &lt;th&gt;Cách tiếp cận Frequentist (Wald / MLE)&lt;/th&gt;
      &lt;th&gt;Cách tiếp cận Bayesian (Prior \(\text{Beta}(2, 2)\))&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Ước lượng điểm&lt;/td&gt;
      &lt;td&gt;\(\hat p = 8/10 = 0.800\)&lt;/td&gt;
      &lt;td&gt;\(\mathbb{E}[p \mid y] = \frac{2+8}{2+2+10} = \frac{10}{14} \approx 0.714\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Khoảng 95%&lt;/td&gt;
      &lt;td&gt;\(0.80 \pm 1.96\sqrt{\frac{0.8 \times 0.2}{10}} = [0.552,\; 1.048]\) (vượt quá 1!)&lt;/td&gt;
      &lt;td&gt;Hậu nghiệm \(\text{Beta}(10, 4)\), khoảng 95% xấp xỉ \([0.46,\; 0.91]\) (luôn nằm trong \([0,1]\))&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Câu hỏi &lt;em&gt;”\(P(p &amp;gt; 0.5)\)”&lt;/em&gt;&lt;/td&gt;
      &lt;td&gt;Không phát biểu được xác suất cho \(p\); chỉ tính \(p\)-value kiểm định \(H_0: p = 0.5\)&lt;/td&gt;
      &lt;td&gt;Tính trực tiếp \(P(p &amp;gt; 0.5 \mid y) \approx 0.954\) (\(95.4\%\))&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chú ý hai điểm rất thực tế: với cỡ mẫu nhỏ \(n = 10\), khoảng Wald tần suất thậm chí tràn qua \(1.048\) (vô nghĩa với xác suất), trong khi hậu nghiệm \(\text{Beta}(10, 4)\) tự động giữ xác suất trong \([0, 1]\) và co nhẹ ước lượng từ \(0.800\) về \(0.714\) để chống quá tự tin trên mẫu nhỏ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nghĩ rằng Bayesian luôn “đúng hơn” Frequentist trong mọi bài toán. Thực tế một mô hình Bayes có prior sai lệch nghiêm trọng hoặc likelihood sai vẫn cho kết quả sai — sức mạnh của Bayes chỉ phát huy khi đi kèm kiểm tra mô hình (PPC, phân tích độ nhạy).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu cỡ mẫu tăng lên \(n = 1000\) với \(k = 800\), ước lượng Bayes với \(\text{Beta}(2, 2)\) là \(802 / 1004 \approx 0.7988\) — gần như trùng khít với MLE \(0.8000\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qJcv7VHwqcA&quot;&gt;Bayesian vs. Frequentist Statistics … MADE EASY!!!&lt;/a&gt; — Stats with Brian, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Minh họa cách hai trường phái đặt hai câu hỏi khác nhau trên cùng một tập dữ liệu, đúng trọng tâm so sánh của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=GEFxFVESQXc&quot;&gt;Are you Bayesian or Frequentist?&lt;/a&gt; — Cassie Kozyrkov, English. Trình bày cách chọn ngôn ngữ xác suất dựa trên quyết định cần đưa ra, củng cố quan điểm không biến khác biệt phương pháp thành phe phái.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YPceDssQFWo&quot;&gt;Bayesian Statistics: Credible vs Confidence Intervals&lt;/a&gt; — Academia Elevated, English. Phân biệt rõ cách đọc khoảng tin cậy (confidence interval) và khoảng tin cậy Bayes (credible interval), bổ trợ cho phần diễn giải kết quả.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Hãy giải thích bằng lời sự khác nhau giữa confidence interval và credible interval.&lt;/li&gt;
  &lt;li&gt;Trong ví dụ đồng xu 7/10, trường phái Frequentist và Bayesian đang đặt hai câu hỏi khác nhau như thế nào?&lt;/li&gt;
  &lt;li&gt;Với một bài toán chẩn đoán y khoa, vì sao cách diễn giải theo hướng Bayes thường tự nhiên hơn?&lt;/li&gt;
  &lt;li&gt;Hãy nêu một tình huống mà cách tiếp cận Frequentist vẫn là lựa chọn hợp lý.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 1-4.&lt;/li&gt;
  &lt;li&gt;Dienes, Z. (2011). Bayesian versus orthodox statistics.&lt;/li&gt;
  &lt;li&gt;Wasserstein, R. L., &amp;amp; Lazar, N. A. (2016). ASA Statement on p-values.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Kết thúc Chapter 1. Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter02/&quot;&gt;Chapter 2 - Cơ bản về Phân tích Dữ liệu Bayesian&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 1.3: Định lý Bayes - Công cụ Cập nhật Niềm tin</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_03_bayes_theorem_posterior/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_03_bayes_theorem_posterior</id>
   <content type="html">&lt;p&gt;Năm 1763 — hai năm sau khi mục sư Thomas Bayes qua đời — người bạn thân Richard Price tìm thấy trong di cảo của ông một bản thảo ngắn về bài toán “xác suất ngược”: biết kết quả quan sát được trên bàn bi-a, làm sao suy ngược lại vị trí ban đầu của quả bóng ẩn? Bản thảo ấy, cùng công trình độc lập và tổng quát hơn của Pierre-Simon Laplace năm 1774, đã đặt nền móng cho phương trình nổi tiếng nhất của thống kê hiện đại: &lt;strong&gt;Định lý Bayes&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Điều kỳ diệu của công thức Bayes nằm ở sự cân bằng hoàn hảo: nó biến trực giác học hỏi từ kinh nghiệm thành một phép nhân tường minh giữa &lt;em&gt;kiến thức ban đầu&lt;/em&gt; (prior) và &lt;em&gt;bằng chứng dữ liệu&lt;/em&gt; (likelihood), rồi chuẩn hóa bằng &lt;em&gt;bằng chứng toàn phần&lt;/em&gt; (evidence).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn cần hiểu định lý Bayes như một quy tắc cập nhật niềm tin chứ không chỉ là một công thức học thuộc. Bạn cần phân biệt rõ vai trò của prior, likelihood và posterior trong các ví dụ thực tế, đồng thời thấy vì sao định lý Bayes phù hợp với các bài toán chẩn đoán, dự báo và học từ dữ liệu.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ mini.&lt;/strong&gt; Một bác sĩ biết bệnh cúm đang phổ biến trong mùa này, nhưng khi bệnh nhân xuất hiện với bộ triệu chứng đặc trưng cho COVID-19, niềm tin ban đầu cần được điều chỉnh. Định lý Bayes là công cụ thực hiện bước cập nhật đó một cách có nguyên tắc.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Nếu prior là điều bạn tin trước khi thấy dữ liệu, còn likelihood là mức độ dữ liệu phù hợp với từng giả thuyết, thì posterior nên được hiểu là gì?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-thành-phần-của-định-lý-bayes-và-cơ-chế-cập-nhật-tuần-tự&quot;&gt;Kiến thức cần nhớ: Bốn thành phần của Định lý Bayes và Cơ chế cập nhật tuần tự&lt;/h2&gt;

&lt;p&gt;Để làm chủ hoàn toàn công thức \(P(\theta \mid y) = \frac{P(y \mid \theta)P(\theta)}{P(y)}\), hãy nhìn rõ ba trụ cột cấu thành nó:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bốn thành phần giải phẫu (Prior, Likelihood, Evidence, Posterior):&lt;/strong&gt; Prior \(P(\theta)\) mã hóa niềm tin trước dữ liệu; Likelihood \(P(y \mid \theta)\) đo mức độ tương thích của dữ liệu dưới từng giả thuyết \(\theta\); Evidence \(P(y) = \sum_\theta P(y \mid \theta)P(\theta)\) là hằng số chuẩn hóa; và Posterior \(P(\theta \mid y)\) là niềm tin sau khi tổng hợp cả hai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dạng tỷ số khả dĩ (Odds Form &amp;amp; Bayes Factor):&lt;/strong&gt; Viết dưới dạng tỷ lệ giữa hai giả thuyết: \(\frac{P(H_1 \mid y)}{P(H_0 \mid y)} = \frac{P(y \mid H_1)}{P(y \mid H_0)} \times \frac{P(H_1)}{P(H_0)}\). Tỷ số ở giữa chính là &lt;strong&gt;hệ số Bayes (Bayes Factor)&lt;/strong&gt; — đo trực tiếp sức mạnh bằng chứng của dữ liệu mà không cần tính mẫu số \(P(y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính nhất quán của cập nhật tuần tự (Sequential Updating):&lt;/strong&gt; Posterior sau quan sát thứ nhất trở thành Prior cho quan sát thứ hai, và kết quả cuối cùng hoàn toàn giống hệt như khi gộp tất cả dữ liệu cập nhật một lần.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-bayes-bắt-đầu-từ-một-câu-hỏi-rất-quen-thuộc&quot;&gt;1. Bayes bắt đầu từ một câu hỏi rất quen thuộc&lt;/h2&gt;

&lt;p&gt;Hằng ngày, chúng ta đều thực hiện một quá trình suy luận gần với Bayes: ban đầu giữ một niềm tin ở mức độ nhất định, sau đó tiếp nhận thông tin mới rồi điều chỉnh lại niềm tin ấy. Quá trình này xuất hiện khi ta nghe dự báo thời tiết để điều chỉnh kế hoạch, xem kết quả xét nghiệm để cập nhật chẩn đoán, hay theo dõi doanh số tuần đầu để điều chỉnh nhận định về nhu cầu thị trường. Định lý Bayes chuyển hóa quá trình trực giác đó thành một quy tắc toán học rõ ràng.&lt;/p&gt;

&lt;h2 id=&quot;2-ví-dụ-minh-họa-bác-sĩ-chẩn-đoán-bệnh&quot;&gt;2. Ví dụ minh họa: bác sĩ chẩn đoán bệnh&lt;/h2&gt;

&lt;p&gt;Giả sử bác sĩ đang cân nhắc ba khả năng: cúm, COVID-19 và viêm phổi vi khuẩn. Trước khi xem xét kỹ triệu chứng của bệnh nhân, bác sĩ đã có niềm tin ban đầu dựa trên mùa dịch, tình hình dịch tễ tại khu vực và kinh nghiệm lâm sàng; đó là &lt;strong&gt;prior&lt;/strong&gt;. Tiếp theo, bác sĩ thu thập dữ liệu mới như sốt, ho, mất vị giác, phim X-quang hay kết quả xét nghiệm; phần thông tin này đi vào &lt;strong&gt;likelihood&lt;/strong&gt;. Khi kết hợp hai thành phần đó lại, bác sĩ thu được niềm tin đã cập nhật về chẩn đoán hợp lý nhất; đó chính là &lt;strong&gt;posterior&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-bác-sĩ-chẩn-đoán-bệnh-bằng-cập-nhật-tuần-tự-bayes&quot;&gt;Video ngắn: Bác sĩ Chẩn đoán Bệnh bằng Cập nhật Tuần tự Bayes&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-03a-doctor-sequential-bayes.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 21 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): 3 thanh xác suất (Cảm cúm, COVID-19, Viêm phổi) biến thiên trực tiếp khi thêm triệu chứng mất khứu giác (COVID tăng 30% → 80%) và test nhanh dương tính (99.4%).&lt;/p&gt;

&lt;h2 id=&quot;3-công-thức-bayes&quot;&gt;3. Công thức Bayes&lt;/h2&gt;

&lt;p&gt;Định lý Bayes được viết như sau:&lt;/p&gt;

\[P(\theta \mid D) = \frac{P(D \mid \theta)\,P(\theta)}{P(D)}.\]

&lt;p&gt;Trong đó, \(P(\theta \mid D)\) là &lt;strong&gt;posterior&lt;/strong&gt; (hậu nghiệm), \(P(D \mid \theta)\) là &lt;strong&gt;likelihood&lt;/strong&gt; (hàm hợp lý), \(P(\theta)\) là &lt;strong&gt;prior&lt;/strong&gt; (tiền nghiệm), còn \(P(D)\) là &lt;strong&gt;evidence&lt;/strong&gt; (bằng chứng) hay hằng số chuẩn hóa. Khi chỉ cần tập trung vào cấu trúc tỉ lệ, ta thường viết gọn:&lt;/p&gt;

\[\text{posterior} \propto \text{likelihood} \times \text{prior}.\]

&lt;h3 id=&quot;31-ôn-nhanh-xác-suất-có-điều-kiện-và-xác-suất-toàn-phần&quot;&gt;3.1. Ôn nhanh xác suất có điều kiện và xác suất toàn phần&lt;/h3&gt;

&lt;p&gt;Trước khi áp dụng định lý Bayes, ta cần hai công thức cơ bản:&lt;/p&gt;

\[P(A\mid B)=\frac{P(A\cap B)}{P(B)}\]

&lt;p&gt;và&lt;/p&gt;

\[P(B)=\sum_i P(B\mid A_i)P(A_i),\]

&lt;p&gt;trong đó \(\{A_i\}\) là hệ các biến cố xung khắc đôi một và phủ toàn bộ không gian mẫu. Với bài toán nhị phân (có bệnh / không bệnh), công thức xác suất toàn phần có dạng:&lt;/p&gt;

\[P(B)=P(B\mid A)P(A)+P(B\mid A&apos;)P(A&apos;).\]

&lt;p&gt;Đây chính là mẫu số chuẩn hóa trong định lý Bayes.&lt;/p&gt;

&lt;h2 id=&quot;4-đọc-công-thức-bằng-lời&quot;&gt;4. Đọc công thức bằng lời&lt;/h2&gt;

&lt;p&gt;Thay vì xem định lý Bayes là một biểu thức khó nhớ, bạn có thể diễn đạt nó bằng lời như sau:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Niềm tin mới về một giả thuyết tỉ lệ với mức độ dữ liệu ủng hộ giả thuyết đó nhân với mức độ tin cậy ban đầu dành cho giả thuyết đó.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Cách đọc này rất trực quan: nếu một giả thuyết có prior cao và dữ liệu cũng phù hợp với nó thì posterior sẽ cao; ngược lại, nếu prior thấp và dữ liệu không ủng hộ thì posterior sẽ thấp.&lt;/p&gt;

&lt;h2 id=&quot;5-ví-dụ-kinh-điển-đồng-xu-thiên-lệch&quot;&gt;5. Ví dụ kinh điển: đồng xu thiên lệch&lt;/h2&gt;

&lt;p&gt;Giả sử ta muốn suy luận xác suất ra mặt ngửa \(\theta\) của một đồng xu.&lt;/p&gt;

&lt;h3 id=&quot;trước-khi-có-dữ-liệu&quot;&gt;Trước khi có dữ liệu&lt;/h3&gt;

&lt;p&gt;Ta cho rằng đồng xu có thể gần cân bằng nhưng chưa chắc chắn; niềm tin này được biểu diễn bằng prior.&lt;/p&gt;

&lt;h3 id=&quot;dữ-liệu-quan-sát&quot;&gt;Dữ liệu quan sát&lt;/h3&gt;

&lt;p&gt;Ta tung 10 lần và thu được 7 mặt ngửa.&lt;/p&gt;

&lt;h3 id=&quot;cập-nhật&quot;&gt;Cập nhật&lt;/h3&gt;

&lt;p&gt;Định lý Bayes kết hợp prior ban đầu với dữ liệu 7/10 để tạo ra phân phối posterior cho \(\theta\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/coin_bayes_visualization.png&quot; alt=&quot;Bayes với ví dụ đồng xu&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Điểm cần chú ý là posterior không giữ nguyên ở prior, nhưng cũng không nhảy thẳng về tỷ lệ mẫu 0.7; nó là sự dung hòa giữa kiến thức ban đầu và dữ liệu vừa quan sát.&lt;/p&gt;

&lt;h2 id=&quot;6-vai-trò-của-prior-likelihood-và-posterior&quot;&gt;6. Vai trò của prior, likelihood và posterior&lt;/h2&gt;

&lt;h3 id=&quot;61-prior&quot;&gt;6.1. Prior&lt;/h3&gt;

&lt;p&gt;Prior biểu diễn niềm tin trước khi có dữ liệu hiện tại. Chẳng hạn, ta biết tỷ lệ qua môn các khóa trước thường quanh 70%, một loại thuốc tương tự thường có hiệu quả ở mức vừa phải, hay đồng xu mua từ cửa hàng thường gần cân bằng.&lt;/p&gt;

&lt;h3 id=&quot;62-likelihood&quot;&gt;6.2. Likelihood&lt;/h3&gt;

&lt;p&gt;Likelihood đo mức độ phù hợp của dữ liệu hiện tại với từng giá trị tham số. Ví dụ, nếu đồng xu thực sự cân bằng thì dữ liệu 7/10 mặt ngửa hợp lý đến mức nào, hoặc nếu tỷ lệ qua môn thực sự là 0.9 thì dữ liệu quan sát có còn phù hợp không.&lt;/p&gt;

&lt;h3 id=&quot;63-posterior&quot;&gt;6.3. Posterior&lt;/h3&gt;

&lt;p&gt;Posterior là niềm tin sau khi đã cập nhật bằng dữ liệu. Đây là đối tượng trung tâm của suy luận Bayes, vì từ posterior ta có thể xác định vùng giá trị khả dĩ của tham số, tính xác suất tham số vượt qua một ngưỡng cụ thể, hoặc tìm khoảng giá trị hợp lý nhất của nó.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayes_theorem_prior.png&quot; alt=&quot;Prior trước khi nhìn dữ liệu&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayes_theorem_likelihood.png&quot; alt=&quot;Likelihood cho biết dữ liệu ủng hộ giá trị nào của tham số&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayes_theorem_posterior.png&quot; alt=&quot;Posterior sau khi cập nhật bằng dữ liệu&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayes_theorem_prior_vs_posterior.png&quot; alt=&quot;So sánh prior và posterior để thấy dữ liệu đã kéo niềm tin đi đâu&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-đếm-người-thay-vì-nhân-xác-suất&quot;&gt;Thử nghiệm: đếm người thay vì nhân xác suất&lt;/h3&gt;

&lt;p&gt;Kéo tỉ lệ nền, độ nhạy và độ đặc hiệu; bấm Bước tiếp để xem 1000 người tách thành bệnh/khỏe, dương/âm tính và vì sao kết quả dương tính chưa chắc là bệnh.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;bayesrule-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;tree&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;7-ví-dụ-kinh-điển-xét-nghiệm-y-khoa&quot;&gt;7. Ví dụ kinh điển: xét nghiệm y khoa&lt;/h2&gt;

&lt;p&gt;Đây là ví dụ minh họa rõ sức mạnh của định lý Bayes. Giả sử một căn bệnh hiếm chỉ ảnh hưởng đến 1% dân số, xét nghiệm có độ nhạy và độ đặc hiệu đều cao, và một người nhận kết quả dương tính. Câu hỏi người bệnh thực sự quan tâm là: “Xác suất tôi thực sự mắc bệnh là bao nhiêu?”&lt;/p&gt;

&lt;p&gt;Nhiều người dễ nhầm rằng kết quả dương tính gần như đồng nghĩa với chắc chắn mắc bệnh. Tuy nhiên, định lý Bayes cho thấy khi bệnh rất hiếm (prior thấp), ngay cả một xét nghiệm có độ chính xác khá cao cũng chưa chắc đẩy xác suất hậu nghiệm lên mức cao. Trong những tình huống như vậy, Bayes cho kết quả chính xác hơn hẳn trực giác cảm tính.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-nghịch-lý-xét-nghiệm-bệnh-hiếm-trên-ma-trận-1000-người&quot;&gt;Video ngắn: Nghịch lý Xét nghiệm Bệnh hiếm trên Ma trận 1.000 người&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-03b-medical-screening-1000.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Video dài khoảng 17 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): lưới 100 chấm trực quan (1% mắc bệnh) chỉ rõ vì sao 50 ca dương tính giả áp đảo 9 ca thật, khiến P(Bệnh&lt;/td&gt;
      &lt;td&gt;Dương tính) chỉ còn 15.3%.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;71-tính-số-cụ-thể-cho-bài-toán-xét-nghiệm-bệnh-hiếm-vd1&quot;&gt;7.1. Tính số cụ thể cho bài toán xét nghiệm bệnh hiếm (VD1)&lt;/h3&gt;

&lt;p&gt;Giả sử tỷ lệ mắc bệnh ban đầu là \(P(D)=0.001\), độ nhạy là \(P(+\mid D)=0.9\), và tỷ lệ dương tính giả là \(P(+\mid D&apos;)=0.01\). Ta cần tính:&lt;/p&gt;

\[P(D\mid +)=\frac{P(+\mid D)P(D)}{P(+)}.\]

&lt;p&gt;Áp dụng công thức xác suất toàn phần:&lt;/p&gt;

\[P(+)=P(+\mid D)P(D)+P(+\mid D&apos;)P(D&apos;)\]

\[=0.9\times 0.001+0.01\times 0.999=0.01089.\]

&lt;p&gt;Suy ra:&lt;/p&gt;

\[P(D\mid +)=\frac{0.9\times 0.001}{0.01089}\approx 0.0826.\]

&lt;p&gt;Dù xét nghiệm khá tốt, xác suất hậu nghiệm vẫn chỉ khoảng \(8.26\%\) do tỷ lệ nền (base rate) của bệnh rất thấp.&lt;/p&gt;

&lt;h3 id=&quot;72-đọc-bài-toán-qua-ma-trận-nhầm-lẫn&quot;&gt;7.2. Đọc bài toán qua ma trận nhầm lẫn&lt;/h3&gt;

&lt;p&gt;Trong chẩn đoán nhị phân, &lt;strong&gt;ma trận nhầm lẫn (confusion matrix)&lt;/strong&gt; giúp phân biệt rõ các đại lượng: &lt;strong&gt;True Positive (TP)&lt;/strong&gt; là có bệnh và xét nghiệm dương tính, &lt;strong&gt;False Positive (FP)&lt;/strong&gt; là không bệnh nhưng xét nghiệm dương tính, &lt;strong&gt;False Negative (FN)&lt;/strong&gt; là có bệnh nhưng xét nghiệm âm tính, còn &lt;strong&gt;True Negative (TN)&lt;/strong&gt; là không bệnh và xét nghiệm âm tính. Khi đó, độ nhạy là \(P(+\mid D)=\frac{TP}{TP+FN}\), độ đặc hiệu là \(P(-\mid D&apos;)=\frac{TN}{TN+FP}\), và tỷ lệ dương tính giả là \(P(+\mid D&apos;)=1-\text{độ đặc hiệu}\).&lt;/p&gt;

&lt;p&gt;Điều người bệnh quan tâm lại là \(P(D\mid +)\), tức giá trị tiên đoán dương (PPV). Định lý Bayes giúp chuyển từ các xác suất điều kiện theo hàng/cột của ma trận nhầm lẫn sang xác suất hậu nghiệm cần thiết cho quyết định lâm sàng.&lt;/p&gt;

&lt;h3 id=&quot;73-ví-dụ-điều-kiện-hóa-theo-ngữ-cảnh-vd2&quot;&gt;7.3. Ví dụ điều kiện hóa theo ngữ cảnh (VD2)&lt;/h3&gt;

&lt;p&gt;Giả sử \(P(\text{Icy})=0.7\) và \(P(\text{Not Icy})=0.3\), đồng thời \(P(\text{One crashes}\mid \text{Icy})=0.8\) còn \(P(\text{One crashes}\mid \text{Not Icy})=0.1\).&lt;/p&gt;

&lt;p&gt;Trước hết, áp dụng công thức xác suất toàn phần:&lt;/p&gt;

\[P(\text{One crashes})=0.8\times 0.7+0.1\times 0.3=0.59.\]

&lt;p&gt;Nếu quan sát thấy Watson bị tai nạn, ta cập nhật xác suất đường đóng băng:&lt;/p&gt;

\[P(\text{Icy}\mid \text{Watson crashes})=\frac{0.8\times 0.7}{0.59}\approx 0.95.\]

&lt;p&gt;Từ đó, xác suất Holmes cũng bị tai nạn sau khi biết tin về Watson là:&lt;/p&gt;

\[P(\text{Holmes crashes}\mid \text{Watson crashes})=0.8\times 0.95+0.1\times 0.05=0.765.\]

&lt;p&gt;Điểm cốt lõi của ví dụ này là ta cập nhật niềm tin về điều kiện môi trường (đường có đóng băng hay không), rồi dùng niềm tin mới đó để suy ra xác suất của sự kiện tiếp theo.&lt;/p&gt;

&lt;h2 id=&quot;8-vai-trò-của-evidence&quot;&gt;8. Vai trò của evidence&lt;/h2&gt;

&lt;p&gt;Trong công thức Bayes, đại lượng:&lt;/p&gt;

\[P(D)\]

&lt;p&gt;là xác suất quan sát được dữ liệu tính trên mọi giá trị có thể của tham số. Bạn có thể xem evidence như hằng số chuẩn hóa giúp đảm bảo posterior là một phân phối xác suất hợp lệ (có tổng hoặc tích phân bằng 1). Trong thực hành, ta thường làm việc trước với dạng tỉ lệ:&lt;/p&gt;

\[P(\theta \mid D) \propto P(D \mid \theta)P(\theta)\]

&lt;p&gt;và thực hiện bước chuẩn hóa ở công đoạn sau.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-mẫu-số-evidence-pd-vì-sao-phải-chia-cho-diện-tích&quot;&gt;Video ngắn: Mẫu số Evidence P(D): Vì sao phải Chia cho Diện tích?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-03c-evidence-area-normalizer.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 17 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): tích thô Prior × Likelihood chỉ có diện tích 0.179; chia cho hằng số Evidence P(D) bơm đường cong phồng lên cho đến khi tổng diện tích bằng đúng 1.000.&lt;/p&gt;

&lt;h2 id=&quot;9-cập-nhật-tuần-tự-trong-bayes&quot;&gt;9. Cập nhật tuần tự trong Bayes&lt;/h2&gt;

&lt;p&gt;Một tính chất quan trọng của thống kê Bayes là khả năng &lt;strong&gt;cập nhật tuần tự&lt;/strong&gt;. Giả sử hôm nay bạn có dữ liệu tuần 1, tuần sau có thêm dữ liệu tuần 2, rồi tuần tiếp theo có thêm dữ liệu tuần 3. Bạn không cần bắt đầu lại từ đầu một cách tách biệt; posterior ở bước hiện tại có thể trở thành prior cho lần cập nhật kế tiếp. Tính chất này đặc biệt phù hợp với bảng điều khiển kinh doanh, giám sát vận hành và mọi bài toán cần học liên tục từ dữ liệu đến theo thời gian.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_sequential_updating_prior.png&quot; alt=&quot;Bước khởi đầu: prior ban đầu&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_sequential_updating_step1.png&quot; alt=&quot;Sau đợt dữ liệu đầu tiên&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_sequential_updating_step2.png&quot; alt=&quot;Sau đợt dữ liệu thứ hai&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_sequential_updating_batch_comparison.png&quot; alt=&quot;So sánh cập nhật tuần tự với cập nhật một lần&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;91-ví-dụ-cập-nhật-tuần-tự-với-hai-xét-nghiệm-vd3&quot;&gt;9.1. Ví dụ cập nhật tuần tự với hai xét nghiệm (VD3)&lt;/h3&gt;

&lt;p&gt;Giả sử:&lt;/p&gt;

\[P(\theta=1)=0.7,\quad P(\theta=0)=0.3,\]

&lt;p&gt;trong đó \(\theta=1\) biểu thị trạng thái có bệnh. Xét nghiệm thứ nhất \(Y\) thỏa mãn \(P(Y=1\mid \theta=1)=0.95\) và \(P(Y=1\mid \theta=0)=0.40\), và ta quan sát được \(Y=1\). Khi đó:&lt;/p&gt;

\[P(\theta=1\mid Y=1)=\frac{0.95\times 0.7}{0.95\times 0.7+0.40\times 0.3}
=\frac{0.665}{0.785}\approx 0.847.\]

&lt;p&gt;Tiếp theo, xét nghiệm thứ hai \(W\) độc lập có điều kiện theo \(\theta\), với \(P(W=1\mid \theta=1)=0.99\) (nên \(P(W=0\mid \theta=1)=0.01\)) và \(P(W=1\mid \theta=0)=0.04\) (nên \(P(W=0\mid \theta=0)=0.96\)), và ta quan sát được \(W=0\). Cập nhật lần thứ hai:&lt;/p&gt;

\[P(\theta=1\mid Y=1,W=0)=
\frac{P(W=0\mid \theta=1)P(\theta=1\mid Y=1)}{P(W=0\mid Y=1)}
\approx 0.055.\]

&lt;p&gt;Như vậy, xác suất hậu nghiệm thay đổi rõ rệt theo từng bằng chứng mới: từ \(0.7 \to 0.847 \to 0.055\).&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-cập-nhật-tuần-tự-qua-từng-lần-tung&quot;&gt;Thử nghiệm: cập nhật tuần tự qua từng lần tung&lt;/h3&gt;

&lt;p&gt;Ba loại đồng xu, mỗi lần tung nhân prior với likelihood rồi chuẩn hóa; đổi prior để thấy dữ liệu dần áp đảo.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;bayesrule-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;sequential&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;10-ảnh-hưởng-của-prior-mạnh-và-prior-yếu&quot;&gt;10. Ảnh hưởng của prior mạnh và prior yếu&lt;/h2&gt;

&lt;p&gt;Nếu prior rất mạnh, một lượng dữ liệu ít có thể chưa làm posterior dịch chuyển nhiều. Ngược lại, nếu prior yếu, dữ liệu sẽ tác động mạnh hơn đến posterior. Đây không phải hạn chế của Bayes mà là hành vi hợp lý: khi kiến thức nền đã vững chắc, ta không nên từ bỏ nó quá dễ dàng trước vài quan sát lẻ tẻ; còn khi kiến thức ban đầu mơ hồ, dữ liệu mới cần có tiếng nói lớn hơn.&lt;/p&gt;

&lt;h3 id=&quot;101-ví-dụ-cụ-thể-cùng-dữ-liệu-prior-khác-nhau&quot;&gt;10.1. Ví dụ cụ thể: cùng dữ liệu, prior khác nhau&lt;/h3&gt;

&lt;p&gt;Giả sử ta quan sát 6 ca dương tính trong 10 trường hợp:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Nếu dùng prior yếu Beta\((1,1)\), posterior là Beta\((7,5)\) với trung bình hậu nghiệm khoảng \(0.583\).&lt;/li&gt;
  &lt;li&gt;Nếu dùng prior mạnh hơn nghiêng về tỷ lệ cao, chẳng hạn Beta\((20,5)\), posterior là Beta\((26,9)\) với trung bình hậu nghiệm khoảng \(0.743\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cùng một bộ dữ liệu nhưng posterior khác nhau vì prior đưa thông tin thực sự vào bài toán. Điều này phản ánh đúng thực tế: dữ liệu mới luôn được diễn giải trong bối cảnh của những gì ta đã biết từ trước.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_prior_strength_weak_prior.png&quot; alt=&quot;Prior yếu: niềm tin ban đầu còn khá mở&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_prior_strength_strong_prior.png&quot; alt=&quot;Prior mạnh: niềm tin ban đầu tập trung hơn nhiều&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_prior_strength_weak_posterior.png&quot; alt=&quot;Khi prior yếu, posterior bị dữ liệu kéo mạnh hơn&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_prior_strength_strong_posterior.png&quot; alt=&quot;Khi prior mạnh, posterior thay đổi ít hơn&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-cuộc-kéo-co-prior-yếu-vs-prior-mạnh-khi-dữ-liệu-tăng-từ-0--120&quot;&gt;Video ngắn: Cuộc kéo co: Prior Yếu vs Prior Mạnh khi Dữ liệu tăng từ 0 → 120&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-03d-prior-strength-tug-of-war.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 20 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): so sánh song song Prior yếu Beta(2,2) và Prior mạnh Beta(20,20) trước cùng luồng dữ liệu 80% Ngửa: mẫu nhỏ thì Prior mạnh kháng cự, mẫu lớn thì dữ liệu thắng áp đảo.&lt;/p&gt;

&lt;h2 id=&quot;11-tư-duy-cốt-lõi-của-định-lý-bayes&quot;&gt;11. Tư duy cốt lõi của định lý Bayes&lt;/h2&gt;

&lt;p&gt;Định lý Bayes không chỉ cung cấp một công thức tính xác suất có điều kiện, mà đề xuất một cách suy luận minh bạch: dữ liệu không tự mang ý nghĩa nếu tách khỏi mô hình, kiến thức ban đầu không phải điều cấm kỵ, dữ liệu mới có quyền điều chỉnh niềm tin cũ, và toàn bộ quá trình cập nhật đều được trình bày rõ ràng. Khi nắm được tinh thần đó, các khái niệm prior và posterior sẽ trở nên tự nhiên.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Định lý Bayes là quy tắc cập nhật niềm tin khi có thêm bằng chứng mới; prior, likelihood và posterior không phải ba khái niệm tách rời mà là ba mắt xích của cùng một quy trình suy luận; và giá trị của Bayes nằm ở việc kết hợp kiến thức sẵn có với dữ liệu mới một cách minh bạch.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;giải-thích-tính-hậu-nghiệm-bằng-bảng-bayes-4-cột-và-kiểm-chứng-cập-nhật-tuần-tự&quot;&gt;Giải thích: Tính hậu nghiệm bằng bảng Bayes 4 cột và kiểm chứng cập nhật tuần tự&lt;/h2&gt;

&lt;p&gt;Thay vì cố nhẩm mẫu số \(P(y)\) ngay từ đầu, cách làm ít sai nhất khi tính tay là lập &lt;strong&gt;bảng Bayes 4 cột&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cột 1 (Giả thuyết \(\theta\)):&lt;/strong&gt; Liệt kê đầy đủ các giả thuyết xung khắc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cột 2 (Prior \(P(\theta)\)):&lt;/strong&gt; Ghi xác suất ban đầu (tổng bằng 1).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cột 3 (Likelihood \(P(y \mid \theta)\)):&lt;/strong&gt; Tính xác suất quan sát đúng dữ liệu \(y\) dưới từng giả thuyết.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cột 4 (Tích chưa chuẩn hóa &amp;amp; Chuẩn hóa):&lt;/strong&gt; Nhân Cột 2 với Cột 3, cộng tổng để thu \(P(y)\), rồi chia từng dòng cho tổng đó để ra Posterior.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-phân-biệt-đồng-xu-công-bằng-và-đồng-xu-thiên-lệch&quot;&gt;Ví dụ tính toán làm từng bước: Phân biệt đồng xu công bằng và đồng xu thiên lệch&lt;/h3&gt;

&lt;p&gt;Trong túi có 2 đồng xu: \(H_0\) công bằng (\(p = 0.5\)) với prior \(0.7\), và \(H_1\) thiên lệch (\(p = 0.8\)) với prior \(0.3\). Ta chọn ngẫu nhiên một đồng xu, tung 2 lần độc lập và cả 2 lần đều ra Ngửa (\(y = \text{NN}\)).&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Giả thuyết&lt;/th&gt;
      &lt;th&gt;Prior \(P(H)\)&lt;/th&gt;
      &lt;th&gt;Likelihood \(P(\text{NN} \vert H)\)&lt;/th&gt;
      &lt;th&gt;Tích \(P(H)P(\text{NN} \vert H)\)&lt;/th&gt;
      &lt;th&gt;Posterior \(P(H \vert \text{NN})\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(H_0\; (p=0.5)\)&lt;/td&gt;
      &lt;td&gt;\(0.70\)&lt;/td&gt;
      &lt;td&gt;\(0.5^2 = 0.25\)&lt;/td&gt;
      &lt;td&gt;\(0.1750\)&lt;/td&gt;
      &lt;td&gt;\(0.1750 / 0.3670 \approx 0.4768\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(H_1\; (p=0.8)\)&lt;/td&gt;
      &lt;td&gt;\(0.30\)&lt;/td&gt;
      &lt;td&gt;\(0.8^2 = 0.64\)&lt;/td&gt;
      &lt;td&gt;\(0.1920\)&lt;/td&gt;
      &lt;td&gt;\(0.1920 / 0.3670 \approx 0.5232\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Tổng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(1.00\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(P(\text{NN}) = 0.3670\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(1.0000\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chỉ sau 2 lần ra Ngửa liên tiếp, niềm tin vào đồng xu thiên lệch đã tăng từ \(30\%\) lên \(52.32\%\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Cộng tổng cột Likelihood rồi thắc mắc vì sao \(0.25 + 0.64 = 0.89 \neq 1\). Likelihood là hàm theo tham số với dữ liệu cố định, nên &lt;strong&gt;không&lt;/strong&gt; nhất thiết có tổng bằng 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh (Cập nhật tuần tự):&lt;/strong&gt; Nếu tách thành từng lần tung: sau lần 1 ra Ngửa, \(P(H_1 \mid \text{N}) = \frac{0.3 \times 0.8}{0.7 \times 0.5 + 0.3 \times 0.8} = \frac{0.24}{0.59} \approx 0.4068\). Dùng \(0.4068\) làm prior cho lần 2 ra Ngửa: \(P(H_1 \mid \text{NN}) = \frac{0.4068 \times 0.8}{0.5932 \times 0.5 + 0.4068 \times 0.8} = \frac{0.3254}{0.6220} \approx 0.5232\) — khớp chính xác tuyệt đối!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zXtcZ-2adK0&quot;&gt;P01.007 — Định lý Bayes cập nhật niềm tin của mô hình ra sao?&lt;/a&gt; — Phạm Thông, Tiếng Việt. &lt;strong&gt;xem trước&lt;/strong&gt;. Giải thích bằng tiếng Việt cách prior và dữ liệu cùng cập nhật niềm tin, phù hợp với cách tiếp cận của bài học.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Minh họa trực quan vai trò của prior, likelihood và hằng số chuẩn hóa trên hình học.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R1vcdhPBlXA&quot;&gt;Statistical Rethinking 2023 - 02 - The Garden of Forking Data&lt;/a&gt; — Richard McElreath, English. Trình bày ví dụ quả địa cầu nước và đất, nơi định lý Bayes trở thành bài toán đếm các khả năng sinh dữ liệu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Trong ví dụ bác sĩ chẩn đoán bệnh, prior đến từ đâu và likelihood đến từ đâu?&lt;/li&gt;
  &lt;li&gt;Vì sao kết quả dương tính của một xét nghiệm chưa chắc đồng nghĩa với xác suất mắc bệnh rất cao?&lt;/li&gt;
  &lt;li&gt;Hãy nêu một ví dụ trong công việc của bạn nơi posterior hôm nay có thể trở thành prior ngày mai.&lt;/li&gt;
  &lt;li&gt;Vì sao posterior không nhất thiết trùng với tỷ lệ quan sát trực tiếp từ dữ liệu?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 1.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 5.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 1-2.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter01/01_04_bayesian_vs_frequentist/&quot;&gt;1.4 Bayesian vs Frequentist - So Sánh và Lựa Chọn&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 1.2: Xác suất như Độ hợp lý - Nền tảng Triết học của Bayesian</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_02_probability_as_plausibility/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_02_probability_as_plausibility</id>
   <content type="html">&lt;p&gt;Năm 1946, nhà vật lý Richard Cox đặt ra một câu hỏi tưởng thuộc về triết học thuần túy: nếu ta muốn mở rộng logic đúng/sai của Aristotle sang thế giới không chắc chắn — sao cho mức độ hợp lý của các mệnh đề luôn nhất quán — thì bộ quy tắc toán học nào là duy nhất? Kết quả chứng minh của ông gây kinh ngạc: bất kỳ hệ thống suy luận hợp lý nhất quán nào cũng &lt;em&gt;bắt buộc&lt;/em&gt; phải đẳng cấu với các quy tắc xác suất (quy tắc cộng và quy tắc nhân), từ đó kéo theo định lý Bayes.&lt;/p&gt;

&lt;p&gt;Trước đó ít lâu, Frank Ramsey và Bruno de Finetti cũng đi tới đúng kết luận ấy từ một hướng khác hoàn toàn: nếu niềm tin của bạn vi phạm tiên đề xác suất, đối thủ có thể lập một tổ hợp kèo cược (&lt;em&gt;Dutch book&lt;/em&gt;) khiến bạn chắc chắn thua tiền bất kể thực tế diễn ra thế nào.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn cần hiểu vì sao thống kê Bayes xem xác suất là &lt;strong&gt;mức độ hợp lý của niềm tin&lt;/strong&gt; chứ không chỉ là tần suất dài hạn. Bạn cũng cần thấy được lợi thế của cách hiểu này trong những bài toán thực tế, nơi ta cần đánh giá các biến cố chỉ xảy ra một lần, các giả thuyết và các tham số chưa biết.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ mini.&lt;/strong&gt; Khi nghe “70% khả năng mưa ngày mai”, bạn hiểu đó là mức độ tin cậy hiện tại để quyết định có mang ô hay không, chứ không phải tần suất thu được từ vô số lần lặp lại của “ngày mai”.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Vì sao câu “xác suất trời mưa ngày mai là 70%” khó diễn giải theo nghĩa tần suất nhưng lại rất tự nhiên theo quan điểm Bayes?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-diễn-giải-xác-suất-định-lý-cox-và-tính-nhất-quán-dutch-book&quot;&gt;Kiến thức cần nhớ: Diễn giải xác suất, Định lý Cox và Tính nhất quán Dutch Book&lt;/h2&gt;

&lt;p&gt;Bài học này đặt nền móng triết học – toán học cho toàn bộ khóa học thông qua ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tần suất dài hạn so với Độ hợp lý (Frequentist vs. Epistemic Probability):&lt;/strong&gt; Trường phái tần suất định nghĩa xác suất qua giới hạn của thí nghiệm lặp vô hạn, nên không thể gán xác suất cho sự kiện đơn lẻ hay tham số cố định. Trường phái Bayes xem xác suất là &lt;strong&gt;độ hợp lý có điều kiện trên thông tin hiện có&lt;/strong&gt;, áp dụng thống nhất cho cả dữ liệu lẫn tham số chưa biết.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Định lý Cox &amp;amp; Lập luận Dutch Book:&lt;/strong&gt; Chứng minh rằng xác suất Bayes không phải sự tùy tiện chủ quan, mà là hệ quả logic duy nhất của yêu cầu nhất quán (&lt;em&gt;coherence&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Mô hình hóa Bayes:&lt;/strong&gt; Khi xem tham số \(\theta\) cũng có phân phối xác suất biểu diễn trạng thái tri thức, mọi bài toán suy luận, dự báo và kiểm định đều quy về một phép toán duy nhất: tính xác suất có điều kiện và biên hóa.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-một-câu-hỏi-tưởng-đơn-giản-xác-suất-thực-chất-là-gì&quot;&gt;1. Một câu hỏi tưởng đơn giản: xác suất thực chất là gì?&lt;/h2&gt;

&lt;p&gt;Trong nhiều khóa thống kê truyền thống, xác suất thường được giới thiệu là tần suất xuất hiện của một sự kiện qua rất nhiều lần lặp lại. Định nghĩa này hoạt động tốt với những ví dụ như tung đồng xu, gieo xúc xắc hay rút thẻ từ bộ bài. Tuy nhiên, nó bắt đầu bộc lộ giới hạn khi ta đặt ra các câu hỏi rất thực tế như: xác suất trời mưa ngày mai là bao nhiêu, xác suất bệnh nhân này mắc bệnh A hay B là bao nhiêu, hay xác suất mô hình này đúng hơn mô hình kia là bao nhiêu. Những sự kiện như vậy khó có thể hiểu theo nghĩa “lặp lại vô hạn lần” một cách cơ học.&lt;/p&gt;

&lt;h2 id=&quot;2-quan-điểm-tần-suất-xác-suất-là-tần-suất-dài-hạn&quot;&gt;2. Quan điểm tần suất: xác suất là tần suất dài hạn&lt;/h2&gt;

&lt;p&gt;Theo quan điểm tần suất (frequentist), xác suất của một sự kiện là tần suất tương đối của nó khi số lần lặp tiến tới rất lớn. Ví dụ, với một đồng xu cân bằng, khi tung rất nhiều lần thì tỷ lệ mặt ngửa sẽ tiến gần về 0.5. Đây là một ý tưởng chặt chẽ và có vai trò quan trọng, nhưng nó có hai giới hạn lớn.&lt;/p&gt;

&lt;h3 id=&quot;21-khó-áp-dụng-cho-sự-kiện-chỉ-xảy-ra-một-lần&quot;&gt;2.1. Khó áp dụng cho sự kiện chỉ xảy ra một lần&lt;/h3&gt;

&lt;p&gt;Những biến cố như ngày mai có mưa hay không, ca phẫu thuật này có thành công hay không, hay thị trường tuần tới tăng hay giảm đều là các sự kiện đơn lẻ. Ta không thể “lặp lại vô hạn lần” đúng cùng một ngày mai để định nghĩa xác suất theo nghĩa tần suất thuần túy.&lt;/p&gt;

&lt;h3 id=&quot;22-khó-phát-biểu-trực-tiếp-về-tham-số-chưa-biết&quot;&gt;2.2. Khó phát biểu trực tiếp về tham số chưa biết&lt;/h3&gt;

&lt;p&gt;Trong thống kê tần suất, tham số \(\theta\) được xem là một hằng số cố định nhưng chưa biết, còn dữ liệu mới là đại lượng ngẫu nhiên. Vì vậy, trường phái này tránh nói “xác suất để \(\theta\) nằm giữa 0.4 và 0.6 là 95%”, bởi theo quan điểm của họ, \(\theta\) không phải biến ngẫu nhiên để có thể gán xác suất.&lt;/p&gt;

&lt;h2 id=&quot;3-quan-điểm-bayes-xác-suất-là-độ-hợp-lý&quot;&gt;3. Quan điểm Bayes: xác suất là độ hợp lý&lt;/h2&gt;

&lt;p&gt;Thống kê Bayes đi theo một hướng phù hợp hơn với nhiều bài toán thực tế: xác suất không chỉ là tần suất dài hạn, mà còn là mức độ tin cậy, mức độ hợp lý hay mức độ sẵn sàng đặt cược vào một mệnh đề dựa trên thông tin hiện có. Nhờ đó, phát biểu “70% khả năng mưa ngày mai” được hiểu một cách tự nhiên là: với thông tin hiện tại, mệnh đề “ngày mai có mưa” đáng tin ở mức 70%. Đây không phải cách nói cảm tính, mà là nền tảng của suy luận Bayes.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-tần-suất-dài-hạn-vs-độ-hợp-lý-bayes-câu-chuyện-chiếc-ô&quot;&gt;Video ngắn: Tần suất dài hạn vs Độ hợp lý Bayes (Câu chuyện Chiếc Ô)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-02a-frequentist-vs-plausibility.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 28 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): đối chiếu tần suất tung xu dài hạn với thanh độ hợp lý cập nhật trực tiếp P(Mưa hôm nay) từ 20% → 55% → 82% → 95% qua từng bằng chứng mới.&lt;/p&gt;

&lt;h2 id=&quot;4-vì-sao-cách-hiểu-bayes-gần-với-đời-sống-hơn&quot;&gt;4. Vì sao cách hiểu Bayes gần với đời sống hơn?&lt;/h2&gt;

&lt;p&gt;Cách hiểu này phản ánh đúng cách con người suy luận hằng ngày trong nhiều tình huống quen thuộc.&lt;/p&gt;

&lt;h3 id=&quot;41-dự-báo-thời-tiết&quot;&gt;4.1. Dự báo thời tiết&lt;/h3&gt;

&lt;p&gt;Khi nghe “70% khả năng mưa”, bạn không nghĩ về vô số thế giới song song, mà đơn giản hiểu rằng khả năng mưa khá cao nên mang theo ô là hợp lý.&lt;/p&gt;

&lt;h3 id=&quot;42-chẩn-đoán-y-khoa&quot;&gt;4.2. Chẩn đoán y khoa&lt;/h3&gt;

&lt;p&gt;Bác sĩ không chỉ nhìn vào triệu chứng trước mắt, mà còn kết hợp tỷ lệ mắc bệnh trong cộng đồng, tuổi tác, tiền sử bệnh và các kết quả xét nghiệm trước đó. Quá trình ấy chính là cập nhật niềm tin dựa trên thông tin.&lt;/p&gt;

&lt;h3 id=&quot;43-kinh-doanh&quot;&gt;4.3. Kinh doanh&lt;/h3&gt;

&lt;p&gt;Một công ty khởi nghiệp thấy 3 khách hàng đầu tiên đều mua hàng. Không ai kết luận ngay rằng tỷ lệ mua hàng thực sự là 100%; thay vào đó, ta giữ một mức bất định hợp lý và tiếp tục cập nhật khi có thêm dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;5-ví-dụ-trực-quan-đồng-xu-của-người-bạn&quot;&gt;5. Ví dụ trực quan: đồng xu của người bạn&lt;/h2&gt;

&lt;p&gt;Giả sử bạn của bạn đưa một đồng xu và nói: “Tôi vừa tung 10 lần, ra 8 mặt ngửa.” Câu hỏi bạn thực sự muốn trả lời là xác suất ra ngửa của đồng xu này có thể nằm ở mức nào.&lt;/p&gt;

&lt;h3 id=&quot;theo-quan-điểm-tần-suất&quot;&gt;Theo quan điểm tần suất&lt;/h3&gt;

&lt;p&gt;Nhà thống kê tần suất xem tham số thực là một hằng số cố định; ta chỉ có thể ước lượng nó từ mẫu và dựng khoảng tin cậy.&lt;/p&gt;

&lt;h3 id=&quot;theo-quan-điểm-bayes&quot;&gt;Theo quan điểm Bayes&lt;/h3&gt;

&lt;p&gt;Nhà thống kê Bayes đặt một phân phối tiền nghiệm (prior) cho \(\theta\) trước khi thấy dữ liệu; sau khi quan sát 8/10 mặt ngửa, prior đó được cập nhật thành phân phối hậu nghiệm (posterior), cho biết vùng giá trị nào của \(\theta\) hiện đang hợp lý hơn.&lt;/p&gt;

&lt;p&gt;Điểm mạnh của cách tiếp cận Bayes là cho phép phát biểu trực tiếp về tham số chưa biết, mức độ tin cậy hiện tại và cách niềm tin đó dịch chuyển theo dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;cách-đọc-bằng-con-số&quot;&gt;Cách đọc bằng con số&lt;/h3&gt;

&lt;p&gt;Nếu bắt đầu với prior đều Beta\((1,1)\) và quan sát 8 mặt ngửa trong 10 lần tung, posterior sẽ là Beta\((9,3)\). Trung bình hậu nghiệm lúc này là:&lt;/p&gt;

\[\frac{9}{9+3}=0.75.\]

&lt;p&gt;Ta cũng có thể hỏi trực tiếp: “xác suất đồng xu thiên về mặt ngửa cao hơn mức cân bằng là bao nhiêu?”, tức \(P(\theta&amp;gt;0.5\mid D)\), và giá trị này vào khoảng \(0.97\). Đây chính là tinh thần xem xác suất như độ hợp lý: nó cho phép định lượng trực tiếp mức độ hợp lý của các giá trị tham số sau khi đã quan sát dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;6-tính-chủ-quan-có-phải-là-điểm-yếu-không&quot;&gt;6. Tính “chủ quan” có phải là điểm yếu không?&lt;/h2&gt;

&lt;p&gt;Nhiều người khi nghe đến “mức độ tin cậy” (degree of belief) thường lo ngại rằng thống kê Bayes quá chủ quan. Tuy nhiên, cần phân biệt giữa &lt;strong&gt;chủ quan có nguyên tắc&lt;/strong&gt; và sự tùy tiện. Trong thống kê Bayes, bạn không được gán xác suất một cách vô căn cứ; các xác suất phải nhất quán, tuân thủ các tiên đề xác suất và chịu sự điều chỉnh của dữ liệu. Nói cách khác, Bayes cho phép đưa kiến thức ban đầu vào mô hình, nhưng buộc niềm tin đó phải có cấu trúc logic rõ ràng và sẵn sàng thay đổi trước bằng chứng mới.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-lạc-quan-vs-bi-quan-dữ-liệu-kéo-hai-niềm-tin-về-cùng-1-đích&quot;&gt;Video ngắn: Lạc quan vs Bi quan: Dữ liệu kéo Hai Niềm tin về Cùng 1 Đích!&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-02c-two-priors-converge.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 24 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): hai người bắt đầu với Prior trái ngược hoàn toàn (Beta(9,2) vs Beta(2,9)), nhưng sau 160 dữ liệu (θ = 0.65) cả hai đường hậu nghiệm hội tụ khít về cùng một đỉnh.&lt;/p&gt;

&lt;h2 id=&quot;7-trực-giác-dutch-book-vì-sao-niềm-tin-phải-nhất-quán&quot;&gt;7. Trực giác Dutch book: vì sao niềm tin phải nhất quán?&lt;/h2&gt;

&lt;p&gt;Một lập luận nổi tiếng gọi là &lt;strong&gt;Dutch book argument&lt;/strong&gt; chỉ ra rằng nếu hệ thống xác suất của bạn không nhất quán, người khác có thể thiết kế một tổ hợp kèo cược khiến bạn chắc chắn thua bất kể kết quả nào xảy ra. Bạn chưa cần đi sâu vào khía cạnh triết học này ngay lúc đầu; điều quan trọng cần nhớ là &lt;strong&gt;xác suất Bayes không phải “muốn tin gì thì tin”, mà là niềm tin có kỷ luật logic&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-nghịch-lý-dutch-book-niềm-tin-bất-nhất--chắc-chắn-thua-tiền&quot;&gt;Video ngắn: Nghịch lý Dutch Book: Niềm tin bất nhất = Chắc chắn thua tiền&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-02b-dutch-book-coherence.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 19 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): chứng minh trực quan bằng 2 vé cược giá 60đ (tổng 120đ &amp;gt; 100đ): dù trời mưa hay không mưa, người đặt niềm tin bất nhất đều lỗ chắc 20đ.&lt;/p&gt;

&lt;h2 id=&quot;8-cox-và-ý-tưởng-xác-suất-là-logic-mở-rộng&quot;&gt;8. Cox và ý tưởng “xác suất là logic mở rộng”&lt;/h2&gt;

&lt;p&gt;Logic cổ điển xử lý các mệnh đề chắc chắn đúng hoặc chắc chắn sai, trong khi xác suất xử lý những mệnh đề chưa chắc chắn hoàn toàn. Theo tinh thần đó, xác suất Bayes có thể được xem như một dạng &lt;strong&gt;logic mở rộng cho thế giới có bất định&lt;/strong&gt;. Điều này giải thích vì sao cách tiếp cận Bayes trở nên tự nhiên: khi chưa có dữ liệu, ta giữ một mức độ tin cậy ban đầu; khi dữ liệu mới xuất hiện, ta cập nhật niềm tin ấy một cách nhất quán.&lt;/p&gt;

&lt;h2 id=&quot;9-đại-lượng-nào-ngẫu-nhiên-đại-lượng-nào-cố-định&quot;&gt;9. Đại lượng nào ngẫu nhiên, đại lượng nào cố định?&lt;/h2&gt;

&lt;p&gt;Đây là khác biệt cốt lõi giữa hai trường phái Frequentist và Bayesian.&lt;/p&gt;

&lt;h3 id=&quot;trường-phái-frequentist&quot;&gt;Trường phái Frequentist&lt;/h3&gt;

&lt;p&gt;Tham số là đại lượng cố định nhưng chưa biết, còn dữ liệu là đại lượng ngẫu nhiên.&lt;/p&gt;

&lt;h3 id=&quot;trường-phái-bayesian&quot;&gt;Trường phái Bayesian&lt;/h3&gt;

&lt;p&gt;Dữ liệu đã quan sát là cố định, còn tham số chưa biết được mô tả bằng phân phối xác suất.&lt;/p&gt;

&lt;p&gt;Sự khác biệt nền tảng này dẫn đến hai cách diễn giải kết quả rất khác nhau.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_philosophy_frequentist.png&quot; alt=&quot;Frequentist nhìn xác suất theo dữ liệu lặp lại&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_philosophy_bayesian.png&quot; alt=&quot;Bayesian nhìn xác suất như bất định về tham số&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;10-vì-sao-bài-học-này-quan-trọng-cho-các-phần-sau&quot;&gt;10. Vì sao bài học này quan trọng cho các phần sau?&lt;/h2&gt;

&lt;p&gt;Nếu chưa chấp nhận rằng xác suất có thể biểu diễn mức độ hợp lý của niềm tin, toàn bộ các khái niệm Bayes ở những chương sau sẽ trở nên khó hiểu. Ngược lại, khi đã nắm rõ quan điểm này, những khái niệm như prior, posterior, khoảng tin cậy Bayes (credible interval) hay xác suất của giả thuyết sẽ trở nên mạch lạc và tự nhiên.&lt;/p&gt;

&lt;h2 id=&quot;11-tóm-lược-ngắn-gọn&quot;&gt;11. Tóm lược ngắn gọn&lt;/h2&gt;

&lt;p&gt;Nếu tóm gọn trong một câu: trường phái tần suất gắn xác suất với tần suất dài hạn của dữ liệu có thể lặp lại, còn trường phái Bayes gắn xác suất với mức độ hợp lý của niềm tin dựa trên thông tin hiện có. Không phải một bên hoàn toàn sai và bên kia hoàn toàn đúng trong mọi bối cảnh, nhưng cách hiểu Bayes linh hoạt hơn nhiều đối với các câu hỏi khoa học thực tế.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Frequentist và Bayesian khác nhau trước hết ở cách định nghĩa xác suất chứ không chỉ ở kỹ thuật tính toán; quan điểm Bayes xem xác suất là độ hợp lý nên áp dụng tự nhiên cho giả thuyết, tham số và các sự kiện chỉ xảy ra một lần; và tính “chủ quan” trong Bayes không đồng nghĩa với tùy tiện vì mọi niềm tin đều phải tuân thủ quy tắc nhất quán của xác suất.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;giải-thích-chứng-minh-bằng-con-số-vì-sao-niềm-tin-bất-nhất-sẽ-bị-dutch-book&quot;&gt;Giải thích: Chứng minh bằng con số vì sao niềm tin bất nhất sẽ bị “Dutch Book”&lt;/h2&gt;

&lt;p&gt;Nhiều người nghĩ tính nhất quán xác suất chỉ là lý thuyết suông. Hãy đọc chậm ví dụ đặt cược 4 bước sau để thấy bất kỳ sự vi phạm tiên đề cộng nào cũng dẫn đến thua lỗ chắc chắn:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Liên hệ niềm tin với giá cược công bằng:&lt;/strong&gt; Nếu bạn tin biến cố \(A\) có độ hợp lý \(q\), bạn sẵn sàng mua/bán một vé trả \(100\text{ nghìn}\) khi \(A\) xảy ra với giá \(100q\text{ nghìn}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giả sử niềm tin bị bất nhất:&lt;/strong&gt; Bạn gán xác suất đội X thắng là \(0.60\) và đội X không thắng là \(0.50\) — tổng bằng \(1.10 &amp;gt; 1\) (vi phạm tiên đề chuẩn hóa).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đối thủ thiết lập bộ kèo Dutch Book:&lt;/strong&gt; Đối thủ bán cho bạn cả hai vé (một vé “đội X thắng” giá \(60\text{ nghìn}\), một vé “đội X không thắng” giá \(50\text{ nghìn}\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra mọi kịch bản thực tế:&lt;/strong&gt; Tổng tiền bạn bỏ ra là \(110\text{ nghìn}\), nhưng dù kết quả trận đấu thế nào bạn cũng chỉ thắng đúng một vé và nhận lại \(100\text{ nghìn}\) — lỗ chắc chắn \(10\text{ nghìn}\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-bảng-kết-quả-của-một-dutch-book&quot;&gt;Ví dụ tính toán làm từng bước: Bảng kết quả của một Dutch Book&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Kịch bản thực tế&lt;/th&gt;
      &lt;th&gt;Tiền bạn bỏ ra mua 2 vé&lt;/th&gt;
      &lt;th&gt;Tiền nhận về từ vé thắng&lt;/th&gt;
      &lt;th&gt;Lãi / Lỗ ròng của bạn&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Đội X thắng (\(A\))&lt;/td&gt;
      &lt;td&gt;\(60 + 50 = 110\text{ nghìn}\)&lt;/td&gt;
      &lt;td&gt;\(100\text{ nghìn}\)&lt;/td&gt;
      &lt;td&gt;\(-10\text{ nghìn}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Đội X không thắng (\(A^c\))&lt;/td&gt;
      &lt;td&gt;\(60 + 50 = 110\text{ nghìn}\)&lt;/td&gt;
      &lt;td&gt;\(100\text{ nghìn}\)&lt;/td&gt;
      &lt;td&gt;\(-10\text{ nghìn}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Để không bao giờ rơi vào tình huống thua chắc chắn như vậy (dù ở vai người mua hay người bán vé), bộ niềm tin \(q(A)\) bắt buộc phải thỏa mãn đúng ba tiên đề Kolmogorov và quy tắc cập nhật Bayes khi có thêm thông tin!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nghĩ rằng “xác suất chủ quan” trong Bayes nghĩa là ai muốn bịa số nào cũng được. Thực chất “chủ quan” có nghĩa là &lt;em&gt;phụ thuộc vào thông tin hiện có&lt;/em&gt;, và mọi bước cập nhật từ thông tin đó đều bị ràng buộc chặt chẽ bởi toán học.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu bạn gán \(q(A) = 0.45\) và \(q(A^c) = 0.45\) (tổng \(0.90 &amp;lt; 1\)), đối thủ chỉ cần &lt;em&gt;mua lại&lt;/em&gt; cả hai vé từ bạn với tổng giá \(90\text{ nghìn}\) và chắc chắn thu về \(100\text{ nghìn}\) từ bạn — bạn vẫn lỗ chắc chắn \(10\text{ nghìn}\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R13BD8qKeTg&quot;&gt;The Bayesian Trap&lt;/a&gt; — Veritasium, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Minh họa cách dùng xác suất như mức độ tin vào giả thuyết, làm rõ bước chuyển từ tần suất dài hạn sang độ hợp lý.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=akClB1J6b28&quot;&gt;Bayes’ Theorem (with Example!)&lt;/a&gt; — Steve Brunton, English. Trình bày định lý Bayes như bài toán suy luận ngược từ dấu hiệu về nguyên nhân, hỗ trợ các tình huống xảy ra một lần trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Trực quan hóa quá trình cập nhật niềm tin bằng diện tích, giúp hình dung rõ xác suất theo nghĩa độ hợp lý (plausibility).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao dự báo “70% khả năng mưa ngày mai” là ví dụ tự nhiên cho cách hiểu Bayes về xác suất?&lt;/li&gt;
  &lt;li&gt;Trong bài toán đồng xu 8/10 mặt ngửa, điểm khác biệt quan trọng nhất giữa Frequentist và Bayesian là gì?&lt;/li&gt;
  &lt;li&gt;Hãy nêu một ví dụ trong công việc hoặc đời sống mà cách hiểu xác suất như độ hợp lý hữu ích hơn cách hiểu tần suất.&lt;/li&gt;
  &lt;li&gt;Vì sao thống kê Bayes vẫn giữ được tính kỷ luật logic dù cho phép đưa niềm tin ban đầu vào mô hình?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Jaynes, E. T. &lt;em&gt;Probability Theory: The Logic of Science&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 1.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 1.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter01/01_03_bayes_theorem_posterior/&quot;&gt;1.3 Định lý Bayes - Công cụ Cập nhật Niềm tin&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 1.1: Khủng hoảng Khoa học và Giới hạn của P-values</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_01_replication_crisis_pvalues/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter01/01_01_replication_crisis_pvalues</id>
   <content type="html">&lt;p&gt;Năm 2015, dự án &lt;em&gt;Open Science Collaboration&lt;/em&gt; công bố kết quả gây chấn động cộng đồng khoa học trên tạp chí &lt;em&gt;Science&lt;/em&gt;: khi 270 nhà nghiên cứu lặp lại cẩn thận 100 thí nghiệm tâm lý học từng đăng trên các tạp chí hàng đầu, chưa đầy 40% tái lập được kết quả có ý nghĩa thống kê. Trước đó một thập kỷ, John Ioannidis đã cảnh báo trong bài báo nổi tiếng &lt;em&gt;“Why Most Published Research Findings Are False”&lt;/em&gt; (2005) rằng sự kết hợp giữa ngưỡng cứng \(p &amp;lt; 0.05\), mẫu nhỏ và thiên lệch công bố đang sản sinh hàng loạt phát hiện giả.&lt;/p&gt;

&lt;p&gt;Bài học này mở đầu Chương 1 bằng cách mổ xẻ đúng căn nguyên toán học của cuộc khủng hoảng đó — không phải để bài bác công cụ tần suất một cách cảm tính, mà để thấy rõ câu hỏi cốt lõi nào mà \(p\)-value vốn không được thiết kế để trả lời.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn cần nắm được ba nội dung chính. Thứ nhất, vì sao nhiều nghiên cứu đã công bố lại không thể tái lập kết quả. Thứ hai, vì sao p-value thường bị hiểu sai và dễ bị lạm dụng. Thứ ba, vì sao những vấn đề đó thúc đẩy cộng đồng khoa học tìm đến các phương pháp suy luận khác, trong đó có thống kê Bayes.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ví dụ mini.&lt;/strong&gt; Một nghiên cứu báo cáo p-value &amp;lt; 0.05 cho thấy thuốc mới có hiệu quả, nhưng khi nhóm nghiên cứu khác lặp lại đúng thiết kế thí nghiệm thì không còn quan sát thấy hiệu quả đó nữa. Đây là dạng tình huống điển hình dẫn đến khủng hoảng tái lập.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Câu hỏi tự kiểm tra.&lt;/strong&gt; Một p-value nhỏ có thực sự đồng nghĩa với việc giả thuyết nghiên cứu là đúng không?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-kiểm-định-giả-thuyết-dương-tính-giả-và-khủng-hoảng-tái-lập&quot;&gt;Kiến thức cần nhớ: Kiểm định giả thuyết, Dương tính giả và Khủng hoảng tái lập&lt;/h2&gt;

&lt;p&gt;Để hiểu sâu cơ chế toán học đứng sau khủng hoảng tái lập, cần liên kết ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm định giả thuyết không (NHST &amp;amp; p-value):&lt;/strong&gt; \(p\)-value là xác suất có điều kiện \(P(\text{dữ liệu cực đoan như thế này hoặc hơn} \mid H_0)\). Nó giả định trước rằng giả thuyết không \(H_0\) đúng, hoàn toàn không phải xác suất \(P(H_0 \mid \text{dữ liệu})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lực kiểm định và Tỷ lệ nền (Power &amp;amp; Base Rate):&lt;/strong&gt; Xác suất một kết quả có \(p &amp;lt; 0.05\) thực sự là phát hiện thật phụ thuộc mạnh vào hai yếu tố thường bị bỏ quên: tỷ lệ giả thuyết thật trong lĩnh vực đó (prior \(P(H_1)\)) và lực kiểm định (\(1 - \beta\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Thống kê Bayes:&lt;/strong&gt; Thống kê Bayes đặt trực tiếp câu hỏi mà nhà khoa học thực sự muốn biết — \(P(H_1 \mid \text{dữ liệu})\) và phân phối hậu nghiệm của độ lớn hiệu ứng — đồng thời miễn nhiễm với lỗi dừng thu thập tùy ý (&lt;em&gt;optional stopping&lt;/em&gt;) nhờ nguyên lý hợp lý (&lt;em&gt;likelihood principle&lt;/em&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-khủng-hoảng-tái-lập-là-gì&quot;&gt;1. Khủng hoảng tái lập là gì?&lt;/h2&gt;

&lt;p&gt;Trong khoa học, một kết quả đáng tin cậy không chỉ cần có số liệu “đẹp” trên một bài báo, mà còn phải &lt;strong&gt;lặp lại được&lt;/strong&gt; khi nhóm nghiên cứu khác tiến hành lại thí nghiệm theo quy trình tương tự. Tuy nhiên, trong nhiều lĩnh vực như tâm lý học, y học tiền lâm sàng hay khoa học xã hội, không ít kết quả nổi bật đã không thể tái lập.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/replication_crisis_stats.png&quot; alt=&quot;Thống kê khủng hoảng tái lập&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Điều này không có nghĩa là phần lớn các nhà khoa học đều gian lận. Nguyên nhân chủ yếu nằm ở việc dữ liệu thường chứa nhiều nhiễu, cỡ mẫu hay bị giới hạn, trong khi hệ thống công bố lại ưu ái mạnh mẽ những kết quả đạt nhãn “có ý nghĩa thống kê”.&lt;/p&gt;

&lt;h2 id=&quot;2-cơ-chế-phía-sau-khủng-hoảng-tái-lập&quot;&gt;2. Cơ chế phía sau khủng hoảng tái lập&lt;/h2&gt;

&lt;p&gt;Hãy tưởng tượng 20 nhóm nghiên cứu độc lập cùng kiểm tra một giả thuyết mà thực chất là sai. Nếu mỗi nhóm sử dụng ngưỡng \(p &amp;lt; 0.05\), thì chỉ riêng do biến động ngẫu nhiên, ta vẫn kỳ vọng có khoảng 1 nhóm thu được “kết quả có ý nghĩa thống kê”. Nếu đúng nhóm thu được kết quả “đẹp” ấy được đăng báo còn 19 nhóm còn lại không công bố, thì kho tài liệu khoa học sẽ trông như thể giả thuyết đó đã được củng cố. Đây là một trong những cơ chế đáng lo ngại nhất đằng sau khủng hoảng tái lập.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-20-phòng-lab--ngăn-kéo-hồ-sơ-file-drawer-problem&quot;&gt;Video ngắn: 20 Phòng Lab &amp;amp; Ngăn kéo Hồ sơ (File Drawer Problem)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-01a-file-drawer-phacking.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 19 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): mô phỏng 20 phòng lab kiểm định một giả thuyết hoàn toàn sai với α = 0.05: 19 kết quả âm tính bị giấu vào ngăn kéo, chỉ 1 dương tính giả (p = 0.031) được đăng báo.&lt;/p&gt;

&lt;h2 id=&quot;3-p-value-thực-chất-là-gì&quot;&gt;3. P-value thực chất là gì?&lt;/h2&gt;

&lt;p&gt;Định nghĩa chuẩn của p-value như sau:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;P-value là xác suất quan sát được dữ liệu cực đoan ngang bằng hoặc hơn dữ liệu đang có, với giả định giả thuyết không \(H_0\) là đúng.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Nói gọn hơn, p-value trả lời câu hỏi: &lt;strong&gt;nếu giả thuyết không \(H_0\) là đúng, thì dữ liệu quan sát được có bất thường không?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ví dụ, nếu \(H_0\) phát biểu rằng thuốc không có hiệu quả, còn dữ liệu cho thấy nhóm dùng thuốc cải thiện nhiều hơn nhóm đối chứng, thì một p-value nhỏ chỉ có nghĩa là dữ liệu này khá bất thường nếu giả thuyết không thực sự đúng. Vấn đề nảy sinh ở chỗ đó &lt;strong&gt;không phải&lt;/strong&gt; câu hỏi mà nhà nghiên cứu thực sự muốn trả lời. Nhà nghiên cứu thường muốn biết giả thuyết có khả năng đúng đến đâu, bằng chứng mạnh mức nào, hiệu ứng lớn hay nhỏ, và kết quả đáng tin tới đâu — những câu hỏi mà p-value không trả lời trực tiếp.&lt;/p&gt;

&lt;h2 id=&quot;4-cách-đọc-p-value-cho-đúng&quot;&gt;4. Cách đọc p-value cho đúng&lt;/h2&gt;

&lt;p&gt;Giả sử một thử nghiệm cho \(p = 0.03\). Con số này &lt;strong&gt;không&lt;/strong&gt; có nghĩa là “xác suất giả thuyết không đúng là 3%”, và cũng không có nghĩa là “xác suất thuốc có hiệu quả là 97%”. Nó chỉ có nghĩa là nếu thuốc thực sự không có hiệu quả, thì xác suất quan sát được dữ liệu này hoặc cực đoan hơn chỉ vào khoảng 3%. Sự khác biệt nghe có vẻ tinh tế, nhưng thực chất là một khoảng cách lớn về mặt logic.&lt;/p&gt;

&lt;h2 id=&quot;5-những-hiểu-lầm-phổ-biến-nhất-về-p-value&quot;&gt;5. Những hiểu lầm phổ biến nhất về p-value&lt;/h2&gt;

&lt;p&gt;Dưới đây là những hiểu lầm rất thường gặp, kể cả trong các bài báo khoa học.&lt;/p&gt;

&lt;h3 id=&quot;hiểu-lầm-1-p-value-là-xác-suất-giả-thuyết-không-đúng&quot;&gt;Hiểu lầm 1. P-value là xác suất giả thuyết không đúng&lt;/h3&gt;

&lt;p&gt;Sai. P-value là:&lt;/p&gt;

\[P(\text{dữ liệu hoặc cực đoan hơn} \mid H_0),\]

&lt;p&gt;không phải:&lt;/p&gt;

\[P(H_0 \mid \text{dữ liệu}).\]

&lt;h3 id=&quot;hiểu-lầm-2-p-value-nhỏ-nghĩa-là-hiệu-ứng-lớn&quot;&gt;Hiểu lầm 2. P-value nhỏ nghĩa là hiệu ứng lớn&lt;/h3&gt;

&lt;p&gt;Sai. P-value phụ thuộc mạnh vào cỡ mẫu: khi cỡ mẫu rất lớn, một hiệu ứng rất nhỏ vẫn có thể tạo ra p-value nhỏ; ngược lại, khi cỡ mẫu nhỏ, một hiệu ứng tương đối lớn vẫn có thể chưa đủ để vượt qua ngưỡng 0.05.&lt;/p&gt;

&lt;h4 id=&quot;video-ngắn-bẫy-cỡ-mẫu-khổng-lồ-hiệu-ứng-tí-hon-nhưng-vẫn-ra-p--005&quot;&gt;Video ngắn: Bẫy Cỡ mẫu Khổng lồ: Hiệu ứng tí hon nhưng vẫn ra p &amp;lt; 0.05!&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-01c-pvalue-sample-size-trap.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 23 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): trượt cỡ mẫu n từ 50 → 12.000 cho một hiệu ứng rất nhỏ (+1%): đường cong chuẩn co hẹp dần kéo p-value từ 0.89 xuống 0.028 dù tác động thực tế không đổi.&lt;/p&gt;

&lt;h3 id=&quot;hiểu-lầm-3-p-value--005-nghĩa-là-không-có-hiệu-ứng&quot;&gt;Hiểu lầm 3. P-value &amp;gt; 0.05 nghĩa là không có hiệu ứng&lt;/h3&gt;

&lt;p&gt;Sai. Kết quả này có thể chỉ phản ánh rằng dữ liệu hiện có chưa đủ mạnh để phát hiện hiệu ứng.&lt;/p&gt;

&lt;h3 id=&quot;hiểu-lầm-4-0049-và-0051-khác-nhau-về-bản-chất&quot;&gt;Hiểu lầm 4. 0.049 và 0.051 khác nhau về bản chất&lt;/h3&gt;

&lt;p&gt;Thực tế hai giá trị này gần như không khác nhau. Tuy nhiên, khi biến ngưỡng 0.05 thành một ranh giới đỗ/trượt cứng nhắc, người ta thường diễn giải chúng như hai kết quả đối lập hoàn toàn.&lt;/p&gt;

&lt;h2 id=&quot;6-vì-sao-p-value-dễ-bị-lạm-dụng&quot;&gt;6. Vì sao p-value dễ bị lạm dụng?&lt;/h2&gt;

&lt;p&gt;Khi hệ thống công bố chỉ ưu tiên kết quả “có ý nghĩa thống kê”, người nghiên cứu dễ bị cuốn vào những thao tác linh hoạt quá mức như thử nhiều biến đầu ra khác nhau, thử nhiều cách lọc dữ liệu, loại bỏ ngoại lai (outlier) có chọn lọc, dừng thu thập dữ liệu ngay khi vừa chạm ngưỡng, hoặc chỉ báo cáo phân tích cho kết quả đẹp nhất. Những hành vi này không phải lúc nào cũng xuất phát từ ý định gian lận; nhiều khi chúng bắt nguồn từ áp lực công bố và tâm lý cho rằng mình chỉ đang “khám phá dữ liệu”. Tuy vậy, hậu quả vẫn giống nhau: tỷ lệ phát hiện giả (false positive) tăng mạnh.&lt;/p&gt;

&lt;h2 id=&quot;7-dừng-thu-thập-tùy-ý-optional-stopping-một-ví-dụ-dễ-gặp&quot;&gt;7. Dừng thu thập tùy ý (Optional stopping): một ví dụ dễ gặp&lt;/h2&gt;

&lt;p&gt;Giả sử bạn bắt đầu với 20 người tham gia và chưa thấy p-value đủ nhỏ. Bạn tuyển thêm 10 người, rồi thêm 10 người nữa, cho đến khi \(p &amp;lt; 0.05\) thì dừng lại. Thao tác này nghe có vẻ vô hại, nhưng nó âm thầm làm tăng xác suất thu được “kết quả có ý nghĩa thống kê” hoàn toàn do ngẫu nhiên. Trong thống kê Bayes, việc cập nhật tuần tự diễn ra tự nhiên hơn nhiều, còn trong kiểm định tần suất cổ điển, việc quyết định dừng dựa trên dữ liệu đang quan sát sẽ phá vỡ ý nghĩa ban đầu của p-value.&lt;/p&gt;

&lt;h3 id=&quot;71-một-ví-dụ-bằng-con-số-nhìn-dữ-liệu-cho-tới-khi-p--005&quot;&gt;7.1. Một ví dụ bằng con số: nhìn dữ liệu cho tới khi p &amp;lt; 0.05&lt;/h3&gt;

&lt;p&gt;Giả sử một nghiên cứu bắt đầu với 20 người tham gia và thu được \(p=0.18\). Chưa hài lòng, người nghiên cứu tuyển thêm 10 người và thấy \(p=0.09\). Vẫn chưa đạt ngưỡng, họ tuyển thêm 10 người nữa, thấy \(p=0.047\), liền dừng ngay và công bố kết quả có ý nghĩa thống kê.&lt;/p&gt;

&lt;p&gt;Vấn đề không nằm ở riêng con số \(0.047\), mà ở chỗ quy tắc dừng đã phụ thuộc vào chính dữ liệu đang quan sát. Nếu kế hoạch ban đầu là thu đủ 60 người rồi mới kiểm định, p-value cuối cùng hoàn toàn có thể quay lại một mức như \(0.11\). Do đó, optional stopping làm tăng cơ hội “vừa kịp” chạm ngưỡng, ngay cả khi hiệu ứng thực rất yếu hoặc không tồn tại.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-bẫy-dừng-thu-thập-tùy-ý-optional-stopping&quot;&gt;Video ngắn: Bẫy Dừng Thu thập Tùy ý (Optional Stopping)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-01b-optional-stopping-trap.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 21 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): quỹ đạo p-value của một đồng xu 100% cân bằng chạm ngưỡng p &amp;lt; 0.05 do ngẫu nhiên rồi bật ngược trở lại, giải thích vì sao nhìn dữ liệu liên tục đẩy dương tính giả lên trên 25%.&lt;/p&gt;

&lt;h2 id=&quot;8-thiên-lệch-công-bố-publication-bias-điều-làm-méo-bức-tranh-khoa-học&quot;&gt;8. Thiên lệch công bố (Publication bias): điều làm méo bức tranh khoa học&lt;/h2&gt;

&lt;p&gt;Ngay cả khi từng nghiên cứu riêng lẻ đều được thực hiện đúng quy trình, bức tranh khoa học vẫn có thể bị sai lệch nếu các kết quả “dương tính” được công bố còn các kết quả “âm tính” bị xếp lại trong ngăn kéo. Khi đó, người đọc chỉ nhìn thấy các nghiên cứu “thành công” và dễ đánh giá quá cao độ mạnh của bằng chứng dành cho một giả thuyết. Đây là lý do ta không nên đánh giá một phát hiện khoa học chỉ dựa trên một bài báo đơn lẻ.&lt;/p&gt;

&lt;h2 id=&quot;9-ví-dụ-nổi-tiếng-ngoại-cảm-và-những-tuyên-bố-phi-thường&quot;&gt;9. Ví dụ nổi tiếng: ngoại cảm và những tuyên bố phi thường&lt;/h2&gt;

&lt;p&gt;Một ví dụ thường được nhắc đến là các nghiên cứu tuyên bố tìm thấy bằng chứng về ngoại cảm. Nếu chỉ nhìn vào p-value, một vài kết quả có vẻ “đáng chú ý”. Tuy nhiên, trực giác khoa học cho thấy một tuyên bố càng phi thường thì càng đòi hỏi bằng chứng mạnh hơn rất nhiều.&lt;/p&gt;

&lt;p&gt;P-value không phân biệt được một giả thuyết quen thuộc như “aspirin giúp giảm đau đầu” với một tuyên bố phi thường như “con người nhìn thấy tương lai”; nó chỉ đo mức độ bất thường của dữ liệu dưới giả thuyết không. Phân tích Bayes khác ở chỗ cho phép đưa &lt;strong&gt;mức độ hợp lý ban đầu (prior plausibility)&lt;/strong&gt; vào mô hình: một giả thuyết khó tin ngay từ đầu sẽ cần bằng chứng mạnh hơn nhiều để xác suất hậu nghiệm trở nên thuyết phục.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_vs_posterior_frequentist.png&quot; alt=&quot;Cách nhìn Frequentist: p-value đo độ lạ của dữ liệu&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_vs_posterior_bayesian.png&quot; alt=&quot;Cách nhìn Bayesian: posterior nói trực tiếp về xác suất điều ta quan tâm&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-thí-nghiệm-ngoại-cảm-bem-2011-cùng-p--001-nhưng-hai-kết-luận&quot;&gt;Video ngắn: Thí nghiệm Ngoại cảm (Bem, 2011): Cùng p = 0.01 nhưng Hai Kết luận!&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch01-01d-extraordinary-claims-esp.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 16 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): áp cùng một bằng chứng (Bayes Factor ×10) cho thuốc cải tiến (Prior 50% → 90.9%) và năng lực ngoại cảm ESP (Prior 0.1% → chỉ 0.99%).&lt;/p&gt;

&lt;h2 id=&quot;10-vấn-đề-cốt-lõi-p-value-trả-lời-sai-câu-hỏi&quot;&gt;10. Vấn đề cốt lõi: p-value trả lời sai câu hỏi&lt;/h2&gt;

&lt;p&gt;Đây là điểm quan trọng nhất của bài học. Nhà khoa học thường muốn biết giả thuyết nào đáng tin hơn, tham số có thể nằm trong khoảng nào, dữ liệu ủng hộ giả thuyết mạnh đến mức nào, và độ bất định còn lại là bao nhiêu. Trong khi đó, p-value lại trả lời một câu hỏi khác: nếu giả thuyết không \(H_0\) đúng thì dữ liệu này bất thường đến đâu. Nó có thể hữu ích trong một số bối cảnh kiểm định nhất định, nhưng không phải câu trả lời trực tiếp cho mối quan tâm khoa học cốt lõi.&lt;/p&gt;

&lt;h2 id=&quot;11-vì-sao-bài-này-mở-đường-cho-thống-kê-bayes&quot;&gt;11. Vì sao bài này mở đường cho thống kê Bayes?&lt;/h2&gt;

&lt;p&gt;Thống kê Bayes hấp dẫn không phải vì phủ nhận p-value, mà vì hướng đến việc trả lời trực tiếp hơn những câu hỏi ta thực sự quan tâm: xác suất của giả thuyết sau khi quan sát dữ liệu, phân phối của tham số chưa biết, mức độ bất định hiện tại và cách cập nhật niềm tin khi có thông tin mới. Bài học này đóng vai trò khởi động cho Chương 1 bằng cách chỉ ra vì sao nhiều nhà nghiên cứu cảm thấy cách suy luận truyền thống là chưa đủ.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 ý cần nhớ.&lt;/strong&gt; Khủng hoảng tái lập không chỉ là lỗi cá nhân của từng nhà nghiên cứu mà còn là vấn đề của cả hệ thống suy luận và cơ chế khuyến khích công bố; p-value dễ bị hiểu sai vì nó trả lời một câu hỏi khác với câu hỏi khoa học cốt lõi; và khi p-value trở thành mục tiêu phải đạt, p-hacking cùng thiên lệch công bố gần như chắc chắn sẽ xuất hiện.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;giải-thích-tại-sao-p--005-không-có-nghĩa-là-xác-suất-sai-chỉ-5&quot;&gt;Giải thích: Tại sao \(p &amp;lt; 0.05\) không có nghĩa là xác suất sai chỉ 5%?&lt;/h2&gt;

&lt;p&gt;Hãy đọc chậm bốn bước sau để giải mã nghịch lý lớn nhất của kiểm định thống kê truyền thống:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phân biệt hai xác suất đảo ngược:&lt;/strong&gt; \(p &amp;lt; 0.05\) kiểm soát \(P(\text{bác bỏ } H_0 \mid H_0 \text{ đúng}) = \alpha = 0.05\), chứ không kiểm soát tỷ lệ phát hiện giả \(P(H_0 \text{ đúng} \mid \text{bác bỏ } H_0)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đưa tỷ lệ giả thuyết thật (Base rate) vào phương trình:&lt;/strong&gt; Trong nghiên cứu khám phá, phần lớn các giả thuyết ban đầu là không có hiệu ứng (ví dụ chỉ 10% giả thuyết là thật).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính cả lực kiểm định (Power = \(1 - \beta\)):&lt;/strong&gt; Với cỡ mẫu nhỏ, ngay cả khi hiệu ứng có thật, xác suất phát hiện ra nó có thể chỉ đạt 50%–80%.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp dụng định lý Bayes cho 1.000 nghiên cứu:&lt;/strong&gt; So sánh số ca dương tính thật và dương tính giả để thấy tỷ lệ phát hiện giả thực sự cao đến mức nào.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-1000-thí-nghiệm-với-ngưỡng-alpha--005&quot;&gt;Ví dụ tính toán làm từng bước: 1.000 thí nghiệm với ngưỡng \(\alpha = 0.05\)&lt;/h3&gt;

&lt;p&gt;Giả sử trong một lĩnh vực khám phá mới, có 1.000 giả thuyết được kiểm định độc lập với tỷ lệ giả thuyết thật là \(10\%\) (\(100\) giả thuyết thật, \(900\) giả thuyết sai), ngưỡng ý nghĩa \(\alpha = 0.05\) và lực kiểm định \(1 - \beta = 0.80\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Trạng thái thật&lt;/th&gt;
      &lt;th&gt;Số thí nghiệm&lt;/th&gt;
      &lt;th&gt;Kết quả \(p &amp;lt; 0.05\) (có ý nghĩa)&lt;/th&gt;
      &lt;th&gt;Kết quả \(p \ge 0.05\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Có hiệu ứng thật (\(H_1\))&lt;/td&gt;
      &lt;td&gt;\(100\)&lt;/td&gt;
      &lt;td&gt;\(100 \times 0.80 = 80\) (dương tính thật)&lt;/td&gt;
      &lt;td&gt;\(20\) (âm tính giả)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Không có hiệu ứng (\(H_0\))&lt;/td&gt;
      &lt;td&gt;\(900\)&lt;/td&gt;
      &lt;td&gt;\(900 \times 0.05 = 45\) (dương tính giả)&lt;/td&gt;
      &lt;td&gt;\(855\) (âm tính thật)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Tổng cộng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(1\,000\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(80 + 45 = 125\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(875\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Trong \(125\) bài báo đạt ngưỡng \(p &amp;lt; 0.05\) và được xuất bản, tỷ lệ phát hiện giả (False Discovery Rate) là:&lt;/p&gt;

\[P(H_0 \mid p &amp;lt; 0.05) = \frac{45}{125} = 0.36 \quad (36\%!).\]

&lt;p&gt;Dù mỗi thí nghiệm đều tuân thủ nghiêm ngặt \(\alpha = 0.05\) và không hề gian lận, hơn &lt;strong&gt;một phần ba&lt;/strong&gt; các kết quả “có ý nghĩa thống kê” vẫn là sai lệch ngẫu nhiên!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nghĩ rằng \(p = 0.04\) đồng nghĩa với “chỉ có 4% khả năng giả thuyết không đúng”. Khi tỷ lệ nền thấp hoặc cỡ mẫu nhỏ, xác suất giả thuyết không đúng có thể lên tới 30%–50%.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu cỡ mẫu nhỏ hơn khiến lực kiểm định giảm xuống còn \(0.20\) (các thông số khác giữ nguyên), số dương tính thật chỉ còn \(100 \times 0.20 = 20\), còn dương tính giả vẫn là \(45\) — khi đó tỷ lệ phát hiện giả vọt lên \(45 / (20 + 45) \approx 69.2\%\)!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vemZtEM63GY&quot;&gt;p-values: What they are and how to interpret them&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Giải thích câu hỏi thực sự mà p-value trả lời, bổ trợ cho phần chỉ ra các hiểu lầm thường gặp trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HDCOUXE3HMM&quot;&gt;p-hacking: What it is and how to avoid it!&lt;/a&gt; — StatQuest with Josh Starmer, English. Phân tích cách p-hacking nảy sinh từ những lựa chọn phân tích linh hoạt quá mức, làm rõ vì sao nhiều kết quả không thể tái lập.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[The reproducibility crisis and other problems in science&lt;/td&gt;
          &lt;td&gt;John Ioannidis](https://www.youtube.com/watch?v=vY9mGJQFdyE) — The Institute of Art and Ideas, English. Bài nói chuyện của John Ioannidis về khủng hoảng tái lập, kết nối việc lạm dụng kiểm định với độ tin cậy của các công bố khoa học.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao một nghiên cứu có p-value nhỏ vẫn có thể không tái lập được?&lt;/li&gt;
  &lt;li&gt;Hãy giải thích bằng lời sự khác nhau giữa \(P(\text{dữ liệu} \mid H_0)\) và \(P(H_0 \mid \text{dữ liệu})\).&lt;/li&gt;
  &lt;li&gt;Vì sao cỡ mẫu lớn có thể làm một hiệu ứng nhỏ nhưng không có ý nghĩa thực tế vẫn cho p-value rất nhỏ?&lt;/li&gt;
  &lt;li&gt;Hãy nêu một ví dụ đời thường về thiên lệch công bố (publication bias) ngoài lĩnh vực khoa học.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 1.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 11.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 1.&lt;/li&gt;
  &lt;li&gt;Wasserstein, R. L., &amp;amp; Lazar, N. A. (2016). The ASA Statement on p-Values.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter01/01_02_probability_as_plausibility/&quot;&gt;1.2 Xác suất như Độ tin cậy - Quan điểm Bayes&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.21: Mô phỏng để kiểm tra trực giác thống kê</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_19_simulation_for_statistical_intuition/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_19_simulation_for_statistical_intuition</id>
   <content type="html">&lt;p&gt;Năm 1946, khi nằm dưỡng bệnh và chơi trò xếp bài Solitaire, nhà toán học Stanislaw Ulam nảy ra một ý tưởng làm thay đổi toàn bộ khoa học tính toán: thay vì cố giải bài toán tổ hợp cực khó bằng công thức đóng, tại sao không chơi thử hàng trăm ván trên máy tính rồi đếm tỷ lệ thắng? Cùng với John von Neumann, ông gọi kỹ thuật đó là &lt;strong&gt;phương pháp Monte Carlo&lt;/strong&gt; — đặt theo sòng bạc nổi tiếng ở Monaco.&lt;/p&gt;

&lt;p&gt;Đối với người học thống kê Bayes, mô phỏng không chỉ là công cụ kiểm chứng bài tập mà là &lt;strong&gt;phòng thí nghiệm tư duy&lt;/strong&gt;: bất cứ khi nào một công thức trông mờ ảo hoặc một mô hình phức tạp khó đoán hành vi, bạn luôn có thể sinh dữ liệu giả lập với tham số đã biết để nhìn tận mắt điều gì xảy ra.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ sử dụng mô phỏng như một công cụ suy luận thực thụ chứ không chỉ để minh họa, biết dùng mô phỏng để kiểm chứng công thức, phát hiện các điểm mù trực giác, và chuẩn bị nền tảng cho quy trình làm việc Bayesian dựa trên cơ chế sinh dữ liệu (generative story).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-mô-hình-sinh-dữ-liệu-monte-carlo-và-kiểm-chứng-quy-trình-bayes&quot;&gt;Kiến thức cần nhớ: Mô hình sinh dữ liệu, Monte Carlo và Kiểm chứng quy trình Bayes&lt;/h2&gt;

&lt;p&gt;Mô phỏng kết nối ba trụ cột quan trọng của khoa học dữ liệu định lượng:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình sinh dữ liệu (Generative Modeling):&lt;/strong&gt; Muốn mô phỏng, bạn buộc phải viết rõ ràng từng bước dữ liệu được tạo ra như thế nào (từ tham số đến quan sát). Nếu viết được hàm sinh dữ liệu, bạn đã hiểu trọn vẹn cấu trúc xác suất của bài toán.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích phân Monte Carlo (Monte Carlo Integration):&lt;/strong&gt; Mọi xác suất \(P(A)\) hay kỳ vọng \(\mathbb{E}[g(X)]\) đều có thể xấp xỉ bằng tần suất thực nghiệm trên \(M\) lần mô phỏng độc lập, với sai số giảm theo \(1/\sqrt{M}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Thống kê Bayes (Prior &amp;amp; Posterior Predictive Checks):&lt;/strong&gt; Toàn bộ quy trình Bayes hiện đại xoay quanh mô phỏng: &lt;em&gt;Prior predictive simulation&lt;/em&gt; kiểm tra xem prior có sinh ra dữ liệu hợp lý không, &lt;em&gt;Simulation-Based Calibration (SBC)&lt;/em&gt; kiểm tra thuật toán suy diễn có khôi phục được tham số thật không, và &lt;em&gt;Posterior predictive simulation&lt;/em&gt; kiểm tra mô hình sau khi khớp có tái tạo được dữ liệu thực tế không.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-mô-phỏng-như-phòng-thí-nghiệm-của-suy-luận&quot;&gt;Giới thiệu: Mô phỏng như phòng thí nghiệm của suy luận&lt;/h2&gt;

&lt;p&gt;Trong nhiều bài toán xác suất, suy đoán bằng lời dễ dẫn tới kết luận sai, còn công thức giải tích đôi khi khó hình dung trong bối cảnh thực tế. Mô phỏng đóng vai trò như một “phòng thí nghiệm” trung gian: ta phát biểu rõ giả định, sinh dữ liệu theo giả định đó, rồi đối chiếu hệ quả với điều mình kỳ vọng. Cách làm này giúp gắn chặt mô hình lý thuyết với hành vi thực tế của dữ liệu.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/simulation_statistical_intuition_workflow.png&quot; alt=&quot;Quy trình mô phỏng thống kê&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1: Quy trình mô phỏng 4 bước: xác định giả định mô hình -&amp;gt; chọn tham số -&amp;gt; sinh dữ liệu lặp lại -&amp;gt; so sánh với kỳ vọng và cập nhật.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-vì-sao-cần-mô-phỏng&quot;&gt;1) Vì sao cần mô phỏng?&lt;/h2&gt;

&lt;p&gt;Nhiều bài toán thống kê dễ gây nhầm lẫn về trực giác: ta có thể hiểu sai xác suất có điều kiện, đánh giá thấp mức độ bất định, hoặc tin vào một kết quả bề ngoài hợp lý mà chưa kiểm tra cơ chế sinh dữ liệu phía sau. Mô phỏng cho phép quan sát trực tiếp hệ quả của từng giả định.&lt;/p&gt;

&lt;h2 id=&quot;2-quy-trình-mô-phỏng-4-bước&quot;&gt;2) Quy trình mô phỏng 4 bước&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Phát biểu rõ cơ chế sinh dữ liệu (generative story).&lt;/li&gt;
  &lt;li&gt;Chọn bộ tham số đầu vào hợp lý.&lt;/li&gt;
  &lt;li&gt;Sinh dữ liệu lặp lại nhiều lần.&lt;/li&gt;
  &lt;li&gt;Tóm tắt kết quả mô phỏng và đối chiếu với kỳ vọng lý thuyết.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Khi kết quả mô phỏng mâu thuẫn với dự đoán ban đầu (và mã mô phỏng không có lỗi), thường chính trực giác của ta cần được hiệu chỉnh.&lt;/p&gt;

&lt;h2 id=&quot;3-khi-nào-nên-mô-phỏng&quot;&gt;3) Khi nào nên mô phỏng?&lt;/h2&gt;

&lt;p&gt;Mô phỏng đặc biệt hữu ích khi công thức quá phức tạp để kiểm tra bằng tay, khi cần đánh giá độ nhạy của kết quả theo tham số, khi muốn trực quan hóa một khái niệm xác suất, hoặc khi cần kiểm tra nhanh (sanity check) cho mã nguồn suy luận Bayesian.&lt;/p&gt;

&lt;h2 id=&quot;4-ví-dụ-ngắn&quot;&gt;4) Ví dụ ngắn&lt;/h2&gt;

&lt;p&gt;Để thấy trực tiếp độ bất định của tỷ lệ mẫu \(\hat p\) khi cỡ mẫu nhỏ, ta có thể cố định giá trị thật \(p=0.2\), mô phỏng nhiều mẫu Binomial với \(n=20\) và \(n=200\), rồi so sánh mức dao động của \(\hat p\) giữa hai trường hợp. Kết quả sẽ cho thấy ngay vì sao cỡ mẫu nhỏ dao động mạnh và vì sao thông tin tiên nghiệm (prior) đóng vai trò lớn hơn khi dữ liệu còn ít.&lt;/p&gt;

&lt;h3 id=&quot;41-quan-sát-5-lần-mô-phỏng-cụ-thể&quot;&gt;4.1) Quan sát 5 lần mô phỏng cụ thể&lt;/h3&gt;

&lt;p&gt;Với cùng giá trị thật \(p=0.2\), năm lần mô phỏng điển hình có thể cho:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Khi \(n=20\): \(\hat p = 0.10, 0.15, 0.20, 0.30, 0.35\).&lt;/li&gt;
  &lt;li&gt;Khi \(n=200\): \(\hat p = 0.17, 0.19, 0.20, 0.22, 0.24\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cả hai dãy đều xoay quanh 0.2, nhưng nhóm \(n=20\) phân tán rộng hơn nhiều. Chỉ vài lần mô phỏng cũng đủ tạo trực giác rõ ràng về ảnh hưởng của cỡ mẫu đến độ ổn định của ước lượng.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-mô-phỏng-monte-carlo-từ-ulam-phòng-thí-nghiệm-trực-giác-xác-suất&quot;&gt;Video ngắn: Mô phỏng Monte Carlo từ Ulam: Phòng thí nghiệm Trực giác Xác suất&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-21a-ulam-monte-carlo.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): kiểm chứng Nghịch lý Sinh nhật (23 người vượt 50.7%), bài toán Monty Hall (đổi cửa thắng 66.7%), và dùng mô phỏng 10.000 lần làm máy dò lỗi công thức.&lt;/p&gt;

&lt;h2 id=&quot;5-liên-hệ-trực-tiếp-với-thống-kê-bayesian&quot;&gt;5) Liên hệ trực tiếp với thống kê Bayesian&lt;/h2&gt;

&lt;p&gt;Mô phỏng là “phòng thí nghiệm” cốt lõi của quy trình làm việc Bayesian (Bayesian workflow): nó cho phép thực hiện kiểm tra dự báo tiên nghiệm (prior predictive check), kiểm tra dự báo hậu nghiệm (posterior predictive check) và đánh giá độ ổn định của quyết định khi thay đổi giả định đầu vào. Nói gọn lại, mô phỏng rèn luyện tư duy “mô hình quy định dạng dữ liệu sinh ra” (model implies data).&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-kiểm-chứng-phục-hồi-tham-số-parameter-recovery--sbc&quot;&gt;Video ngắn: Kiểm chứng Phục hồi Tham số (Parameter Recovery) &amp;amp; SBC&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-21b-parameter-recovery.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): quy trình tạo dữ liệu từ tham số thật đã biết θ_true, chạy lại bộ suy luận để kiểm tra xem mô hình có phục hồi đúng θ_true trước khi dùng dữ liệu thật.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt-nhanh&quot;&gt;Tóm tắt nhanh&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Mô phỏng là công cụ kiểm chứng suy luận, không chỉ là hình minh họa.&lt;/li&gt;
  &lt;li&gt;Quy trình chuẩn gồm bốn bước: đặt giả định -&amp;gt; chọn tham số -&amp;gt; sinh dữ liệu lặp -&amp;gt; tóm tắt và đối chiếu.&lt;/li&gt;
  &lt;li&gt;Mô phỏng rất hữu ích để kiểm tra nhanh (sanity check) các mô hình Bayesian.&lt;/li&gt;
  &lt;li&gt;Khi trực giác mâu thuẫn với mô phỏng, hãy kiểm tra lại mã nguồn rồi xem lại chính giả định và trực giác ban đầu.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;giải-thích-bốn-bước-kiểm-chứng-trực-giác-bằng-mô-phỏng&quot;&gt;Giải thích: Bốn bước kiểm chứng trực giác bằng mô phỏng&lt;/h2&gt;

&lt;p&gt;Khi gặp một câu hỏi xác suất khó hoặc nghi ngờ một bộ ước lượng, hãy dùng quy trình mô phỏng 4 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cố định “chân lý ẩn” (Ground truth):&lt;/strong&gt; Tự chọn giá trị tham số thật biết trước (ví dụ \(\theta_{\text{true}} = 0.30\)) để có mốc đối chiếu tuyệt đối.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sinh \(M\) tập dữ liệu giả lập:&lt;/strong&gt; Dùng bộ sinh số ngẫu nhiên (cố định &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seed&lt;/code&gt; để tái lập) tạo ra \(M\) kịch bản độc lập theo đúng giả định mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp dụng đúng quy trình suy diễn lên từng kịch bản:&lt;/strong&gt; Tính thống kê quan tâm (trung bình mẫu, khoảng tin cậy, xác suất sự kiện).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đo sai số Monte Carlo:&lt;/strong&gt; Kiểm tra \(\mathrm{MCSE} = \sqrt{\hat p(1-\hat p)/M}\) để chắc chắn số lần mô phỏng \(M\) đủ lớn nhằm kết luận đáng tin cậy.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-đo-độ-chính-xác-ước-lượng-xác-suất-bằng-monte-carlo&quot;&gt;Ví dụ tính toán làm từng bước: Đo độ chính xác ước lượng xác suất bằng Monte Carlo&lt;/h3&gt;

&lt;p&gt;Giả sử bạn mô phỏng bài toán kiểm tra xem tổng của 2 viên xúc xắc công bằng có lớn hơn hoặc bằng 10 hay không (giá trị lý thuyết chính xác là \(p = 6/36 = 1/6 \approx 0.1667\)). Hãy theo dõi sai số chuẩn Monte Carlo \(\mathrm{MCSE} = \sqrt{p(1-p)/M}\) khi tăng số lần chạy \(M\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Số lần mô phỏng \(M\)&lt;/th&gt;
      &lt;th&gt;\(\mathrm{MCSE} = \sqrt{0.1667 \times 0.8333 / M}\)&lt;/th&gt;
      &lt;th&gt;Biên sai số 95% (\(\pm 1.96\,\mathrm{MCSE}\))&lt;/th&gt;
      &lt;th&gt;Mức độ tin cậy&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(M = 100\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{0.1389 / 100} \approx 0.0373\)&lt;/td&gt;
      &lt;td&gt;\(\pm 0.0731\)&lt;/td&gt;
      &lt;td&gt;Rất thô (dao động từ 9% đến 24%)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(M = 1\,000\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{0.1389 / 1000} \approx 0.0118\)&lt;/td&gt;
      &lt;td&gt;\(\pm 0.0231\)&lt;/td&gt;
      &lt;td&gt;Khá ổn để xem trực giác&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(M = 10\,000\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{0.1389 / 10000} \approx 0.0037\)&lt;/td&gt;
      &lt;td&gt;\(\pm 0.0073\)&lt;/td&gt;
      &lt;td&gt;Chính xác tới dưới 1 điểm phần trăm&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Chạy mô phỏng chỉ \(M = 50\) lần rồi kết luận thuật toán bị sai chỉ vì kết quả lệch vài phần trăm so với lý thuyết. Luôn tính nhanh \(\mathrm{MCSE}\) trước khi phán xét.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu bạn muốn ước lượng một xác suất quanh \(0.5\) với sai số chuẩn Monte Carlo nhỏ hơn \(0.005\), ta cần \(\sqrt{0.25/M} \le 0.005 \implies M \ge 0.25 / 0.000025 = 10\,000\) lần mô phỏng.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=7TqhmX92P6U&quot;&gt;What is Monte Carlo Simulation?&lt;/a&gt; — IBM Technology, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giải thích mô phỏng Monte Carlo như cách đặt giả định và sinh dữ liệu lặp lại để quan sát phân phối kết quả.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=MntX3zWNWec&quot;&gt;Law of Large Numbers - Explained and Visualized&lt;/a&gt; — Jeremy Blitz-Jones, English. Minh họa việc dùng mô phỏng để kiểm chứng trực quan một định lý xác suất.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zeJD6dqJ5lo&quot;&gt;But what is the Central Limit Theorem?&lt;/a&gt; — 3Blue1Brown, English. Cho thấy quy trình sinh nhiều mẫu lặp lại để quan sát phân phối của trung bình mẫu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Nêu một khái niệm xác suất mà bạn hay nhầm lẫn và thiết kế một thí nghiệm mô phỏng nhỏ để tự kiểm chứng.&lt;/li&gt;
  &lt;li&gt;Vì sao mô phỏng là cầu nối hiệu quả giữa công thức toán học và mã lập trình?&lt;/li&gt;
  &lt;li&gt;Khi kết quả mô phỏng khác xa kỳ vọng ban đầu, bạn nên kiểm tra những yếu tố nào trước tiên?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Downey, A. (2014). &lt;em&gt;Think Bayes&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;McElreath, R. (2020). &lt;em&gt;Statistical Rethinking&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter01/&quot;&gt;Chương 1: Cơ bản về Suy diễn Bayes&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.20: Kiểm tra giả định mô hình cơ bản</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_18_basic_model_assumption_checks/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_18_basic_model_assumption_checks</id>
   <content type="html">&lt;p&gt;Năm 1976, nhà thống kê George Box viết một câu nói trở thành kim chỉ nam cho mọi người làm dữ liệu: &lt;em&gt;“Mọi mô hình đều sai, nhưng một số mô hình hữu ích.”&lt;/em&gt; Câu nói đó không phải lời biện minh để bỏ qua kiểm tra giả định, mà ngược lại: vì mọi mô hình đều là bản đồ đơn giản hóa của thực tại, việc đầu tiên của nhà phân tích là kiểm tra xem bản đồ có đang sai ở đúng chỗ quyết định hay không.&lt;/p&gt;

&lt;p&gt;Trước khi đi vào các mô hình hồi quy hay MCMC phức tạp, bài học này trang bị cho bạn thói quen chẩn đoán có hệ thống: nhìn phần dư, phát hiện ngoại lai, kiểm tra phương sai thay đổi và tính độc lập để không bao giờ tin mù quáng vào một bảng kết quả đẹp mã.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ biết cách kiểm tra có hệ thống các giả định cốt lõi của mô hình (dạng phân phối, tính độc lập, cấu trúc sai số), nhận diện sớm dấu hiệu sai đặc tả mô hình (misspecification), và chuyển kết quả chẩn đoán thành bước cải tiến mô hình cụ thể.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-chẩn-đoán-giả-định-cơ-chế-sinh-dữ-liệu-và-phản-biện-mô-hình-bayes&quot;&gt;Kiến thức cần nhớ: Chẩn đoán giả định, Cơ chế sinh dữ liệu và Phản biện mô hình Bayes&lt;/h2&gt;

&lt;p&gt;Kiểm tra giả định không phải thủ tục hình thức mà là sự giao thoa của ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bốn giả định cốt lõi của mô hình tuyến tính (LINE):&lt;/strong&gt; Tuyến tính (&lt;em&gt;Linearity&lt;/em&gt;), Độc lập (&lt;em&gt;Independence&lt;/em&gt;), Phân phối phần dư (&lt;em&gt;Normality&lt;/em&gt;) và Phương sai đồng nhất (&lt;em&gt;Equal variance / Homoscedasticity&lt;/em&gt;). Mỗi giả định tương ứng với một bộ phận cụ thể trong phương trình sinh dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chẩn đoán bằng đồ thị và kiểm định (Residual &amp;amp; Influence Diagnostics):&lt;/strong&gt; Biểu đồ phần dư theo giá trị dự đoán, Q-Q plot và chỉ số đòn bẩy giúp nhìn thấy ngay cấu trúc bị bỏ sót mà các chỉ số tổng hợp như \(R^2\) thường che giấu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Quy trình Bayes (Bayesian Workflow):&lt;/strong&gt; Trong thống kê Bayes, khi phát hiện giả định bị vi phạm, ta không vội “xóa điểm dữ liệu cho đẹp”, mà chủ động nâng cấp mô hình sinh: thay Gaussian bằng Student-\(t\) khi có đuôi dày/ngoại lai, thêm thành phần phân cấp khi dữ liệu gom cụm, hoặc chuyển sang GLM (Poisson/Negative Binomial) cho dữ liệu đếm.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-giả-định-mô-hình-là-gì-và-nằm-ở-đâu&quot;&gt;1) Giả định mô hình là gì và nằm ở đâu?&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Mỗi mô hình thống kê đều ngầm giả định dữ liệu phát sinh từ một cơ chế nhất định, nhiễu mang một cấu trúc cụ thể, và mối liên hệ giữa biến đầu vào với biến đầu ra có một dạng hình học hoặc xác suất xác định.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Trong thực hành, giả định thường nằm ở ba lớp:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hàm hợp lý (likelihood)&lt;/strong&gt;: dữ liệu thuộc họ phân phối nào (Gaussian, Poisson, Binomial…).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cấu trúc trung bình (mean structure)&lt;/strong&gt;: mối quan hệ giữa \(x\) và kỳ vọng của \(y\) là tuyến tính, phi tuyến hay có tương tác.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cấu trúc nhiễu (noise structure)&lt;/strong&gt;: phương sai có đồng nhất hay thay đổi theo giá trị dự báo, và các quan sát có phụ thuộc theo thời gian hay theo nhóm không.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;2-bộ-kiểm-tra-tối-thiểu-nên-thực-hiện&quot;&gt;2) Bộ kiểm tra tối thiểu nên thực hiện&lt;/h2&gt;

&lt;h3 id=&quot;21-kiểm-tra-phân-phối-đầu-ra&quot;&gt;2.1 Kiểm tra phân phối đầu ra&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Vẽ histogram hoặc đường ước lượng mật độ của \(y\).&lt;/li&gt;
  &lt;li&gt;Đối chiếu hình dạng dữ liệu với hàm hợp lý dự định dùng.&lt;/li&gt;
  &lt;li&gt;Kiểm tra các đặc điểm nổi bật: dữ liệu có lệch mạnh, có nhiều giá trị 0, hay bị giới hạn miền (như đoạn \([0,1]\)) không?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Ví dụ, dữ liệu đếm chứa nhiều giá trị 0 thường không phù hợp với phân phối Gaussian; dữ liệu tỷ lệ trên \([0,1]\) cần mô hình tôn trọng miền giá trị thay vì dự báo vượt ngoài khoảng hợp lệ.&lt;/p&gt;

&lt;h3 id=&quot;22-kiểm-tra-phần-dư&quot;&gt;2.2 Kiểm tra phần dư&lt;/h3&gt;

&lt;p&gt;Phần dư (residual) được định nghĩa là:&lt;/p&gt;

\[e_i = y_i - \hat y_i\]

&lt;p&gt;Ở đây, \(e_i\) là chênh lệch giữa giá trị quan sát thật \(y_i\) và giá trị mô hình dự báo \(\hat y_i\): nếu \(e_i &amp;gt; 0\), mô hình dự báo thấp hơn thực tế; nếu \(e_i &amp;lt; 0\), mô hình dự báo cao hơn thực tế.&lt;/p&gt;

&lt;p&gt;Cần phân biệt rõ \(e_i\) và \(\epsilon_i\). Trong mô hình sinh dữ liệu \(y_i = \mu_i + \epsilon_i\), \(\epsilon_i\) là &lt;strong&gt;sai số thật không quan sát trực tiếp được&lt;/strong&gt;, còn \(e_i = y_i - \hat y_i\) là &lt;strong&gt;phần dư tính sau khi khớp mô hình&lt;/strong&gt;, đóng vai trò công cụ chẩn đoán thực hành. Khi mô hình phù hợp, hành vi của \(e_i\) gần với \(\epsilon_i\), nhưng hai đại lượng này không hoàn toàn trùng nhau vì \(\hat y_i\) được ước lượng từ chính dữ liệu.&lt;/p&gt;

&lt;p&gt;Với một mô hình tạm ổn, phần dư cần dao động quanh 0, không thể hiện xu hướng có hệ thống theo \(\hat y\) hay \(x\), và không lộ ra cấu trúc rõ rệt như đường cong, hình phễu hay các cụm tách biệt theo nhóm.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_residual_check.png&quot; alt=&quot;Residual check để nhìn xu hướng phần dư&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1a: Biểu đồ phần dư (residual plot) giúp kiểm tra nhanh xem phần dư có dao động quanh 0 hay đang lộ ra cấu trúc bất thường.&lt;/em&gt;&lt;/p&gt;

&lt;h4 id=&quot;video-ngắn-chẩn-đoán-phần-dư-residual-diagnostics-phát-hiện-lỗi-mô-hình-bằng-mắt&quot;&gt;Video ngắn: Chẩn đoán Phần dư (Residual Diagnostics): Phát hiện lỗi mô hình bằng mắt&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-20a-residual-diagnostics.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): đọc biểu đồ phần dư phát hiện phi tuyến, phương sai thay đổi (hình phễu), tự tương quan chuỗi thời gian và điểm ngoại lai.&lt;/p&gt;

&lt;h3 id=&quot;23-kiểm-tra-giá-trị-ngoại-lai-và-điểm-ảnh-hưởng-mạnh&quot;&gt;2.3 Kiểm tra giá trị ngoại lai và điểm ảnh hưởng mạnh&lt;/h3&gt;

&lt;p&gt;Không phải giá trị ngoại lai (outlier) nào cũng là dữ liệu “hỏng”. Chúng có thể là lỗi nhập liệu, trường hợp hiếm nhưng hợp lệ, hoặc tín hiệu cho thấy mô hình đang thiếu biến giải thích hay chọn sai hàm hợp lý. Bước quan trọng là kiểm tra độ nhạy: khi loại bỏ hoặc giảm trọng số một vài điểm ảnh hưởng mạnh, kết luận có thay đổi đáng kể không?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_fit_outliers.png&quot; alt=&quot;Fit tuyến tính và các điểm có thể là outlier&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1b: Quan sát đường khớp cùng các điểm nằm xa xu hướng chung giúp phát hiện giá trị ngoại lai và điểm ảnh hưởng mạnh trước khi chỉnh sửa mô hình.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;24-kiểm-tra-giả-định-độc-lập&quot;&gt;2.4 Kiểm tra giả định độc lập&lt;/h3&gt;

&lt;p&gt;Giả định độc lập rất dễ bị vi phạm trong dữ liệu thực, phổ biến nhất ở ba dạng: phụ thuộc theo &lt;strong&gt;thời gian&lt;/strong&gt; (tự tương quan), theo &lt;strong&gt;nhóm&lt;/strong&gt; (như học sinh cùng lớp hoặc bệnh nhân cùng bệnh viện), và theo &lt;strong&gt;không gian&lt;/strong&gt; (các điểm đo gần nhau thường tương đồng hơn). Nếu bỏ qua sự phụ thuộc này, khoảng bất định ước lượng thường bị thu hẹp quá mức lạc quan.&lt;/p&gt;

&lt;h2 id=&quot;3-bản-đồ-dấu-hiệu---hành-động&quot;&gt;3) Bản đồ “dấu hiệu -&amp;gt; hành động”&lt;/h2&gt;

&lt;p&gt;Đây không phải quy tắc máy móc “thấy A thì bắt buộc dùng B”, mà là trình tự suy luận: quan sát dấu hiệu từ dữ liệu hoặc phần dư, xác định giả định đang bị nghi ngờ, rồi thử điều chỉnh nhỏ nhất nhưng trúng trọng tâm:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phần dư có dạng đường cong&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nghi ngờ: cấu trúc trung bình (mean structure) chưa phù hợp — quan hệ giữa biến đầu vào và đầu ra không còn tuyến tính đơn giản.&lt;/li&gt;
  &lt;li&gt;Hướng xử lý thử trước: thêm thành phần phi tuyến như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x^2&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(x)&lt;/code&gt;, spline, hoặc thêm số hạng tương tác.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phần dư mở rộng hình phễu&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nghi ngờ: phương sai sai số không đồng nhất (heteroscedasticity), độ nhiễu tăng theo mức dự báo.&lt;/li&gt;
  &lt;li&gt;Hướng xử lý thử trước: biến đổi thang đo như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(y)&lt;/code&gt;, chuyển sang hàm hợp lý phù hợp với dữ liệu lệch, hoặc mô hình hóa trực tiếp phương sai thay đổi.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Xuất hiện nhiều giá trị cực đoan hơn dự kiến&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nghi ngờ: hàm hợp lý hiện tại có đuôi quá mỏng (chẳng hạn Gaussian rất nhạy với ngoại lai).&lt;/li&gt;
  &lt;li&gt;Hướng xử lý thử trước: rà soát lỗi dữ liệu và biến bị bỏ sót, sau đó cân nhắc hàm hợp lý đuôi dày như Student-t thay cho Gaussian.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Dữ liệu đếm có quá nhiều số 0 hoặc phương sai lớn hơn trung bình rõ rệt&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nghi ngờ: phân phối Poisson quá chặt so với độ phân tán thực tế.&lt;/li&gt;
  &lt;li&gt;Hướng xử lý thử trước: chuyển sang Negative Binomial khi có quá phân tán (overdispersion); nếu số 0 dư thừa xuất phát từ cơ chế riêng, cân nhắc mô hình zero-inflated hoặc hurdle.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Dữ liệu phân cụm theo nhóm hoặc phụ thuộc theo thời gian&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nghi ngờ: giả định độc lập giữa các quan sát bị vi phạm.&lt;/li&gt;
  &lt;li&gt;Hướng xử lý thử trước: bổ sung cấu trúc phân cấp theo nhóm, hiệu ứng ngẫu nhiên (random effects), hoặc mô hình tương quan theo thứ tự thời gian.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tóm lại, hãy sửa đúng giả định đang hỏng thay vì chọn mô hình theo xu hướng: phần dư cong là vấn đề &lt;strong&gt;mean structure&lt;/strong&gt;, hình phễu là vấn đề &lt;strong&gt;noise structure&lt;/strong&gt;, nhiều số 0 hoặc đuôi dày là vấn đề &lt;strong&gt;likelihood&lt;/strong&gt;, còn phân cụm theo nhóm/thời gian là vấn đề &lt;strong&gt;tính độc lập&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;4-ví-dụ-dữ-liệu-thực-tế-nêu-rõ-nguồn-số-liệu-và-suy-luận&quot;&gt;4) Ví dụ dữ liệu thực tế: Nêu rõ nguồn số liệu và suy luận&lt;/h2&gt;

&lt;p&gt;Để minh họa cụ thể thay vì nhận xét cảm tính, phần này dùng các tập dữ liệu công khai trong Python (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seaborn.load_dataset&lt;/code&gt;) theo quy trình bốn bước: nêu rõ dữ liệu và câu hỏi, khớp một mô hình cơ sở (baseline) đơn giản, kiểm tra giả định bằng chỉ số định lượng và biểu đồ phần dư, rồi đề xuất cập nhật đúng trọng tâm.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-1-dữ-liệu-diamonds-giá-kim-cương&quot;&gt;Ví dụ 1: Dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; (giá kim cương)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Nguồn dữ liệu&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seaborn.load_dataset(&quot;diamonds&quot;)&lt;/code&gt;, gồm \(n=53{,}940\) quan sát.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Câu hỏi&lt;/strong&gt;: nếu bắt đầu với một biến giải thích duy nhất là trọng lượng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, mô hình nào mô tả giá &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; ở mức hợp lý và những giả định nào hỏng trước tiên?&lt;/p&gt;

&lt;p&gt;Đây là dạng dữ liệu thực rất phổ biến: biến đầu ra dương, lệch phải mạnh và độ biến động tăng theo giá trị trung bình. Khớp thẳng mô hình Gaussian tuyến tính trên thang giá gốc dễ vi phạm đồng thời cả cấu trúc trung bình lẫn cấu trúc nhiễu.&lt;/p&gt;

&lt;p&gt;Bảng dưới đây trích 7 quan sát thật ở các mốc phân vị khác nhau của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; (sau khi sắp xếp tăng dần), cho thấy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; tăng nhanh theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; đồng thời còn chịu ảnh hưởng của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;color&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clarity&lt;/code&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Mốc trong phân phối giá&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;carat&lt;/th&gt;
      &lt;th&gt;cut&lt;/th&gt;
      &lt;th&gt;color&lt;/th&gt;
      &lt;th&gt;clarity&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;price (USD)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;0%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.23&lt;/td&gt;
      &lt;td&gt;Ideal&lt;/td&gt;
      &lt;td&gt;E&lt;/td&gt;
      &lt;td&gt;SI2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;326&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;10%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.31&lt;/td&gt;
      &lt;td&gt;Ideal&lt;/td&gt;
      &lt;td&gt;H&lt;/td&gt;
      &lt;td&gt;VS2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;646&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;30%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.42&lt;/td&gt;
      &lt;td&gt;Premium&lt;/td&gt;
      &lt;td&gt;H&lt;/td&gt;
      &lt;td&gt;VS1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1087&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;50%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.58&lt;/td&gt;
      &lt;td&gt;Ideal&lt;/td&gt;
      &lt;td&gt;F&lt;/td&gt;
      &lt;td&gt;VVS2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2401&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;70%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1.02&lt;/td&gt;
      &lt;td&gt;Ideal&lt;/td&gt;
      &lt;td&gt;I&lt;/td&gt;
      &lt;td&gt;VS2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4662&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;90%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1.51&lt;/td&gt;
      &lt;td&gt;Very Good&lt;/td&gt;
      &lt;td&gt;H&lt;/td&gt;
      &lt;td&gt;VS2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;9821&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;98%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.43&lt;/td&gt;
      &lt;td&gt;Very Good&lt;/td&gt;
      &lt;td&gt;H&lt;/td&gt;
      &lt;td&gt;SI2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;16170&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Bước 1 — Kiểm tra phân phối đầu ra&lt;/strong&gt;: trên dữ liệu thực, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;min = 326&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;median = 2401&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max = 18823&lt;/code&gt;, độ lệch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;skewness = 1.618&lt;/code&gt;, và phân vị thứ 95 ở mức &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;13107.1&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Chênh lệch lớn giữa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;median = 2401&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max = 18823&lt;/code&gt; cho thấy đuôi phải kéo rất dài.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;skewness = 1.618&lt;/code&gt; xác nhận định lượng mức độ lệch phải rõ rệt.&lt;/li&gt;
  &lt;li&gt;Mốc phân vị 95% ở &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;13107.1&lt;/code&gt; cho thấy nhóm nhỏ quan sát ở đuôi cao có thể tác động mạnh tới đường khớp nếu chọn sai mô hình.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;quyết-định-thực-hành-từ-các-chỉ-số-mô-tả&quot;&gt;Quyết định thực hành từ các chỉ số mô tả&lt;/h3&gt;

&lt;p&gt;Với phân phối dương và lệch phải mạnh như trên, một bước thử hợp lý là chuyển sang mô hình hóa trên thang &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(price)&lt;/code&gt; trước khi tăng độ phức tạp. Phép biến đổi log giúp nén đuôi phải và ổn định phương sai hơn, tạo điểm khởi đầu tốt hơn để chẩn đoán tiếp. Các thống kê mô tả đầu vào nhờ đó dẫn thẳng tới hành động mô hình hóa cụ thể.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_assumption_diamonds_distribution.png&quot; alt=&quot;Diamonds price distribution&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 2: Histogram giá kim cương (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt;) kèm mốc phân vị q95, thể hiện phân phối lệch phải rõ rệt với đuôi cao kéo dài.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 2 — Khớp mô hình cơ sở và kiểm tra phần dư&lt;/strong&gt;: ta khớp mô hình cơ sở đơn giản để làm mốc chẩn đoán:&lt;/p&gt;

\[y_i \sim \mathcal{N}(\mu_i, \sigma), \quad \mu_i = \alpha + \beta\,\text{carat}_i\]

&lt;p&gt;Tương đương \(y_i = \mu_i + \epsilon_i\) với \(\epsilon_i \sim \mathcal{N}(0,\sigma)\). Mô hình này giả định: (1) giá trung bình tăng tuyến tính theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, và (2) phương sai sai số không đổi trên toàn miền dự báo.&lt;/p&gt;

&lt;p&gt;Chẩn đoán định lượng trên phần dư \(e_i = y_i - \hat y_i\) cho thấy:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\mathrm{corr}(\lvert e_i \rvert, \hat y_i)=0.579\): tương quan dương mạnh, nghĩa là giá trị dự báo càng lớn thì độ lớn phần dư càng tăng.&lt;/li&gt;
  &lt;li&gt;MAE ở nhóm dự báo thấp và cao lần lượt là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;478.4&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2059.1&lt;/code&gt;, chênh nhau &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4.30&lt;/code&gt; lần.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sự mở rộng sai số có hệ thống này cho thấy giả định &lt;strong&gt;đồng nhất phương sai&lt;/strong&gt; bị vi phạm rõ rệt — hoàn toàn khớp với trực giác thực tế rằng sai số 500 USD là lớn với viên kim cương giá 700 USD nhưng nhỏ với viên giá 10,000 USD.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_assumption_diamonds_residuals.png&quot; alt=&quot;Diamonds residual vs fitted&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 3: Biểu đồ phần dư theo giá trị dự báo (residual vs fitted) của mô hình cơ sở trên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt;, cho thấy độ phân tán mở rộng hình phễu khi dự báo tăng (dấu hiệu heteroscedasticity).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 3 — Cập nhật mô hình và kiểm tra lại&lt;/strong&gt;: ta điều chỉnh trực tiếp vào hai điểm hỏng vừa phát hiện:&lt;/p&gt;

\[\log y_i = \alpha + \beta_1\,\text{carat}_i + \beta_2\,\text{carat}_i^2 + \epsilon_i,\]

&lt;p&gt;trong đó lấy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(y)&lt;/code&gt; chuyển sai số mang tính tỷ lệ về dạng cộng tính ổn định hơn, còn số hạng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat^2&lt;/code&gt; cho phép quan hệ trung bình có độ cong.&lt;/p&gt;

&lt;p&gt;Sau khi cập nhật, \(\mathrm{corr}(\lvert e_i \rvert, \hat y_i)\) giảm từ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.579&lt;/code&gt; xuống &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.047&lt;/code&gt; và tỷ lệ MAE cao/thấp giảm từ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4.30&lt;/code&gt; xuống &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.16&lt;/code&gt;. Cả hai chỉ số đều cho thấy độ phân tán phần dư giữa vùng giá thấp và vùng giá cao đã cân bằng hơn nhiều. Kết luận ở đây không phải mô hình log bậc hai là “đúng tuyệt đối”, mà là quy trình kiểm tra giả định đã chỉ đúng chỗ hỏng và xác nhận cải thiện bằng cùng bộ tiêu chí.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;ví-dụ-2-dữ-liệu-taxis-đếm-số-chuyến-theo-khu-vực-và-ngày&quot;&gt;Ví dụ 2: Dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;taxis&lt;/code&gt; (đếm số chuyến theo khu vực và ngày)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Nguồn dữ liệu&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seaborn.load_dataset(&quot;taxis&quot;)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Câu hỏi&lt;/strong&gt;: khi tổng hợp số chuyến theo từng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pickup_zone&lt;/code&gt; và từng ngày, phân phối Poisson có phải là mô hình cơ sở phù hợp cho biến đếm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trips&lt;/code&gt; hay không?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cách tạo biến đếm&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Lọc các chuyến có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pickup_borough = Manhattan&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Gộp theo cặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(pickup_zone, day)&lt;/code&gt; để đếm số chuyến &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trips&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Điền đầy đủ mọi tổ hợp khu vực–ngày để giữ lại các ngày có 0 chuyến.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Kết quả thu được \(n=1953\) ô quan sát khu vực–ngày, mỗi ô là một số đếm nguyên không âm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 1 — Kiểm tra giả định cơ bản của Poisson&lt;/strong&gt;: nếu \(Y \sim \mathrm{Poisson}(\lambda)\) thì kỳ vọng và phương sai phải bằng nhau:&lt;/p&gt;

\[\mathbb{E}[Y] = \mathrm{Var}(Y).\]

&lt;p&gt;Trên dữ liệu thực, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean(trips) = 2.697&lt;/code&gt; nhưng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var(trips) = 7.441&lt;/code&gt;, cho tỷ lệ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var/mean = 2.76&lt;/code&gt; — độ phân tán lớn gần gấp 3 lần mức Poisson cho phép. Đây là dấu hiệu rõ ràng của &lt;strong&gt;quá phân tán (overdispersion)&lt;/strong&gt;, xuất phát từ sự chênh lệch lớn về mật độ khách giữa các khu vực và giữa các ngày khác nhau.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_assumption_taxis_distribution.png&quot; alt=&quot;Taxis trip-count distribution&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 4: Phân phối số chuyến theo khu vực–ngày trong dữ liệu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;taxis&lt;/code&gt;, kèm các chỉ số mean, variance và tỷ số var/mean thể hiện quá phân tán.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 2 — Kiểm tra tỷ lệ số 0 và đuôi phải&lt;/strong&gt;: với Poisson, một tham số \(\lambda\) duy nhất quy định đồng thời trung bình, xác suất bằng 0 và xác suất đuôi phải:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Tỷ lệ bằng 0 quan sát được là \(P(Y=0)=0.245\), trong khi Poisson với \(\lambda=2.697\) chỉ dự báo \(P(Y=0)=e^{-\lambda}=0.067\) — thực tế nhiều hơn khoảng \(0.245 / 0.067 \approx 3.7\) lần.&lt;/li&gt;
  &lt;li&gt;Ở đuôi phải, tỷ lệ quan sát được là \(P(Y\ge 10)=0.0261\), trong khi Poisson chỉ dự báo \(0.00050\) — thực tế lớn hơn khoảng 52 lần.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Như vậy, phân phối Poisson một tham số quá hẹp: khi khớp trung bình, nó đồng thời đánh giá thấp cả xác suất ngày vắng (0 chuyến) lẫn xác suất ngày rất đông (\(\ge 10\) chuyến).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_assumption_taxis_probabilities.png&quot; alt=&quot;Observed vs model implied probabilities on taxis&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 5: So sánh xác suất quan sát với xác suất suy ra từ Poisson và Negative Binomial tại hai mốc mục tiêu \(P(Y=0)\) và \(P(Y\ge 10)\).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 3 — Cập nhật và kiểm tra lại&lt;/strong&gt;: với dữ liệu đếm quá phân tán, Negative Binomial là bước mở rộng tự nhiên vì cho phép phương sai lớn hơn trung bình (tương đương việc cho tốc độ sinh chuyến biến thiên giữa các khu vực–ngày).&lt;/p&gt;

&lt;p&gt;Ước lượng Negative Binomial theo phương pháp khớp mô-men (moment matching) cho tham số phân tán \(k=1.534\), dự báo \(P(Y=0)=0.211\) (gần mức quan sát &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.245&lt;/code&gt;) và \(P(Y\ge 10)=0.0279\) (rất sát mức quan sát &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0261&lt;/code&gt;). Lựa chọn Negative Binomial ở đây có cơ sở chẩn đoán rõ ràng vì nó khắc phục đồng thời ba điểm yếu của Poisson: phương sai vượt trung bình, tỷ lệ 0 cao và đuôi phải dày.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;điều-cần-rút-ra-từ-hai-ví-dụ&quot;&gt;Điều cần rút ra từ hai ví dụ&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Bắt đầu bằng một mô hình cơ sở đủ đơn giản để thấy rõ toàn bộ giả định đang đặt ra.&lt;/li&gt;
  &lt;li&gt;Gắn nhận xét trực quan với chỉ số định lượng cụ thể (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;skewness&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var/mean&lt;/code&gt;, tương quan phần dư, xác suất bằng 0 và đuôi).&lt;/li&gt;
  &lt;li&gt;Cập nhật đúng giả định bị vi phạm (biến đổi thang đo/thêm độ cong cho mean và noise structure; đổi hàm hợp lý khi phân phối đếm quá phân tán).&lt;/li&gt;
  &lt;li&gt;Kiểm chứng lại mô hình mới bằng chính bộ tiêu chí chẩn đoán ban đầu.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;5-quy-trình-15-phút-trước-khi-tin-vào-kết-quả-mô-hình&quot;&gt;5) Quy trình 15 phút trước khi tin vào kết quả mô hình&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Xem phân phối của biến đầu ra.&lt;/li&gt;
  &lt;li&gt;Khớp một mô hình đơn giản làm mốc cơ sở.&lt;/li&gt;
  &lt;li&gt;Vẽ biểu đồ phần dư theo giá trị dự báo và theo các biến giải thích chính.&lt;/li&gt;
  &lt;li&gt;Tìm điểm ảnh hưởng mạnh và kiểm tra độ nhạy của kết luận.&lt;/li&gt;
  &lt;li&gt;Kiểm tra dấu hiệu phụ thuộc theo thời gian hoặc theo nhóm.&lt;/li&gt;
  &lt;li&gt;Ghi nhận 1–2 giả định có rủi ro cao nhất.&lt;/li&gt;
  &lt;li&gt;Cập nhật mô hình và đối chiếu lại các chỉ số chẩn đoán.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mục tiêu của quy trình này là giảm rủi ro suy luận sai, không phải vẽ thật nhiều biểu đồ hình thức.&lt;/p&gt;

&lt;h2 id=&quot;6-sai-mô-hình-không-phải-thất-bại-mà-là-tín-hiệu-cập-nhật&quot;&gt;6) Sai mô hình không phải thất bại, mà là tín hiệu cập nhật&lt;/h2&gt;

&lt;p&gt;Trong quy trình làm việc Bayesian (Bayesian workflow), xây dựng mô hình là một vòng lặp:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Đề xuất mô hình.&lt;/li&gt;
  &lt;li&gt;Khớp mô hình với dữ liệu.&lt;/li&gt;
  &lt;li&gt;Kiểm tra giả định và hệ quả dự báo.&lt;/li&gt;
  &lt;li&gt;Cải tiến mô hình.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mục tiêu không phải chứng minh mô hình “đúng tuyệt đối”, mà là làm cho mô hình ngày càng phù hợp hơn với dữ liệu và câu hỏi nghiên cứu.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-sai-cấu-trúc-mô-hình--kiểm-tra-dự-báo-hậu-nghiệm-ppc&quot;&gt;Video ngắn: Sai cấu trúc mô hình &amp;amp; Kiểm tra Dự báo Hậu nghiệm (PPC)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-20b-misspecification-ppc.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): quy trình sinh dữ liệu giả lập y_rep từ hậu nghiệm để so sánh trực tiếp với dữ liệu thật y, sớm phát hiện mô hình thiếu khớp trước khi ra quyết định.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt-nhanh&quot;&gt;Tóm tắt nhanh&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Mọi mô hình thống kê đều đi kèm các giả định cụ thể.&lt;/li&gt;
  &lt;li&gt;Giả định bị vi phạm nặng có thể dẫn đến kết luận sai lệch.&lt;/li&gt;
  &lt;li&gt;Bộ kiểm tra tối thiểu gồm: phân phối đầu ra, phần dư, ngoại lai/điểm ảnh hưởng và tính độc lập.&lt;/li&gt;
  &lt;li&gt;Dấu hiệu sai đặc tả cần được chuyển thành điều chỉnh cụ thể ở hàm hợp lý hoặc cấu trúc mô hình.&lt;/li&gt;
  &lt;li&gt;Sai mô hình là thông tin chẩn đoán để cải tiến, không phải thất bại.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;giải-thích-bốn-câu-hỏi-chẩn-đoán-trước-khi-tin-kết-quả&quot;&gt;Giải thích: Bốn câu hỏi chẩn đoán trước khi tin kết quả&lt;/h2&gt;

&lt;p&gt;Mỗi khi vừa khớp xong một mô hình cơ bản, hãy đọc chậm và lần lượt kiểm tra bốn câu hỏi sau trên phần dư \(e_i = y_i - \hat y_i\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phần dư có còn hình dáng có quy luật (cong hình chữ U hay chữ S)?&lt;/strong&gt; Nếu có, quan hệ thật là phi tuyến — cần thêm bậc đa thức, spline hoặc biến đổi biến.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ phân tán của phần dư có phình to dần theo \(\hat y\) (hình phễu)?&lt;/strong&gt; Nếu có, phương sai không đồng nhất (heteroscedasticity) — khoảng tin cậy sẽ sai lệch nếu giữ nguyên giả định \(\sigma\) cố định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Có điểm ngoại lai nào kéo nghiêng đường hồi quy không?&lt;/strong&gt; Chỉ một quan sát bất thường cũng có thể làm lệch mạnh trung bình và độ dốc dưới hàm mất mát bình phương (Gaussian).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phần dư liên tiếp có tương quan theo thời gian hoặc theo nhóm không?&lt;/strong&gt; Nếu có, giả định độc lập bị phá vỡ và sai số chuẩn bị đánh giá thấp một cách giả tạo.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-một-điểm-ngoại-lai-làm-lệch-ước-lượng-ra-sao&quot;&gt;Ví dụ tính toán làm từng bước: Một điểm ngoại lai làm lệch ước lượng ra sao?&lt;/h3&gt;

&lt;p&gt;Xét 5 phép đo thời gian hoàn thành một tác vụ (đơn vị: giây): \(10, 11, 12, 13, 14\). Giả sử ở lần ghi thứ 5 bị lỗi nhập liệu từ \(14\) thành \(64\) (một điểm ngoại lai duy nhất). So sánh ước lượng trung bình (tương ứng likelihood Gaussian) và trung vị (tương ứng likelihood Laplace / bền vững):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Tập dữ liệu&lt;/th&gt;
      &lt;th&gt;Trung bình mẫu \(\bar x\)&lt;/th&gt;
      &lt;th&gt;Độ lệch chuẩn mẫu \(s\)&lt;/th&gt;
      &lt;th&gt;Trung vị (Median)&lt;/th&gt;
      &lt;th&gt;Khoảng tứ phân vị (IQR)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Dữ liệu sạch: \(10, 11, 12, 13, 14\)&lt;/td&gt;
      &lt;td&gt;\(60 / 5 = 12.0\text{ s}\)&lt;/td&gt;
      &lt;td&gt;\(1.58\text{ s}\)&lt;/td&gt;
      &lt;td&gt;\(12.0\text{ s}\)&lt;/td&gt;
      &lt;td&gt;\(13 - 11 = 2.0\text{ s}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Có 1 ngoại lai: \(10, 11, 12, 13, 64\)&lt;/td&gt;
      &lt;td&gt;\(110 / 5 = 22.0\text{ s}\)&lt;/td&gt;
      &lt;td&gt;\(23.51\text{ s}\)&lt;/td&gt;
      &lt;td&gt;\(12.0\text{ s}\)&lt;/td&gt;
      &lt;td&gt;\(13 - 11 = 2.0\text{ s}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chỉ &lt;strong&gt;một&lt;/strong&gt; điểm ngoại lai đã kéo trung bình tăng vọt từ \(12\text{ s}\) lên \(22\text{ s}\) (lệch hơn \(83\%\)) và làm độ lệch chuẩn phình gấp gần &lt;strong&gt;15 lần&lt;/strong&gt; (từ \(1.58\text{ s}\) lên \(23.51\text{ s}\)), trong khi trung vị và IQR hầu như bất biến. Đây là lý do trong hồi quy Bayes thực tế ta thường thay likelihood Gaussian bằng phân phối Student-\(t\) khi phát hiện ngoại lai.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nghĩ rằng chỉ cần hệ số \(R^2\) cao (chẳng hạn \(R^2 = 0.90\)) thì các giả định mô hình chắc chắn đã thỏa mãn. Bộ tứ Anscombe kinh điển chứng minh 4 tập dữ liệu có cùng \(R^2\) và cùng đường hồi quy nhưng cấu trúc phần dư hoàn toàn khác nhau.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu dùng mô hình Gaussian trên tập có ngoại lai trên, khoảng tin cậy 95% thô \(\bar x \pm 1.96\,s/\sqrt{5}\) trở thành \(22.0 \pm 20.6 = [1.4,\; 42.6]\text{ s}\) — rộng vô nghĩa vì vi phạm giả định đuôi mỏng.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=okjYjClSjOg&quot;&gt;Quantile-Quantile Plots (QQ plots), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giải thích cách dùng biểu đồ Q–Q để đối chiếu phân phối phần dư với phân phối giả định.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=iMdtTCX2Q70&quot;&gt;Simple Linear Regression:  Checking Assumptions with Residual Plots&lt;/a&gt; — jbstatistics, English. Minh họa các dạng biểu đồ phần dư và cách nhận diện giả định bị vi phạm.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ADICTMUvPg0&quot;&gt;Lecture37 (Data2Decision) Independence of Residuals&lt;/a&gt; — Chris Mack, English. Trình bày giả định độc lập của phần dư và các dấu hiệu tự tương quan.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Nêu một tình huống thực tế vi phạm giả định độc lập và đề xuất hướng điều chỉnh mô hình.&lt;/li&gt;
  &lt;li&gt;Vì sao biểu đồ phần dư theo giá trị dự báo giúp phát hiện sai cấu trúc trung bình?&lt;/li&gt;
  &lt;li&gt;Khi gặp giá trị ngoại lai mạnh, bạn phân biệt “lỗi dữ liệu” với “tín hiệu thực” bằng cách nào?&lt;/li&gt;
  &lt;li&gt;Chọn một bài toán phân tích dữ liệu bạn từng gặp và liệt kê 2 giả định rủi ro nhất của mô hình đó.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;McElreath, R. (2020). &lt;em&gt;Statistical Rethinking&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_19_simulation_for_statistical_intuition/&quot;&gt;0.21 Mô phỏng để kiểm tra trực giác thống kê&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.19: Log-probability và Ổn định số</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_17_log_probability_numerical_stability/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_17_log_probability_numerical_stability</id>
   <content type="html">&lt;p&gt;Trên bảng phấn, tích của 1.000 xác suất bằng \(0.1\) chỉ là một dòng ký hiệu gọn gàng \(10^{-1000}\). Nhưng ngay khi bạn gõ công thức ấy vào máy tính dấu phẩy động 64-bit chuẩn IEEE 754, con số đó lập tức biến mất thành đúng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt; vì vượt quá giới hạn dưới khoảng \(10^{-308}\). Trong một lần chạy công thức Bayes, chỉ cần tử số và mẫu số cùng bị làm tròn về &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt;, toàn bộ thuật toán lập tức sập với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0 / 0.0 = NaN&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Bài học này bóc tách &lt;strong&gt;cầu nối giữa toán học lý tưởng và tính toán số thực tế&lt;/strong&gt;: làm việc trên thang logarit và sử dụng thủ thuật &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log-sum-exp&lt;/code&gt; không phải mẹo lập trình vặt, mà là kỹ thuật quan trọng trong mọi phần mềm Bayes hiện đại như PyMC hay Stan.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu vì sao thực hành Bayesian gần như luôn thao tác trên thang log, nhận diện được các sự cố số học như underflow, overflow, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt;, biết cách viết log-likelihood và log-posterior đúng chuẩn, đồng thời nắm kỹ thuật log-sum-exp để chuẩn hóa trọng số hậu nghiệm an toàn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-số-học-dấu-phẩy-động-đại-số-logarit-và-ổn-định-mcmc&quot;&gt;Kiến thức cần nhớ: Số học dấu phẩy động, Đại số Logarit và Ổn định MCMC&lt;/h2&gt;

&lt;p&gt;Để hiểu vì sao mọi công cụ Bayes chuyên nghiệp đều tính hoàn toàn trong không gian log, hãy kết nối ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Biểu diễn dấu phẩy động IEEE 754 (Floating-Point Arithmetic):&lt;/strong&gt; Số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; chỉ biểu diễn được các số dương lớn hơn khoảng \(2.2 \times 10^{-308}\) (và nhỏ hơn \(1.8 \times 10^{308}\)). Khi nhân hàng trăm xác suất nhỏ hơn 1, hiện tượng tràn dưới (&lt;em&gt;underflow&lt;/em&gt;) chắc chắn xảy ra.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phép biến đổi đơn điệu Logarit (Log-Space Algebra):&lt;/strong&gt; Hàm \(\log\) biến tích thành tổng (\(\log\prod p_i = \sum \log p_i\)), giữ nguyên thứ tự lớn nhỏ (nên \(\arg\max\) không đổi) và thu gọn dải giá trị \(10^{-1000}\) thành một con số hết sức bình thường là \(-2302.6\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kỹ thuật Log-Sum-Exp &amp;amp; Cầu nối sang Bayes:&lt;/strong&gt; Khi chuẩn hóa phân phối hậu nghiệm trên lưới hay tính trọng số mô hình (WAIC/LOO), ta buộc phải cộng các xác suất từ thang log. Đẳng thức \(\log\sum_i e^{a_i} = m + \log\sum_i e^{a_i - m}\) (với \(m = \max_i a_i\)) triệt tiêu cả tràn trên lẫn tràn dưới mà không làm mất một chữ số chính xác nào.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-đúng-về-mặt-toán-chưa-đủ-còn-phải-ổn-định-trên-máy-tính&quot;&gt;Giới thiệu: Đúng về mặt toán chưa đủ, còn phải ổn định trên máy tính&lt;/h2&gt;

&lt;p&gt;Nhiều công thức xác suất hoàn toàn đúng trên giấy nhưng lại thất bại khi chạy trên máy tính. Nguyên nhân không nằm ở lý thuyết xác suất mà ở giới hạn biểu diễn số dấu phẩy động của máy tính. Trong tính toán Bayesian, hàm hợp lý và phân phối hậu nghiệm thường là tích của rất nhiều số dương nhỏ hơn 1; nếu nhân trực tiếp, kết quả dễ bị làm tròn thành 0. Ngược lại, một số phép lấy hàm mũ có thể tràn số thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt;. Khi đó, mô hình toán học vẫn đúng nhưng thuật toán đã hỏng.&lt;/p&gt;

&lt;p&gt;Do đó, làm việc trên thang log (log-probability) không phải mẹo vặt lập trình, mà là chuẩn mực bắt buộc để tối ưu hóa, chuẩn hóa và lấy mẫu xác suất một cách ổn định.&lt;/p&gt;

&lt;h2 id=&quot;1-vấn-đề-thực-sự-nằm-ở-đâu&quot;&gt;1) Vấn đề thực sự nằm ở đâu?&lt;/h2&gt;

&lt;p&gt;Với chuẩn số thực &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt;, máy tính chỉ biểu diễn được một dải giá trị hữu hạn. Trong mô hình xác suất, giới hạn này bộc lộ ngay khi gặp ba tình huống:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Nhân rất nhiều xác suất nhỏ hơn 1 với nhau.&lt;/li&gt;
  &lt;li&gt;Lấy hàm mũ của các số có độ lớn quá lớn.&lt;/li&gt;
  &lt;li&gt;Chuẩn hóa bằng cách chia các số cực nhỏ cho tổng của các số cực nhỏ khác.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Xét ví dụ đơn giản:&lt;/p&gt;

\[10^{-3}\times 10^{-3}\times \cdots \times 10^{-3}\quad \text{(1000 lần)} = 10^{-3000}\]

&lt;p&gt;Con số này hoàn toàn hợp lệ về mặt toán học, nhưng vượt dưới ngưỡng biểu diễn của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; nên máy tính làm tròn thành 0. Khi đó, ta mất toàn bộ thông tin về độ lớn tương đối của nó.&lt;/p&gt;

&lt;h2 id=&quot;2-log-probability-là-gì-và-vì-sao-nó-giải-quyết-được-bài-toán&quot;&gt;2) Log-probability là gì và vì sao nó giải quyết được bài toán?&lt;/h2&gt;

&lt;p&gt;Với mọi xác suất \(p &amp;gt; 0\), ta chuyển sang làm việc với \(\log p\) (trong thống kê mặc định là logarit tự nhiên). Tính chất quyết định là hàm log biến tích thành tổng:&lt;/p&gt;

\[\log\left(\prod_{i=1}^n p(x_i\mid\theta)\right)=\sum_{i=1}^n \log p(x_i\mid\theta)\]

&lt;p&gt;Trong thực hành, làm việc trên thang log mang lại ba lợi ích chính:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Tránh underflow khi nhân nhiều xác suất nhỏ.&lt;/li&gt;
  &lt;li&gt;Chuyển tích thành tổng nên thuận tiện hơn cho đạo hàm và tối ưu hóa.&lt;/li&gt;
  &lt;li&gt;Kết hợp phân phối tiên nghiệm và hàm hợp lý thành phép cộng đơn giản trong định lý Bayes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Lưu ý nhỏ về thuật ngữ: với biến liên tục, đại lượng chính xác là &lt;strong&gt;log-density&lt;/strong&gt; (log của hàm mật độ), nhưng trong thực hành Bayesian thường được gọi gọn là &lt;strong&gt;log-probability&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;21-ví-dụ-quen-thuộc-khi-chuyển-sang-thang-log&quot;&gt;2.1) Ví dụ quen thuộc khi chuyển sang thang log&lt;/h3&gt;

&lt;p&gt;Với phân phối Binomial:&lt;/p&gt;

\[p(k\mid n,\theta)=\binom{n}{k}\theta^k(1-\theta)^{n-k}\]

&lt;p&gt;Lấy log hai vế ta thu được:&lt;/p&gt;

\[\log p(k\mid n,\theta)=\log\binom{n}{k}+k\log\theta+(n-k)\log(1-\theta)\]

&lt;p&gt;Thay vì nhân các lũy thừa rất nhỏ như \(\theta^k\) và \((1-\theta)^{n-k}\), ta chỉ cần cộng các hạng tử log tương ứng.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/log_probability_direct_product.png&quot; alt=&quot;Nhân trực tiếp nhiều xác suất nhỏ dễ gây underflow&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1a: Nhân trực tiếp nhiều xác suất nhỏ trên thang thường khiến tích nhanh chóng chạm 0 do underflow.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;22-cực-đại-của-hàm-hợp-lý-không-đổi-khi-lấy-log&quot;&gt;2.2) Cực đại của hàm hợp lý không đổi khi lấy log&lt;/h3&gt;

&lt;p&gt;Vì hàm log tăng nghiêm ngặt trên \((0, \infty)\), điểm cực đại được bảo toàn:&lt;/p&gt;

\[\arg\max_\theta L(\theta)=\arg\max_\theta \log L(\theta)\]

&lt;p&gt;Do đó, khi tìm MLE hay MAP, ta có thể tối ưu hóa trực tiếp trên thang log mà không làm thay đổi nghiệm.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-số-cụ-thể-đúng-về-toán-học-nhưng-hỏng-khi-tính-trực-tiếp&quot;&gt;3) Ví dụ số cụ thể: Đúng về toán học nhưng hỏng khi tính trực tiếp&lt;/h2&gt;

&lt;p&gt;Giả sử có 1,000 quan sát độc lập và tại một giá trị tham số nào đó, mỗi quan sát đóng góp xác suất xấp xỉ 0.01. Khi đó:&lt;/p&gt;

\[L = 0.01^{1000} = 10^{-2000}\]

&lt;p&gt;Trên giấy đây là một số dương, nhưng trên máy tính nó bị làm tròn thành:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;— tức xảy ra &lt;strong&gt;underflow&lt;/strong&gt;. Trong khi đó, log-likelihood vẫn hữu hạn và dễ xử lý:&lt;/p&gt;

\[\log L = 1000\log(0.01)\approx -4605.17\]

&lt;p&gt;Hơn nữa, phần lớn thuật toán Bayesian chỉ cần so sánh độ lớn &lt;strong&gt;tương đối&lt;/strong&gt; giữa các tham số. Nếu hai giá trị tham số cho:&lt;/p&gt;

\[\log L_1=-4605,\qquad \log L_2=-4700\]

&lt;p&gt;ta biết ngay \(L_1 &amp;gt; L_2\), dù nếu lấy hàm mũ trên máy tính thì cả hai đều bị đưa về &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;4-underflow-overflow--inf-và-nan&quot;&gt;4) Underflow, overflow, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;Đây là bốn tín hiệu số học thường gặp nhất khi lập trình mô hình xác suất:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Underflow&lt;/strong&gt;: số dương quá nhỏ bị làm tròn thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt; (ví dụ nhân nhiều xác suất nhỏ hoặc tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.exp(-1000)&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Overflow&lt;/strong&gt;: số quá lớn vượt giới hạn lưu trữ của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; và trở thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt; (ví dụ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.exp(1000)&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt;&lt;/strong&gt;: thường xuất hiện khi tính \(\log(0)\). Trong mô hình xác suất, đây đôi khi là kết quả hợp lệ khi mô hình gán xác suất bằng 0 cho một trạng thái không khả thi.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt;&lt;/strong&gt;: xuất hiện khi phép toán vô định về mặt số học, chẳng hạn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0/0&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf - inf&lt;/code&gt;, hoặc chuẩn hóa một vector trọng số mà mọi phần tử đã underflow về 0.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Vì vậy, thang log giảm mạnh rủi ro số học nhưng không loại bỏ hoàn toàn; bạn vẫn cần kiểm tra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt; trong quá trình chạy mô hình.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-thảm-họa-tràn-số-dưới-underflow-khi-nhân-hàng-nghìn-xác-suất&quot;&gt;Video ngắn: Thảm họa Tràn số dưới (Underflow) khi nhân hàng nghìn xác suất&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-19a-underflow-disaster.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): cách tích 1.000 xác suất nhỏ sụp xuống đúng 0.0 trong dấu phẩy động 64-bit và giải pháp chuyển toàn bộ phép nhân sang tổng log-xác suất.&lt;/p&gt;

&lt;h2 id=&quot;5-trong-thống-kê-bayesian-ta-thường-làm-việc-với-log-posterior&quot;&gt;5) Trong thống kê Bayesian, ta thường làm việc với log-posterior&lt;/h2&gt;

&lt;p&gt;Viết định lý Bayes ở dạng xác suất:&lt;/p&gt;

\[p(\theta\mid x)=\frac{p(x\mid\theta)p(\theta)}{p(x)}\]

&lt;p&gt;Chuyển sang thang log:&lt;/p&gt;

\[\log p(\theta\mid x)=\log p(x\mid\theta)+\log p(\theta)-\log p(x)\]

&lt;p&gt;Hay viết gọn:&lt;/p&gt;

\[\log p(\theta\mid x)=\log p(x\mid\theta)+\log p(\theta)+C\]

&lt;p&gt;trong đó \(C\) là hằng số không phụ thuộc vào \(\theta\). Tính chất này đặc biệt hữu ích vì:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Để so sánh hai giá trị tham số, không cần tính hằng số chuẩn hóa \(p(x)\).&lt;/li&gt;
  &lt;li&gt;Ước lượng MAP chỉ cần cực đại hóa log-posterior chưa chuẩn hóa.&lt;/li&gt;
  &lt;li&gt;Các thuật toán lấy mẫu và xấp xỉ hiện đại như MCMC, HMC, NUTS hay variational inference đều hoạt động trực tiếp trên hàm mật độ đồng thời ở thang log.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nói cách khác, phần lõi mà các thư viện Bayesian tính toán thực chất là &lt;strong&gt;log-likelihood&lt;/strong&gt; và &lt;strong&gt;log-posterior chưa chuẩn hóa&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;6-khi-nào-cần-quay-lại-thang-xác-suất&quot;&gt;6) Khi nào cần quay lại thang xác suất?&lt;/h2&gt;

&lt;p&gt;Ta buộc phải chuyển từ thang log về thang xác suất trong các tình huống như:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Chuẩn hóa trọng số sao cho tổng bằng 1.&lt;/li&gt;
  &lt;li&gt;Tính phân phối hậu nghiệm trên lưới (grid approximation).&lt;/li&gt;
  &lt;li&gt;Chuyển log-weight thành xác suất lấy mẫu.&lt;/li&gt;
  &lt;li&gt;Tính hàm softmax trong phân loại hoặc học máy.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nếu các log-weight đều rất âm, việc tính trực tiếp:&lt;/p&gt;

\[e^{a_i}\]

&lt;p&gt;có thể khiến mọi phần tử underflow về &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt;, dẫn tới phép chia &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0/0&lt;/code&gt; và kết quả &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;7-kỹ-thuật-log-sum-exp&quot;&gt;7) Kỹ thuật log-sum-exp&lt;/h2&gt;

&lt;p&gt;Khi cần tính:&lt;/p&gt;

\[\log\sum_i e^{a_i}\]

&lt;p&gt;không nên tính hàm mũ trực tiếp mà dùng dạng ổn định số học:&lt;/p&gt;

\[\log\sum_i e^{a_i}=m+\log\sum_i e^{a_i-m},\qquad m=\max_i a_i\]

&lt;p&gt;Bằng cách tách \(e^m\) ra ngoài tổng, mọi số mũ \(a_i - m\) đều nhỏ hơn hoặc bằng 0, tránh được overflow và giữ lại thành phần trội nhất để tránh underflow toàn phần.&lt;/p&gt;

&lt;h3 id=&quot;71-vì-sao-trừ-max-không-làm-đổi-kết-quả-chuẩn-hóa&quot;&gt;7.1) Vì sao trừ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt; không làm đổi kết quả chuẩn hóa?&lt;/h3&gt;

&lt;p&gt;Khi chuẩn hóa trọng số, ta chỉ quan tâm tỷ lệ tương đối giữa các thành phần. Với mọi hằng số \(c\):&lt;/p&gt;

\[\frac{e^{a_i}}{\sum_j e^{a_j}}
=
\frac{e^{a_i-c}}{\sum_j e^{a_j-c}}\]

&lt;p&gt;Do đó, trừ cùng một hằng số khỏi toàn bộ log-weight không làm thay đổi xác suất cuối cùng, và chọn \(c=\max_j a_j\) là cách an toàn nhất về mặt số học.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/log_probability_log_sum.png&quot; alt=&quot;Cộng trên thang log ổn định hơn với log-sum-exp&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1b: Kỹ thuật log-sum-exp dịch các số mũ về quanh giá trị lớn nhất để phép cộng và chuẩn hóa xác suất luôn ổn định.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;72-ví-dụ-minh-họa&quot;&gt;7.2) Ví dụ minh họa&lt;/h3&gt;

&lt;p&gt;Giả sử ba log-weight là:&lt;/p&gt;

\[a=(-1000,\,-1001,\,-1005)\]

&lt;p&gt;Nếu lấy hàm mũ trực tiếp:&lt;/p&gt;

\[e^{-1000},\ e^{-1001},\ e^{-1005}\]

&lt;p&gt;thì cả ba đều bị làm tròn thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt; trên máy tính. Khi trừ đi giá trị lớn nhất \(\max(a) = -1000\):&lt;/p&gt;

\[a-\max(a)=(0,\,-1,\,-5)\]

&lt;p&gt;Ta thu được:&lt;/p&gt;

\[(e^0,\ e^{-1},\ e^{-5}) \approx (1,\ 0.3679,\ 0.0067)\]

&lt;p&gt;Sau khi chuẩn hóa, ba trọng số xấp xỉ:&lt;/p&gt;

\[(0.727,\ 0.268,\ 0.005)\]

&lt;p&gt;Như vậy thông tin xác suất vẫn hoàn toàn nguyên vẹn; chỉ cách tính trực tiếp mới làm mất thông tin đó.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-thủ-thuật-log-sum-exp-tính-tổng-xác-suất-không-bao-giờ-tràn-số&quot;&gt;Video ngắn: Thủ thuật Log-Sum-Exp: Tính tổng xác suất không bao giờ tràn số&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-19b-log-sum-exp.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): cách rút giá trị cực đại m = max(aᵢ) để cộng các log-xác suất an toàn tuyệt đối khi chuẩn hóa mẫu số định lý Bayes và tính Softmax.&lt;/p&gt;

&lt;h2 id=&quot;8-ví-dụ-python-ngắn&quot;&gt;8) Ví dụ Python ngắn&lt;/h2&gt;

&lt;p&gt;Đoạn mã dưới đây minh họa hai lỗi phổ biến: underflow khi nhân xác suất trực tiếp và lỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt; khi chuẩn hóa log-weight chưa trừ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ 1: nhân xác suất trực tiếp
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;likelihood&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;log_likelihood&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# 0.0  -&amp;gt; underflow
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# -4605.170185988091
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Ví dụ 2: chuẩn hóa log-weights sai cách
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1000.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1001.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1005.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;bad_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;bad_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bad_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bad_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bad_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;     &lt;span class=&quot;c1&quot;&gt;# [nan nan nan]
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Cách ổn định: trừ max trước khi exponentiate
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;good_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;good_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;good_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;good_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;good_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# [0.727..., 0.268..., 0.0049...]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Bài học rút ra là: khi đã ở thang log, đừng lấy hàm mũ quá sớm; và khi cần chuẩn hóa, hãy trừ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt; hoặc dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log-sum-exp&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;9-các-sai-lầm-thực-hành-thường-gặp&quot;&gt;9) Các sai lầm thực hành thường gặp&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Dùng \(\log a + \log b\) thay cho \(\log(a+b)\): đây là nhầm lẫn cơ bản vì \(\log a + \log b = \log(ab)\). Khi cần tính log của một tổng, phải dùng log-sum-exp.&lt;/li&gt;
  &lt;li&gt;Tính hàm hợp lý trên thang thường rồi mới lấy log: nếu hàm hợp lý đã underflow về 0 thì lấy log chỉ cho \(-\infty\), không thể khôi phục thông tin đã mất.&lt;/li&gt;
  &lt;li&gt;Lấy hàm mũ cho log-posterior quá sớm chỉ để nhìn cho quen mắt, trong khi phần lớn bước tính không cần quay lại thang xác suất.&lt;/li&gt;
  &lt;li&gt;Mặc định mọi giá trị \(-\infty\) đều là lỗi lập trình: đôi khi \(-\infty\) là tín hiệu hợp lệ cho biết mô hình gán xác suất 0 cho một cấu hình cụ thể; cần phân biệt đó là tính chất mô hình hay lỗi số học.&lt;/li&gt;
  &lt;li&gt;Nhầm tưởng log-density của biến liên tục phải luôn âm: vì hàm mật độ có thể lớn hơn 1, log-density hoàn toàn có thể mang giá trị dương.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;10-thói-quen-tốt-khi-lập-trình-mô-hình-bayesian&quot;&gt;10) Thói quen tốt khi lập trình mô hình Bayesian&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Viết hàm trả về log-likelihood hoặc log-posterior thay vì likelihood thô.&lt;/li&gt;
  &lt;li&gt;Cộng các đóng góp của từng quan sát trên thang log.&lt;/li&gt;
  &lt;li&gt;Chỉ lấy hàm mũ ở bước cuối cùng khi thực sự cần xác suất đã chuẩn hóa.&lt;/li&gt;
  &lt;li&gt;Dùng kỹ thuật trừ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt; hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log-sum-exp&lt;/code&gt; khi chuẩn hóa trọng số.&lt;/li&gt;
  &lt;li&gt;Kiểm tra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.isfinite(...)&lt;/code&gt; ở các bước tính quan trọng.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nguyên tắc cốt lõi cần nhớ: &lt;strong&gt;trong tính toán Bayesian, hãy giữ phép tính trên thang log lâu nhất có thể.&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt-nhanh&quot;&gt;Tóm tắt nhanh&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Công thức xác suất đúng về mặt toán học vẫn có thể hỏng trên máy tính do giới hạn biểu diễn số.&lt;/li&gt;
  &lt;li&gt;Log-probability biến tích thành tổng, tránh underflow và thuận lợi cho tối ưu hóa.&lt;/li&gt;
  &lt;li&gt;Tính toán Bayesian chủ yếu làm việc với log-likelihood và log-posterior chưa chuẩn hóa.&lt;/li&gt;
  &lt;li&gt;Khi cần cộng hoặc chuẩn hóa từ thang log, dùng log-sum-exp hoặc kỹ thuật trừ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Các giá trị &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt; là tín hiệu chẩn đoán quan trọng trong quy trình tính toán.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;giải-thích-ba-bước-chuẩn-hóa-hậu-nghiệm-an-toàn-bằng-log-sum-exp&quot;&gt;Giải thích: Ba bước chuẩn hóa hậu nghiệm an toàn bằng Log-Sum-Exp&lt;/h2&gt;

&lt;p&gt;Khi bạn có vectơ log-posterior chưa chuẩn hóa \(\mathbf{a} = (a_1, \dots, a_K)\) gồm các số âm rất lớn, hãy luôn thực hiện đúng ba bước sau thay vì gọi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;exp(a)&lt;/code&gt; trực tiếp:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tìm điểm neo cực đại:&lt;/strong&gt; Đặt \(m = \max_k a_k\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dịch chuyển về gần 0 trước khi lấy mũ:&lt;/strong&gt; Tính \(b_k = a_k - m \le 0\). Phần tử lớn nhất có \(b_{k^*} = 0 \implies e^{b_{k^*}} = 1\), đảm bảo không bao giờ tràn trên (overflow) và mẫu số luôn \(\ge 1\) (không bao giờ chia cho 0).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính hằng số chuẩn hóa và xác suất hậu nghiệm:&lt;/strong&gt; \(\log Z = m + \log\sum_k e^{b_k}\), rồi \(p_k = \exp(a_k - \log Z)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-chuẩn-hóa-3-mô-hình-có-log-posterior-bằng--1000&quot;&gt;Ví dụ tính toán làm từng bước: Chuẩn hóa 3 mô hình có log-posterior bằng \(-1000\)&lt;/h3&gt;

&lt;p&gt;Giả sử sau khi quan sát tập dữ liệu lớn, ba giả thuyết \(H_1, H_2, H_3\) có log-posterior chưa chuẩn hóa lần lượt là \(a_1 = -1000.0\), \(a_2 = -1001.0\), \(a_3 = -1002.0\).&lt;/p&gt;

&lt;p&gt;Nếu tính trực tiếp trên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt;: \(\exp(-1000) = 0.0\), nên tổng bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt; và tỷ số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0 / 0.0 = NaN&lt;/code&gt;! Bây giờ áp dụng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log-sum-exp&lt;/code&gt; với \(m = -1000.0\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Giả thuyết&lt;/th&gt;
      &lt;th&gt;Log gốc \(a_k\)&lt;/th&gt;
      &lt;th&gt;Dịch chuyển \(b_k = a_k - m\)&lt;/th&gt;
      &lt;th&gt;\(e^{b_k}\)&lt;/th&gt;
      &lt;th&gt;Xác suất chuẩn hóa \(p_k = e^{b_k} / \sum e^{b_j}\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(H_1\)&lt;/td&gt;
      &lt;td&gt;\(-1000.0\)&lt;/td&gt;
      &lt;td&gt;\(0.0\)&lt;/td&gt;
      &lt;td&gt;\(1.0000\)&lt;/td&gt;
      &lt;td&gt;\(1.0000 / 1.5032 \approx 0.6652\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(H_2\)&lt;/td&gt;
      &lt;td&gt;\(-1001.0\)&lt;/td&gt;
      &lt;td&gt;\(-1.0\)&lt;/td&gt;
      &lt;td&gt;\(0.3679\)&lt;/td&gt;
      &lt;td&gt;\(0.3679 / 1.5032 \approx 0.2447\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(H_3\)&lt;/td&gt;
      &lt;td&gt;\(-1002.0\)&lt;/td&gt;
      &lt;td&gt;\(-2.0\)&lt;/td&gt;
      &lt;td&gt;\(0.1353\)&lt;/td&gt;
      &lt;td&gt;\(0.1353 / 1.5032 \approx 0.0900\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Tổng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(1.5032\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(1.0000\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Hằng số chuẩn hóa trên thang log là \(\log Z = -1000.0 + \ln(1.5032) \approx -999.5924\). Kết quả chính xác tuyệt đối và hoàn toàn tránh được &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhầm rằng trừ cùng một hằng số \(m\) khỏi các giá trị log sẽ làm thay đổi xác suất cuối cùng. Thực tế trừ \(m\) trên thang log tương đương chia cả tử và mẫu cho \(e^m\) trên thang xác suất — tỷ số không hề thay đổi.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu cộng thêm \(-5000\) vào cả ba giá trị \(a_1, a_2, a_3\) (thành \(-6000, -6001, -6002\)), các giá trị dịch chuyển \(b_k\) vẫn là \(0, -1, -2\), nên xác suất hậu nghiệm vẫn y hệt \((0.6652, 0.2447, 0.0900)\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VSi0Z04fWj0&quot;&gt;Logs (logarithms), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Ôn lại tính chất biến tích thành tổng của logarit làm nền cho log-likelihood.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HghZrdnrNQY&quot;&gt;Why Log Probabilities Are Everywhere in AI - Underflow Error in HMMs and Viterbi Algorithm&lt;/a&gt; — Algorithms and AI, English. Minh họa sự cố underflow khi nhân nhiều xác suất nhỏ trong thực tế.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=MZ2VM32h37g&quot;&gt;The log-sum-exp trick (NLP817 5.12)&lt;/a&gt; — Herman Kamper, English. Giải thích chi tiết kỹ thuật log-sum-exp để chuẩn hóa an toàn từ thang log.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao hai giá trị likelihood khác nhau có thể cùng bị làm tròn thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt; trên máy tính, trong khi hai giá trị log-likelihood tương ứng vẫn so sánh được?&lt;/li&gt;
  &lt;li&gt;Giải thích bằng lời vì sao trừ đi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt; không làm thay đổi kết quả softmax cuối cùng.&lt;/li&gt;
  &lt;li&gt;Khi nào \(-\infty\) là hệ quả hợp lệ của mô hình và khi nào nó là dấu hiệu lỗi số học?&lt;/li&gt;
  &lt;li&gt;Vì sao không thể thay \(\log(a+b)\) bằng \(\log a + \log b\)?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Murphy, K. (2012). &lt;em&gt;Machine Learning: A Probabilistic Perspective&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Bishop, C. (2006). &lt;em&gt;Pattern Recognition and Machine Learning&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Higham, N. J. (2002). &lt;em&gt;Accuracy and Stability of Numerical Algorithms&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_18_basic_model_assumption_checks/&quot;&gt;0.20 Kiểm tra giả định mô hình cơ bản&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.18: Ước lượng điểm, Bias-Variance, Consistency</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_16_point_estimation_bias_variance_consistency/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_16_point_estimation_bias_variance_consistency</id>
   <content type="html">&lt;p&gt;Trong phần lớn thế kỷ 20, thống kê học xoay quanh một câu hỏi tưởng như hiển nhiên: làm sao nén toàn bộ dữ liệu thành &lt;em&gt;một con số tốt nhất&lt;/em&gt; đại diện cho tham số chưa biết — và “tốt nhất” nghĩa là gì? Ronald Fisher đặt nền móng cho ước lượng hợp lý cực đại (MLE), nhưng năm 1956 Charles Stein gây chấn động giới toán học khi chứng minh rằng ở từ 3 chiều trở lên, một bộ ước lượng &lt;em&gt;có chệch nhẹ&lt;/em&gt; (co về gốc tọa độ) lại đạt sai số bình phương trung bình thấp hơn mọi bộ ước lượng không chệch cổ điển.&lt;/p&gt;

&lt;p&gt;Câu chuyện của Stein chính là cánh cửa tự nhiên dẫn sang tư duy Bayes: chấp nhận một chút độ chệch có kiểm soát (từ phân phối prior) để đổi lấy sự sụt giảm mạnh của phương sai khi dữ liệu còn ít.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu ba tiêu chí cốt lõi để đánh giá một bộ ước lượng (estimator): độ chệch (bias), phương sai (variance) và tính nhất quán (consistency), đồng thời nắm được sự đánh đổi độ chệch – phương sai (bias–variance tradeoff) như một nguyên lý thực hành khi thiết kế mô hình.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-lý-thuyết-ước-lượng-điểm-phân-rã-mse-và-cầu-nối-sang-co-cụm-bayes&quot;&gt;Kiến thức cần nhớ: Lý thuyết ước lượng điểm, Phân rã MSE và Cầu nối sang Co cụm Bayes&lt;/h2&gt;

&lt;p&gt;Bốn khái niệm trong bài này tạo thành ngôn ngữ đánh giá chuẩn cho mọi bộ ước lượng (từ MLE, OLS đến Posterior Mean và MAP):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Độ chệch và Phương sai (Bias &amp;amp; Variance):&lt;/strong&gt; Độ chệch \(\mathrm{Bias}(\hat\theta) = \mathbb{E}[\hat\theta] - \theta\) đo sai lệch hệ thống, còn phương sai \(\mathrm{Var}(\hat\theta)\) đo mức dao động của ước lượng theo mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sai số bình phương trung bình (MSE Decomposition):&lt;/strong&gt; Mọi sai số bình phương trung bình đều tách gọn thành \(\mathrm{MSE}(\hat\theta) = \mathrm{Bias}(\hat\theta)^2 + \mathrm{Var}(\hat\theta)\). Đây là nền toán học cho đánh đổi độ chệch – phương sai trong học máy và điều chuẩn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính nhất quán (Consistency) &amp;amp; Tiệm cận Bayes:&lt;/strong&gt; Một ước lượng nhất quán hội tụ về giá trị thật \(\theta\) khi \(n \to \infty\). Trong thống kê Bayes, định lý Bernstein–von Mises khẳng định rằng dưới điều kiện chính quy, phân phối hậu nghiệm cũng hội tụ về giá trị thật và thu hẹp quanh MLE khi dữ liệu đủ lớn — tức ước lượng Bayes vừa nhất quán vừa tối ưu hơn khi cỡ mẫu nhỏ.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-đánh-giá-ước-lượng-không-thể-chỉ-nhìn-một-mẫu-duy-nhất&quot;&gt;Giới thiệu: Đánh giá ước lượng không thể chỉ nhìn một mẫu duy nhất&lt;/h2&gt;

&lt;p&gt;Một bộ ước lượng tốt không chỉ cho kết quả “gần đúng” trong một lần lấy mẫu ngẫu nhiên. Ta cần xem xét hành vi của nó trên nhiều mẫu khả dĩ: có lệch có hệ thống không, có dao động quá mạnh giữa các mẫu không, và khi cỡ mẫu tăng lên thì có hội tụ về giá trị thật không. Ba tiêu chí bias, variance và consistency được xây dựng để trả lời ba câu hỏi này.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/bias_variance_tradeoff_curve.png&quot; alt=&quot;Bias variance tradeoff&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1: Khi độ phức tạp mô hình tăng, độ chệch (bias) giảm dần nhưng phương sai (variance) tăng lên, khiến sai số bình phương trung bình (MSE) đạt cực tiểu tại một điểm cân bằng.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-ước-lượng-điểm-là-gì&quot;&gt;1) Ước lượng điểm là gì?&lt;/h2&gt;

&lt;p&gt;Ước lượng điểm (point estimator) là một hàm của dữ liệu \(\hat\theta=g(x_1,\dots,x_n)\) dùng để đưa ra một giá trị ước lượng cụ thể cho tham số chưa biết \(\theta\). Ví dụ, ta dùng trung bình mẫu \(\bar X\) để ước lượng \(\mu\), tỷ lệ mẫu \(\hat p\) để ước lượng \(p\), hoặc hệ số hồi quy mẫu để ước lượng độ dốc thật.&lt;/p&gt;

&lt;h2 id=&quot;2-độ-chệch-bias&quot;&gt;2) Độ chệch (Bias)&lt;/h2&gt;

&lt;p&gt;Độ chệch đo sai lệch có hệ thống của bộ ước lượng so với giá trị thật:&lt;/p&gt;

\[\mathrm{Bias}(\hat\theta)=\mathbb{E}[\hat\theta]-\theta\]

&lt;p&gt;Nếu \(\mathrm{Bias}(\hat\theta) = 0\), bộ ước lượng được gọi là không chệch (unbiased); nếu khác 0, bộ ước lượng có xu hướng lệch hệ thống về một phía.&lt;/p&gt;

&lt;h2 id=&quot;3-phương-sai-variance-của-bộ-ước-lượng&quot;&gt;3) Phương sai (Variance) của bộ ước lượng&lt;/h2&gt;

&lt;p&gt;Ngay cả một bộ ước lượng không chệch vẫn có thể dao động mạnh từ mẫu này sang mẫu khác. Mức độ dao động đó được đo bằng phương sai \(\mathrm{Var}(\hat\theta)\). Vì vậy, một bộ ước lượng tốt không chỉ cần ít chệch mà còn cần phương sai đủ nhỏ.&lt;/p&gt;

&lt;h2 id=&quot;4-mse-và-phân-rã-độ-chệch--phương-sai&quot;&gt;4) MSE và phân rã độ chệch – phương sai&lt;/h2&gt;

&lt;p&gt;Sai số bình phương trung bình (Mean Squared Error — MSE):&lt;/p&gt;

\[\mathrm{MSE}(\hat\theta)=\mathbb{E}[(\hat\theta-\theta)^2]\]

&lt;p&gt;được phân rã thành hai thành phần:&lt;/p&gt;

\[\mathrm{MSE}(\hat\theta)=\mathrm{Bias}(\hat\theta)^2+\mathrm{Var}(\hat\theta)\]

&lt;p&gt;Đẳng thức này là nền tảng cho tư duy điều chuẩn (regularization): chấp nhận một chút độ chệch để đổi lấy mức giảm phương sai lớn hơn, qua đó hạ tổng sai số dự báo.&lt;/p&gt;

&lt;h3 id=&quot;41-một-ví-dụ-cụ-thể-về-đánh-đổi-bias--variance&quot;&gt;4.1) Một ví dụ cụ thể về đánh đổi bias – variance&lt;/h3&gt;

&lt;p&gt;Giả sử cần ước lượng tham số thật \(\theta = 10\) bằng hai bộ ước lượng:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Bộ ước lượng A không chệch (\(\mathrm{Bias}=0\)) nhưng có phương sai bằng \(9\).&lt;/li&gt;
  &lt;li&gt;Bộ ước lượng B chệch lên 1 đơn vị (\(\mathrm{Bias}=1\)) nhưng có phương sai chỉ bằng \(4\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Khi đó:&lt;/p&gt;

\[\mathrm{MSE}(A) = 0^2 + 9 = 9,
\qquad
\mathrm{MSE}(B) = 1^2 + 4 = 5.\]

&lt;p&gt;Dù có độ chệch, bộ ước lượng B vẫn đạt MSE thấp hơn vì giảm được phương sai đáng kể. Đây chính là nguyên lý đứng sau các kỹ thuật co rút (shrinkage) và điều chuẩn (regularization).&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-đánh-đổi-độ-chệch--phương-sai-biasvariance-tradeoff&quot;&gt;Video ngắn: Đánh đổi Độ chệch – Phương sai (Bias–Variance Tradeoff)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-18a-bias-variance.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): trực quan hóa 4 bia bắn (Bias/Variance thấp-cao), công thức phân rã MSE = Bias² + Variance và lý do một chút độ chệch từ Prior giúp giảm mạnh sai số dự đoán.&lt;/p&gt;

&lt;h2 id=&quot;5-tính-nhất-quán-consistency&quot;&gt;5) Tính nhất quán (Consistency)&lt;/h2&gt;

&lt;p&gt;Bộ ước lượng \(\hat\theta_n\) được gọi là nhất quán (consistent) nếu nó hội tụ theo xác suất về giá trị thật khi cỡ mẫu tiến ra vô cùng:&lt;/p&gt;

\[\hat\theta_n \xrightarrow[]{P} \theta \quad \text{khi } n\to\infty\]

&lt;p&gt;Nói đơn giản, khi lượng dữ liệu ngày càng lớn, ước lượng sẽ càng tiến sát tham số thật.&lt;/p&gt;

&lt;h2 id=&quot;6-liên-hệ-với-thống-kê-bayesian&quot;&gt;6) Liên hệ với thống kê Bayesian&lt;/h2&gt;

&lt;p&gt;Trong thống kê Bayesian, ta làm việc với toàn bộ phân phối hậu nghiệm thay vì chỉ một ước lượng điểm. Dù vậy, góc nhìn bias–variance vẫn rất hữu ích: một phân phối tiên nghiệm mạnh thường giúp giảm phương sai ước lượng nhưng có thể kéo theo độ chệch nếu tiên nghiệm đặt lệch; ngược lại, tiên nghiệm yếu ít gây chệch nhưng có thể khiến phương sai lớn khi dữ liệu còn ít.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-nghịch-lý-jamesstein--co-cụm-shrinkage-trong-bayes-phân-tầng&quot;&gt;Video ngắn: Nghịch lý James–Stein &amp;amp; Co cụm (Shrinkage) trong Bayes Phân tầng&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-18b-stein-shrinkage.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): vì sao ước lượng trung bình từng nhóm độc lập dễ quá khớp, cơ chế kéo về trung bình chung (Partial Pooling) và cầu nối tới mô hình phân tầng Bayes.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt-nhanh&quot;&gt;Tóm tắt nhanh&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Độ chệch (bias) đo sai lệch hệ thống của bộ ước lượng.&lt;/li&gt;
  &lt;li&gt;Phương sai (variance) đo độ dao động của bộ ước lượng giữa các mẫu.&lt;/li&gt;
  &lt;li&gt;\(\mathrm{MSE} = \mathrm{Bias}^2 + \mathrm{Var}\).&lt;/li&gt;
  &lt;li&gt;Tính nhất quán (consistency) mô tả sự hội tụ về giá trị thật khi cỡ mẫu lớn.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;giải-thích-khi-nào-một-ước-lượng-có-chệch-lại-đánh-bại-ước-lượng-không-chệch&quot;&gt;Giải thích: Khi nào một ước lượng “có chệch” lại đánh bại ước lượng “không chệch”?&lt;/h2&gt;

&lt;p&gt;Hãy đọc chậm bốn bước sau để thấy vì sao “không chệch” không phải lúc nào cũng là mục tiêu tối thượng:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đặt thước đo tổng sai số là MSE:&lt;/strong&gt; Một ước lượng tốt phải ở gần \(\theta\) nhất có thể về trung bình bình phương: \(\mathrm{MSE} = \mathrm{Bias}^2 + \mathrm{Var}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh MLE (không chệch) với ước lượng co cụm Bayes (có chệch nhẹ):&lt;/strong&gt; Khi \(n\) nhỏ, MLE bám sát dữ liệu nhiễu nên phương sai lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính toán cụ thể phần đánh đổi:&lt;/strong&gt; Nếu thêm một độ chệch nhỏ \(b\) (đóng góp \(b^2\) vào MSE) giúp giảm phương sai đi nhiều hơn \(b^2\), tổng MSE sẽ giảm ròng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra giới hạn \(n \to \infty\):&lt;/strong&gt; Trọng số của prior giảm theo \(1/n\), nên độ chệch tiến về 0 và tính nhất quán vẫn được bảo toàn.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-so-sánh-mle-và-posterior-mean-với-n--4&quot;&gt;Ví dụ tính toán làm từng bước: So sánh MLE và Posterior Mean với \(n = 4\)&lt;/h3&gt;

&lt;p&gt;Giả sử xác suất thật là \(\theta = 0.4\) và ta tung đồng xu \(n = 4\) lần (\(K \sim \text{Binomial}(4, 0.4)\)). So sánh hai bộ ước lượng:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;MLE (không chệch):&lt;/strong&gt; \(\hat\theta_{\text{MLE}} = K / 4\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior Mean với prior \(\text{Beta}(1, 1)\):&lt;/strong&gt; \(\hat\theta_{\text{Bayes}} = \frac{K + 1}{4 + 2} = \frac{K + 1}{6}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ta có \(\mathbb{E}[K] = 4 \times 0.4 = 1.6\) và \(\mathrm{Var}(K) = 4 \times 0.4 \times 0.6 = 0.96\). Tính tay từng thành phần:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Bộ ước lượng&lt;/th&gt;
      &lt;th&gt;Kỳ vọng \(\mathbb{E}[\hat\theta]\)&lt;/th&gt;
      &lt;th&gt;\(\mathrm{Bias}\)&lt;/th&gt;
      &lt;th&gt;\(\mathrm{Bias}^2\)&lt;/th&gt;
      &lt;th&gt;\(\mathrm{Var}(\hat\theta)\)&lt;/th&gt;
      &lt;th&gt;\(\mathrm{MSE} = \mathrm{Bias}^2 + \mathrm{Var}\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\hat\theta_{\text{MLE}} = K/4\)&lt;/td&gt;
      &lt;td&gt;\(1.6 / 4 = 0.4000\)&lt;/td&gt;
      &lt;td&gt;\(0.0000\)&lt;/td&gt;
      &lt;td&gt;\(0.0000\)&lt;/td&gt;
      &lt;td&gt;\(0.96 / 16 = 0.0600\)&lt;/td&gt;
      &lt;td&gt;\(0.0600\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\hat\theta_{\text{Bayes}} = (K+1)/6\)&lt;/td&gt;
      &lt;td&gt;\(2.6 / 6 \approx 0.4333\)&lt;/td&gt;
      &lt;td&gt;\(+0.0333\)&lt;/td&gt;
      &lt;td&gt;\(0.0011\)&lt;/td&gt;
      &lt;td&gt;\(0.96 / 36 \approx 0.0267\)&lt;/td&gt;
      &lt;td&gt;\(0.0278\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chỉ bằng cách chấp nhận độ chệch rất nhỏ (\(+0.0333\), bình phương chỉ \(0.0011\)), bộ ước lượng Bayes đã cắt giảm hơn &lt;strong&gt;một nửa&lt;/strong&gt; tổng sai số MSE (từ \(0.0600\) xuống \(0.0278\))!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nghĩ rằng ước lượng không chệch luôn tốt hơn ước lượng có chệch. Khi cỡ mẫu nhỏ hoặc số tham số lớn, phương sai mới là kẻ thù chính làm hỏng dự báo.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu tăng cỡ mẫu lên \(n = 400\), độ chệch của \(\hat\theta_{\text{Bayes}} = (K+1)/402\) chỉ còn \((161/402) - 0.4 \approx +0.0005\) — tiến sát về 0 đúng như tính nhất quán.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=6i7mqDJICzQ&quot;&gt;Unbiasedness vs consistency of estimators - an example&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Minh họa sự khác nhau giữa tính không chệch và tính nhất quán của bộ ước lượng.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qmVT35gFW-Q&quot;&gt;[Proof] MSE = Variance + Bias²&lt;/a&gt; — math et al, English. Trình bày phép chứng minh phân rã MSE thành bình phương độ chệch cộng phương sai.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vikkiwjQqfU&quot;&gt;Population and Estimated Parameters, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Giải thích mối liên hệ giữa tham số quần thể và ước lượng mẫu khi cỡ mẫu thay đổi.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Một bộ ước lượng có độ chệch nhỏ nhưng MSE lớn có thể xảy ra không? Vì sao?&lt;/li&gt;
  &lt;li&gt;Vì sao điều chuẩn (regularization) có thể cải thiện chất lượng dự báo dù làm xuất hiện độ chệch?&lt;/li&gt;
  &lt;li&gt;Tính nhất quán có bảo đảm bộ ước lượng hoạt động tốt trên mẫu nhỏ không?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Casella, G., &amp;amp; Berger, R. (2002). &lt;em&gt;Statistical Inference&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Hastie, T., Tibshirani, R., &amp;amp; Friedman, J. (2009). &lt;em&gt;The Elements of Statistical Learning&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_17_log_probability_numerical_stability/&quot;&gt;0.19 Log-probability và Ổn định số&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.17: Sampling Distribution và Standard Error</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_15_sampling_distribution_standard_error/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_15_sampling_distribution_standard_error</id>
   <content type="html">&lt;p&gt;Đầu thế kỷ 20, William Sealy Gosset làm việc tại nhà máy bia Guinness ở Dublin với một bài toán hết sức thực tế: ông chỉ có thể thử nghiệm trên vài mẻ lúa mạch nhỏ, nhưng vẫn cần biết trung bình mẫu của mình dao động mạnh đến mức nào nếu lặp lại thí nghiệm. Công trình ký bút danh “Student” của ông đã làm rõ khái niệm &lt;strong&gt;phân phối lấy mẫu (sampling distribution)&lt;/strong&gt; — chiếc cầu nối giữa một mẫu hữu hạn ta cầm trên tay và quần thể ẩn phía sau.&lt;/p&gt;

&lt;p&gt;Dù thống kê Bayes sử dụng phân phối hậu nghiệm thay cho phân phối lấy mẫu tần suất để suy luận trực tiếp về tham số, việc hiểu rạch ròi sự khác biệt giữa độ lệch chuẩn của dữ liệu (SD), sai số chuẩn của ước lượng (SE) và độ lệch chuẩn hậu nghiệm là điều kiện bắt buộc để đọc đúng mọi bảng kết quả thống kê.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ phân biệt rõ phân phối của dữ liệu gốc với phân phối của ước lượng, hiểu sai số chuẩn (standard error) là độ bất định của bộ ước lượng chứ không phải độ phân tán của dữ liệu, và vận dụng trực giác này để đọc kết quả suy luận thống kê chính xác hơn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-biến-thiên-dữ-liệu-phân-phối-lấy-mẫu-và-độ-bất-định-ước-lượng&quot;&gt;Kiến thức cần nhớ: Biến thiên dữ liệu, Phân phối lấy mẫu và Độ bất định ước lượng&lt;/h2&gt;

&lt;p&gt;Để không bao giờ nhầm lẫn giữa các loại “độ lệch chuẩn” trong thống kê, hãy đặt bài học này trên ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thống kê mẫu như biến ngẫu nhiên (Sampling Distribution):&lt;/strong&gt; Một thống kê như \(\bar X\) hay \(\hat p\) là hàm của dữ liệu ngẫu nhiên, nên bản thân nó cũng có phân phối xác suất riêng khi lặp lại quá trình lấy mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ lệch chuẩn (SD) so với Sai số chuẩn (SE):&lt;/strong&gt; SD đo mức độ phân tán giữa &lt;em&gt;các cá thể&lt;/em&gt; trong dữ liệu (\(\sigma\)), còn SE đo mức độ dao động của &lt;em&gt;bản thân ước lượng&lt;/em&gt; qua các lần lấy mẫu lặp lại (\(\sigma/\sqrt{n}\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Thống kê Bayes:&lt;/strong&gt; Trong Bayes, ta không cần giả định lấy mẫu lặp vô hạn để đo bất định của tham số; thay vào đó, ta đọc trực tiếp độ lệch chuẩn hậu nghiệm \(\mathrm{SD}(\theta \mid y)\) và sai số chuẩn Monte Carlo (MCSE) của chuỗi MCMC — hai đại lượng song hành với tư duy SE nhưng trả lời trực tiếp câu hỏi về tham số.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-từ-một-mẫu-dữ-liệu-đến-độ-ổn-định-của-ước-lượng&quot;&gt;Giới thiệu: Từ một mẫu dữ liệu đến độ ổn định của ước lượng&lt;/h2&gt;

&lt;p&gt;Trong thực tế, ta thường chỉ quan sát được một mẫu dữ liệu duy nhất, nhưng vẫn cần đánh giá: “nếu lặp lại quy trình lấy mẫu nhiều lần, ước lượng hiện tại sẽ dao động mạnh đến mức nào?” Phân phối lấy mẫu (sampling distribution) và sai số chuẩn (standard error) là ngôn ngữ để định lượng câu hỏi đó.&lt;/p&gt;

&lt;h2 id=&quot;1-phân-phối-lấy-mẫu-sampling-distribution-là-gì&quot;&gt;1) Phân phối lấy mẫu (Sampling distribution) là gì?&lt;/h2&gt;

&lt;p&gt;Giả sử ta lặp lại cùng một quy trình lấy mẫu nhiều lần và ở mỗi lần đều tính một ước lượng \(\hat\theta\) (chẳng hạn trung bình mẫu \(\bar X\)). Tập hợp các giá trị \(\hat\theta\) thu được qua các lần lặp tạo thành &lt;strong&gt;phân phối lấy mẫu (sampling distribution)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Điểm mấu chốt cần nhớ: phân phối lấy mẫu là phân phối của &lt;strong&gt;ước lượng&lt;/strong&gt;, không phải phân phối của từng quan sát đơn lẻ.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/sampling_distribution_n20.png&quot; alt=&quot;Sampling distribution của trung bình mẫu với n = 20&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1a: Khi cỡ mẫu còn nhỏ (\(n = 20\)), phân phối lấy mẫu của trung bình mẫu khá rộng.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-sai-số-chuẩn-standard-error--se&quot;&gt;2) Sai số chuẩn (Standard Error — SE)&lt;/h2&gt;

&lt;p&gt;Sai số chuẩn là độ lệch chuẩn của phân phối lấy mẫu:&lt;/p&gt;

\[\mathrm{SE}(\hat\theta)=\sqrt{\mathrm{Var}(\hat\theta)}\]

&lt;p&gt;Đối với trung bình mẫu:&lt;/p&gt;

\[\mathrm{SE}(\bar X)=\frac{\sigma}{\sqrt{n}}\approx\frac{s}{\sqrt{n}}\]

&lt;p&gt;Như vậy, độ lệch chuẩn (SD) của dữ liệu đo mức phân tán giữa các cá thể trong mẫu, còn sai số chuẩn (SE) đo mức độ bất định của chính ước lượng.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-sampling-distribution-và-sai-số-chuẩn&quot;&gt;Thử nghiệm: sampling distribution và sai số chuẩn&lt;/h3&gt;

&lt;p&gt;Tăng cỡ mẫu n và xem độ lệch chuẩn của trung bình mẫu giảm theo σ/√n.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;clt-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;clt&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-nhầm-lẫn-phổ-biến-sd-và-se&quot;&gt;3) Nhầm lẫn phổ biến: SD và SE&lt;/h2&gt;

&lt;p&gt;Hai tập dữ liệu có cùng độ lệch chuẩn (SD) nhưng khác cỡ mẫu sẽ có sai số chuẩn (SE) khác nhau: cỡ mẫu \(n\) càng lớn thì SE càng nhỏ và ước lượng càng ổn định; ngược lại, \(n\) càng nhỏ thì SE càng lớn và kết luận càng kém chắc chắn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/sampling_distribution_n200.png&quot; alt=&quot;Sampling distribution của trung bình mẫu với n = 200&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1b: Khi tăng cỡ mẫu lên \(n = 200\), phân phối lấy mẫu thu hẹp rõ rệt, tương ứng với sai số chuẩn nhỏ hơn.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;31-ví-dụ-phân-biệt-sd-và-se&quot;&gt;3.1) Ví dụ phân biệt SD và SE&lt;/h3&gt;

&lt;p&gt;Giả sử cân nặng của một nhóm người có độ lệch chuẩn khoảng 12 kg:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Với mẫu \(n=25\) người, sai số chuẩn của trung bình là \(12/\sqrt{25}=2.4\) kg.&lt;/li&gt;
  &lt;li&gt;Với mẫu \(n=100\) người, sai số chuẩn của trung bình là \(12/\sqrt{100}=1.2\) kg.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trong cả hai trường hợp, độ lệch chuẩn (SD) giữa các cá nhân vẫn là 12 kg; đại lượng thay đổi là độ bất định của &lt;strong&gt;ước lượng trung bình&lt;/strong&gt;. Do đó không thể dùng SD và SE thay thế cho nhau.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-độ-lệch-chuẩn-sd-vs-sai-số-chuẩn-se-hai-khái-niệm-dễ-nhầm-nhất&quot;&gt;Video ngắn: Độ lệch chuẩn (SD) vs Sai số chuẩn (SE): Hai khái niệm dễ nhầm nhất&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-17a-sd-vs-se.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): phân biệt độ phân tán dữ liệu gốc SD (không đổi khi n tăng) với độ bất định trung bình mẫu SE = SD/√n, và quy tắc tăng mẫu 4 lần để giảm sai số đi một nửa.&lt;/p&gt;

&lt;h2 id=&quot;4-liên-hệ-giữa-se-và-khoảng-bất-định&quot;&gt;4) Liên hệ giữa SE và khoảng bất định&lt;/h2&gt;

&lt;p&gt;Theo xấp xỉ chuẩn, khoảng bất định của ước lượng thường có dạng:&lt;/p&gt;

\[\hat\theta \pm c\cdot \mathrm{SE}(\hat\theta)\]

&lt;p&gt;trong đó hệ số \(c\) phụ thuộc vào mức độ tin cậy mong muốn (như 95% hay 90%). Dù khung suy luận là tần suất hay Bayesian, quy luật trực giác “SE càng lớn thì khoảng bất định càng rộng” vẫn giữ nguyên.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-khoảng-tin-cậy-ci-vs-khoảng-tin-cậy-bayes-credible-interval&quot;&gt;Video ngắn: Khoảng tin cậy (CI) vs Khoảng tin cậy Bayes (Credible Interval)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-17b-ci-vs-credible.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): trực giác mô phỏng 20 mẫu lặp lại cho CI tần suất 95% đối chiếu với xác suất hậu nghiệm trực tiếp 95% của Credible Interval trong thống kê Bayes.&lt;/p&gt;

&lt;h2 id=&quot;5-liên-hệ-với-quy-trình-bayesian&quot;&gt;5) Liên hệ với quy trình Bayesian&lt;/h2&gt;

&lt;p&gt;Trong thống kê Bayesian, độ lệch chuẩn hậu nghiệm (posterior SD) của tham số đóng vai trò tương tự SE: nó phản ánh mức độ bất định còn lại về tham số sau khi đã kết hợp thông tin tiên nghiệm với dữ liệu. Nắm vững phân phối lấy mẫu và SE giúp việc đọc các khoảng hậu nghiệm trở nên tự nhiên hơn nhiều.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt-nhanh&quot;&gt;Tóm tắt nhanh&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Phân phối lấy mẫu là phân phối của bộ ước lượng qua các lần lấy mẫu lặp lại.&lt;/li&gt;
  &lt;li&gt;Sai số chuẩn (SE) là độ lệch chuẩn của bộ ước lượng.&lt;/li&gt;
  &lt;li&gt;Độ lệch chuẩn dữ liệu (SD) và sai số chuẩn (SE) đo hai đại lượng khác nhau.&lt;/li&gt;
  &lt;li&gt;Khi cỡ mẫu tăng, SE giảm theo tỷ lệ \(1/\sqrt{n}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;giải-thích-tách-bạch-ba-tầng-độ-bất-định&quot;&gt;Giải thích: Tách bạch ba tầng độ bất định&lt;/h2&gt;

&lt;p&gt;Khi đọc một báo cáo có ghi “trung bình \(50 \pm 2\)”, hãy dừng lại và hỏi con số \(2\) đó thuộc tầng nào trong ba tầng sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tầng dữ liệu (SD = \(s\)):&lt;/strong&gt; Phản ánh khoảng chênh lệch tự nhiên giữa các cá thể. Lấy thêm dữ liệu chỉ giúp ước lượng \(s\) chính xác hơn chứ không làm \(s\) tiến về 0.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng ước lượng (SE = \(s/\sqrt{n}\)):&lt;/strong&gt; Phản ánh độ ổn định của trung bình mẫu \(\bar x\). Khi \(n\) tăng gấp 4 lần, SE giảm đi một nửa và tiến về 0 khi \(n \to \infty\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng dự báo cá thể mới:&lt;/strong&gt; Khi dự đoán một quan sát mới \(X_{\text{new}}\), độ bất định gộp cả hai nguồn: \(\sqrt{s^2 + s^2/n}\) — luôn lớn hơn hoặc bằng SD.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-khảo-sát-chiều-cao-sinh-viên&quot;&gt;Ví dụ tính toán làm từng bước: Khảo sát chiều cao sinh viên&lt;/h3&gt;

&lt;p&gt;Giả sử đo chiều cao của \(n = 36\) sinh viên, ta thu được trung bình mẫu \(\bar x = 168.0\text{ cm}\) và độ lệch chuẩn mẫu \(s = 6.0\text{ cm}\).&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Đại lượng&lt;/th&gt;
      &lt;th&gt;Công thức&lt;/th&gt;
      &lt;th&gt;Giá trị tính tay&lt;/th&gt;
      &lt;th&gt;Ý nghĩa thực tế&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Độ lệch chuẩn mẫu (SD)&lt;/td&gt;
      &lt;td&gt;\(s\)&lt;/td&gt;
      &lt;td&gt;\(6.0\text{ cm}\)&lt;/td&gt;
      &lt;td&gt;Chênh lệch điển hình giữa các sinh viên trong lớp&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Sai số chuẩn (SE)&lt;/td&gt;
      &lt;td&gt;\(s / \sqrt{n}\)&lt;/td&gt;
      &lt;td&gt;\(6.0 / \sqrt{36} = 1.0\text{ cm}\)&lt;/td&gt;
      &lt;td&gt;Độ dao động dự kiến của trung bình mẫu \(\bar x\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Biên sai số 95% của \(\bar x\)&lt;/td&gt;
      &lt;td&gt;\(1.96 \times \mathrm{SE}\)&lt;/td&gt;
      &lt;td&gt;\(1.96 \times 1.0 = 1.96\text{ cm}\)&lt;/td&gt;
      &lt;td&gt;Khoảng tin cậy 95% cho chiều cao trung bình: \([166.04,\; 169.96]\text{ cm}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhìn thấy khoảng \(168.0 \pm 1.96\text{ cm}\) rồi kết luận “95% sinh viên cao từ 166 cm đến 170 cm”. Thực tế đó là khoảng bất định cho &lt;em&gt;trung bình quần thể&lt;/em&gt;, còn 95% sinh viên cá lẻ sẽ trải rộng quanh \(\bar x \pm 1.96 s \approx [156.2,\; 179.8]\text{ cm}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu tăng cỡ mẫu từ \(n = 36\) lên \(n = 144\) (gấp 4 lần), SD vẫn xoay quanh \(6.0\text{ cm}\), còn SE giảm một nửa từ \(1.0\text{ cm}\) xuống \(6.0 / \sqrt{144} = 0.5\text{ cm}\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=A82brFpdr9g&quot;&gt;Standard Deviation vs Standard Error, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Phân biệt rõ độ phân tán của dữ liệu (SD) với độ bất định của ước lượng (SE).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Introduction to sampling distributions&lt;/td&gt;
          &lt;td&gt;Sampling distributions&lt;/td&gt;
          &lt;td&gt;AP Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=z0Ry_3_qhDw) — Khan Academy, English. Giới thiệu khái niệm phân phối lấy mẫu của một thống kê khi lặp lại quy trình lấy mẫu.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Standard error of the mean&lt;/td&gt;
          &lt;td&gt;Inferential statistics&lt;/td&gt;
          &lt;td&gt;Probability and Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=J1twbrHel3o) — Khan Academy, English. Giải thích cách sai số chuẩn của trung bình mẫu thu nhỏ khi cỡ mẫu tăng.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Giải thích vì sao SD lớn không nhất thiết kéo theo SE lớn trong mọi trường hợp.&lt;/li&gt;
  &lt;li&gt;Nếu tăng cỡ mẫu từ 100 lên 400, sai số chuẩn thay đổi ra sao?&lt;/li&gt;
  &lt;li&gt;Phân phối lấy mẫu của trung vị (median) có giống phân phối lấy mẫu của trung bình (mean) không? Vì sao?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Rice, J. (2006). &lt;em&gt;Mathematical Statistics and Data Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Wasserman, L. (2004). &lt;em&gt;All of Statistics&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_16_point_estimation_bias_variance_consistency/&quot;&gt;0.18 Ước lượng điểm, Bias-Variance, Consistency&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.16: Luật số lớn và Định lý giới hạn trung tâm</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_14_law_large_numbers_clt/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_14_law_large_numbers_clt</id>
   <content type="html">&lt;p&gt;Cuối thế kỷ 17, Jacob Bernoulli tự hỏi một câu vừa giản dị vừa sâu sắc: nếu một biến cố có xác suất thật \(p\) ẩn giấu sau màn sương ngẫu nhiên, liệu ta có thể “nhìn thấy” \(p\) chỉ bằng cách lặp đi lặp lại thí nghiệm đủ nhiều lần? Ông mất hơn hai mươi năm để chứng minh câu trả lời — Luật số lớn. Một thế kỷ sau, Pierre-Simon Laplace và Abraham de Moivre còn đi xa hơn: không chỉ biết trung bình mẫu tiến về đâu, họ phát hiện mọi dao động quanh điểm hội tụ đó đều mang chung một hình bóng kỳ lạ — đường cong chuông chuẩn.&lt;/p&gt;

&lt;p&gt;Trong thống kê Bayes hiện đại, hai định lý kinh điển này là xương sống của &lt;strong&gt;phương pháp Monte Carlo và MCMC&lt;/strong&gt;: mỗi khi ta rút hàng nghìn mẫu từ phân phối hậu nghiệm, chính Luật số lớn đảm bảo trung bình mẫu hội tụ về kỳ vọng hậu nghiệm, còn Định lý giới hạn trung tâm cho phép đo chính xác sai số tính toán (MCSE).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu vì sao trung bình mẫu trở nên ổn định khi cỡ mẫu tăng lên (Luật số lớn — LLN), vì sao tổng hoặc trung bình của nhiều biến ngẫu nhiên có xu hướng tiến gần phân phối chuẩn (Định lý giới hạn trung tâm — CLT), và vì sao hai định lý này là nền tảng cho mô phỏng, ước lượng và kiểm định thống kê.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hội-tụ-xác-suất-phân-phối-tiệm-cận-và-monte-carlo-bayes-gặp-nhau-ở-đâu&quot;&gt;Kiến thức cần nhớ: Hội tụ xác suất, Phân phối tiệm cận và Monte Carlo Bayes gặp nhau ở đâu?&lt;/h2&gt;

&lt;p&gt;Để hiểu hai định lý này ở tầm đại học – sau đại học thay vì chỉ thuộc phát biểu, hãy đặt chúng trên ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết hội tụ của biến ngẫu nhiên (Convergence Modes):&lt;/strong&gt; Luật số lớn yếu (WLLN) phát biểu sự hội tụ theo xác suất (\(\bar X_n \xrightarrow{P} \mu\)), còn Luật số lớn mạnh (SLLN) phát biểu hội tụ hầu chắc chắn (\(\bar X_n \xrightarrow{\text{a.s.}} \mu\)). Đây là cơ sở lý thuyết giải thích vì sao ước lượng trung bình không bị trôi vô định khi cỡ mẫu tăng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tiệm cận phân phối (Asymptotic Distribution &amp;amp; CLT):&lt;/strong&gt; Định lý giới hạn trung tâm mô tả hội tụ theo phân phối của đại lượng chuẩn hóa \(\sqrt{n}(\bar X_n - \mu)/\sigma \xrightarrow{d} \mathcal{N}(0,1)\). Điều kỳ diệu là tính chuẩn tiệm cận không đòi hỏi dữ liệu gốc phải chuẩn, miễn phương sai hữu hạn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Thống kê Bayes &amp;amp; MCMC:&lt;/strong&gt; Trong thực hành Bayes, tích phân hậu nghiệm \(\mathbb{E}[g(\theta) \mid y]\) thường không có công thức đóng. Ta thay tích phân bằng trung bình mẫu \(\frac{1}{S}\sum_{s=1}^S g(\theta^{(s)})\) (nhờ LLN / định lý Ergodic cho chuỗi Markov) và đánh giá sai số chuẩn Monte Carlo \(\text{MCSE} = \hat{\sigma}_g / \sqrt{S_{\text{eff}}}\) (nhờ CLT).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-vì-sao-ngẫu-nhiên-vẫn-tạo-ra-quy-luật-ổn-định&quot;&gt;Giới thiệu: Vì sao ngẫu nhiên vẫn tạo ra quy luật ổn định?&lt;/h2&gt;

&lt;p&gt;Một ý tưởng trung tâm của thống kê là từng quan sát đơn lẻ có thể nhiễu mạnh, nhưng khi gộp đủ nhiều quan sát, các quy luật ổn định lại hiện ra rõ rệt. Luật số lớn (LLN) và Định lý giới hạn trung tâm (CLT) mô tả chính xác hai khía cạnh của hiện tượng này, đồng thời giải thích vì sao có thể dùng ước lượng mẫu để suy luận về quần thể.&lt;/p&gt;

&lt;h2 id=&quot;1-luật-số-lớn-lln-trung-bình-mẫu-hội-tụ&quot;&gt;1) Luật số lớn (LLN): Trung bình mẫu hội tụ&lt;/h2&gt;

&lt;p&gt;Cho \(X_1,\dots,X_n\) là các biến ngẫu nhiên độc lập, cùng phân phối (i.i.d.) với kỳ vọng hữu hạn \(\mu\). Xét trung bình mẫu:&lt;/p&gt;

\[\bar X_n = \frac{1}{n}\sum_{i=1}^n X_i\]

&lt;p&gt;Luật số lớn khẳng định rằng khi \(n\to\infty\), \(\bar X_n\) hội tụ về \(\mu\) (theo xác suất). Về mặt trực giác, các sai lệch ngẫu nhiên dương và âm dần bù trừ cho nhau khi ta lấy trung bình trên số lượng quan sát ngày càng lớn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/lln_running_mean_convergence.png&quot; alt=&quot;Trung bình chạy hội tụ dần về kỳ vọng&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1a: Luật số lớn cho thấy trung bình trượt (running mean) dần ổn định và hội tụ về kỳ vọng thật khi số quan sát tăng.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-luật-số-lớn&quot;&gt;Thử nghiệm: luật số lớn&lt;/h3&gt;

&lt;p&gt;Trung bình chạy của năm chuỗi mô phỏng hội tụ về μ.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;clt-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;lln&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;video-ngắn-luật-số-lớn-lln-từ-tung-đồng-xu-đến-hội-tụ-mcmc&quot;&gt;Video ngắn: Luật Số Lớn (LLN): Từ Tung đồng xu đến Hội tụ MCMC&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-16a-law-large-numbers.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): 3 chuỗi tung xu độc lập hội tụ về p = 0.5, bẫy ngụy biện con bạc, phản ví dụ Cauchy và định lý Ergodic cho chuỗi MCMC.&lt;/p&gt;

&lt;h2 id=&quot;2-định-lý-giới-hạn-trung-tâm-clt-phân-phối-của-trung-bình-mẫu-gần-chuẩn&quot;&gt;2) Định lý giới hạn trung tâm (CLT): Phân phối của trung bình mẫu gần chuẩn&lt;/h2&gt;

&lt;p&gt;Với điều kiện phương sai \(\sigma^2\) hữu hạn, ta có hội tụ theo phân phối:&lt;/p&gt;

\[\frac{\bar X_n-\mu}{\sigma/\sqrt{n}} \Rightarrow \mathcal N(0,1)\]

&lt;p&gt;Hệ quả thực hành khi \(n\) đủ lớn là:&lt;/p&gt;

\[\bar X_n \approx \mathcal N\left(\mu,\frac{\sigma^2}{n}\right)\]

&lt;p&gt;ngay cả khi phân phối gốc của từng quan sát \(X_i\) không phải phân phối chuẩn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/clt_sample_means_histogram.png&quot; alt=&quot;Phân phối của trung bình mẫu gần chuẩn&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1b: Định lý giới hạn trung tâm cho thấy phân phối của trung bình mẫu tiến gần dạng chuẩn dù phân phối gốc không nhất thiết chuẩn.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-định-lý-giới-hạn-trung-tâm&quot;&gt;Thử nghiệm: định lý giới hạn trung tâm&lt;/h3&gt;

&lt;p&gt;Histogram của trung bình mẫu tiến tới phân phối chuẩn khi n tăng, dù phân phối gốc lệch.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;clt-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;clt&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;video-ngắn-clt--sai-số-chuẩn-monte-carlo-cần-bao-nhiêu-mẫu-mcmc-là-đủ&quot;&gt;Video ngắn: CLT &amp;amp; Sai số chuẩn Monte Carlo: Cần bao nhiêu mẫu MCMC là đủ?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-16b-clt-mcse-error.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): thu hẹp chuông trung bình mẫu từ n = 4 → 16 → 64 theo quy luật 1/√n, công thức MCSE = SD/√ESS và cách đọc bảng chẩn đoán ArviZ.&lt;/p&gt;

&lt;h2 id=&quot;3-lln-và-clt-khác-nhau-ở-điểm-nào&quot;&gt;3) LLN và CLT khác nhau ở điểm nào?&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;LLN&lt;/strong&gt; trả lời câu hỏi trung bình mẫu có hội tụ về giá trị thật hay không, còn &lt;strong&gt;CLT&lt;/strong&gt; mô tả tốc độ hội tụ và hình dạng độ bất định quanh giá trị thật đó. Nói ngắn gọn, LLN giải thích “hội tụ về đâu”, còn CLT giải thích “dao động ra sao quanh điểm hội tụ”.&lt;/p&gt;

&lt;h2 id=&quot;4-liên-hệ-với-sai-số-chuẩn&quot;&gt;4) Liên hệ với sai số chuẩn&lt;/h2&gt;

&lt;p&gt;Từ CLT, độ rộng dao động của \(\bar X_n\) tỷ lệ với \(1/\sqrt{n}\). Vì vậy sai số chuẩn giảm chậm theo cỡ mẫu: muốn giảm sai số đi một nửa, cần tăng cỡ mẫu lên khoảng 4 lần. Đây là nguyên tắc quan trọng khi thiết kế thí nghiệm và đánh giá độ chính xác của ước lượng.&lt;/p&gt;

&lt;h3 id=&quot;41-một-ví-dụ-bằng-con-số-tăng-cỡ-mẫu-4-lần-thì-sao&quot;&gt;4.1) Một ví dụ bằng con số: Tăng cỡ mẫu 4 lần thì sao?&lt;/h3&gt;

&lt;p&gt;Giả sử ta ước lượng một tỷ lệ thật quanh mức \(0.6\). Sai số chuẩn của tần suất mẫu xấp xỉ:&lt;/p&gt;

\[\mathrm{SE}(\hat p)\approx \sqrt{\frac{0.6\times 0.4}{n}}.\]

&lt;ul&gt;
  &lt;li&gt;Với \(n=25\), \(\mathrm{SE}\approx 0.098\).&lt;/li&gt;
  &lt;li&gt;Với \(n=100\), \(\mathrm{SE}\approx 0.049\).&lt;/li&gt;
  &lt;li&gt;Với \(n=400\), \(\mathrm{SE}\approx 0.024\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Khi tăng cỡ mẫu từ 25 lên 100 rồi lên 400 (mỗi bước gấp 4 lần), sai số chuẩn giảm đi một nửa mỗi lần, thay vì giảm tỷ lệ thuận với \(n\). Ví dụ này minh họa trực tiếp quy luật \(1/\sqrt{n}\) trong thực hành.&lt;/p&gt;

&lt;h2 id=&quot;5-liên-hệ-với-thống-kê-bayesian-và-mô-phỏng&quot;&gt;5) Liên hệ với thống kê Bayesian và mô phỏng&lt;/h2&gt;

&lt;p&gt;Trong thống kê Bayesian, các ước lượng Monte Carlo cũng dựa trên trung bình mẫu: số lượng mẫu rút từ phân phối hậu nghiệm càng lớn thì ước lượng càng ổn định, và nhiều tiêu chí đánh giá độ bất định tính toán (như sai số chuẩn Monte Carlo) đều bắt nguồn từ trực giác của LLN và CLT.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt-nhanh&quot;&gt;Tóm tắt nhanh&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;LLN: trung bình mẫu hội tụ về kỳ vọng thật khi cỡ mẫu tăng.&lt;/li&gt;
  &lt;li&gt;CLT: phân phối của trung bình mẫu tiến gần phân phối chuẩn với phương sai \(\sigma^2/n\).&lt;/li&gt;
  &lt;li&gt;LLN nói về điểm hội tụ; CLT nói về hình dạng và độ rộng dao động quanh điểm đó.&lt;/li&gt;
  &lt;li&gt;Cả hai định lý là nền tảng cho suy luận thống kê và phương pháp mô phỏng.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;giải-thích-bốn-bước-đọc-tốc-độ-hội-tụ-và-sai-số-chuẩn&quot;&gt;Giải thích: Bốn bước đọc tốc độ hội tụ và sai số chuẩn&lt;/h2&gt;

&lt;p&gt;Nhiều người học nhớ mang máng “cỡ mẫu lớn thì chính xác hơn”, nhưng lại lúng túng khi phải định lượng &lt;em&gt;cần bao nhiêu mẫu là đủ&lt;/em&gt;. Hãy đọc chậm chuỗi bốn bước sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Xác định kỳ vọng và độ lệch chuẩn của một quan sát đơn lẻ (\(\mu, \sigma\)):&lt;/strong&gt; Một mẫu đơn lẻ \(X_i\) có độ bất định bằng \(\sigma\) — con số này phản ánh bản chất biến thiên của dữ liệu và không giảm khi lấy thêm mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính kỳ vọng và độ lệch chuẩn của trung bình mẫu (\(\bar X_n\)):&lt;/strong&gt; Trung bình mẫu vẫn có kỳ vọng \(\mu\), nhưng phương sai giảm theo tỷ lệ \(1/n\) thành \(\sigma^2/n\), kéo theo sai số chuẩn \(\mathrm{SE} = \sigma/\sqrt{n}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp dụng xấp xỉ chuẩn CLT:&lt;/strong&gt; Khi \(n\) đủ lớn, khoảng \(\mu \pm 1.96\,\sigma/\sqrt{n}\) chứa xấp xỉ \(95\%\) các giá trị khả dĩ của \(\bar X_n\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh đổi chi phí – độ chính xác:&lt;/strong&gt; Vì căn bậc hai \(\sqrt{n}\) tăng chậm, muốn giảm một nửa bề rộng sai số phải tăng cỡ mẫu gấp \(4\) lần; muốn giảm \(10\) lần phải tăng cỡ mẫu gấp \(100\) lần.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-ước-lượng-thời-gian-phản-hồi-máy-chủ-lệch-phải&quot;&gt;Ví dụ tính toán làm từng bước: Ước lượng thời gian phản hồi máy chủ lệch phải&lt;/h3&gt;

&lt;p&gt;Giả sử thời gian phản hồi của một API tuân theo phân phối mũ (rất lệch phải, hoàn toàn không phải phân phối chuẩn) với trung bình thật \(\mu = 200\text{ ms}\) và độ lệch chuẩn \(\sigma = 200\text{ ms}\). Ta lấy mẫu \(n\) yêu cầu độc lập và tính trung bình mẫu \(\bar X_n\).&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Cỡ mẫu \(n\)&lt;/th&gt;
      &lt;th&gt;Kỳ vọng \(\mathbb{E}[\bar X_n]\)&lt;/th&gt;
      &lt;th&gt;Sai số chuẩn \(\mathrm{SE} = 200/\sqrt{n}\)&lt;/th&gt;
      &lt;th&gt;Khoảng 95% theo CLT (\(\mu \pm 1.96\,\mathrm{SE}\))&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(n = 25\)&lt;/td&gt;
      &lt;td&gt;\(200\text{ ms}\)&lt;/td&gt;
      &lt;td&gt;\(200 / 5 = 40.0\text{ ms}\)&lt;/td&gt;
      &lt;td&gt;\([121.6,\; 278.4]\text{ ms}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(n = 100\)&lt;/td&gt;
      &lt;td&gt;\(200\text{ ms}\)&lt;/td&gt;
      &lt;td&gt;\(200 / 10 = 20.0\text{ ms}\)&lt;/td&gt;
      &lt;td&gt;\([160.8,\; 239.2]\text{ ms}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(n = 400\)&lt;/td&gt;
      &lt;td&gt;\(200\text{ ms}\)&lt;/td&gt;
      &lt;td&gt;\(200 / 20 = 10.0\text{ ms}\)&lt;/td&gt;
      &lt;td&gt;\([180.4,\; 219.6]\text{ ms}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Ta tính thử xác suất \(\bar X_{100}\) vượt quá \(230\text{ ms}\) theo CLT:&lt;/p&gt;

\[z = \frac{230 - 200}{20} = 1.5 \implies P(\bar X_{100} &amp;gt; 230) \approx 1 - \Phi(1.5) \approx 1 - 0.9332 = 0.0668 \quad (6.68\%).\]

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nghĩ rằng CLT làm cho &lt;em&gt;từng quan sát&lt;/em&gt; \(X_i\) trở thành phân phối chuẩn khi \(n\) lớn. Thực tế dữ liệu gốc vẫn lệch phải (vẫn là phân phối mũ); chỉ có phân phối của &lt;strong&gt;trung bình mẫu&lt;/strong&gt; \(\bar X_n\) mới tiến gần dạng chuông chuẩn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu muốn sai số chuẩn của \(\bar X_n\) giảm xuống đúng \(5\text{ ms}\), ta giải \(200/\sqrt{n} = 5 \implies \sqrt{n} = 40 \implies n = 1600\) yêu cầu.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=MntX3zWNWec&quot;&gt;Law of Large Numbers - Explained and Visualized&lt;/a&gt; — Jeremy Blitz-Jones, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Trực quan hóa cách trung bình mẫu ổn định dần khi số quan sát tăng lên.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zeJD6dqJ5lo&quot;&gt;But what is the Central Limit Theorem?&lt;/a&gt; — 3Blue1Brown, English. Giải thích vì sao phân phối của trung bình mẫu tiến dần về dạng chuông chuẩn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Sm2yBx3Jn6c&quot;&gt;Định lý giới hạn trung tâm (Central limit theorem)&lt;/a&gt; — Bài Học 10 Phút, Tiếng Việt. Tóm tắt ngắn gọn bằng tiếng Việt để đối chiếu với các nội dung về ước lượng và mô phỏng trong bài.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao chỉ riêng Luật số lớn không đủ để xây dựng khoảng bất định cho \(\bar X_n\)?&lt;/li&gt;
  &lt;li&gt;Giải thích bằng lời vì sao sai số chuẩn giảm theo tỷ lệ \(1/\sqrt{n}\).&lt;/li&gt;
  &lt;li&gt;Định lý giới hạn trung tâm có đòi hỏi dữ liệu gốc phải tuân theo phân phối chuẩn không?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Casella, G., &amp;amp; Berger, R. (2002). &lt;em&gt;Statistical Inference&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Wasserman, L. (2004). &lt;em&gt;All of Statistics&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_15_sampling_distribution_standard_error/&quot;&gt;0.17 Sampling Distribution và Standard Error&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.15: Kỳ vọng, Phương sai, và Hiệp phương sai</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_13_expectation_variance_covariance/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_13_expectation_variance_covariance</id>
   <content type="html">&lt;p&gt;Nếu hai cổ phiếu mỗi mã đều có độ lệch chuẩn 10%, thì độ lệch chuẩn của tổng hai cổ phiếu đó bằng bao nhiêu? Nhiều người phản xạ trả lời 20% — nhưng tùy vào &lt;strong&gt;hiệp phương sai (covariance)&lt;/strong&gt; giữa chúng, đáp án thực tế có thể nằm bất kỳ đâu từ &lt;strong&gt;0%&lt;/strong&gt; (tương quan âm hoàn hảo — triệt tiêu rủi ro!) cho tới &lt;strong&gt;20%&lt;/strong&gt; (tương quan dương hoàn hảo)! Làm chủ kỳ vọng, phương sai và hiệp phương sai là chìa khóa để hiểu cả rủi ro danh mục lẫn &lt;strong&gt;độ bất định tương quan giữa các tham số trong hậu nghiệm Bayes&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Bài học này rèn luyện thành phản xạ các quy tắc tuyến tính của kỳ vọng, công thức phương sai của tổng và ý nghĩa hình học của hiệp phương sai / hệ số tương quan.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-đồng-nhất-thức-moment-trụ-cột-trong-thống-kê-bayes&quot;&gt;Kiến thức cần nhớ: Bốn đồng nhất thức Moment trụ cột trong Thống kê Bayes&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính tuyến tính của Kỳ vọng (Luôn đúng mọi lúc!):&lt;/strong&gt; \(\mathbb{E}[aX + bY + c] = a\mathbb{E}[X] + b\mathbb{E}[Y] + c\) đúng &lt;strong&gt;kể cả khi \(X\) và \(Y\) phụ thuộc chặt vào nhau&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy tắc biến đổi &amp;amp; tổng Phương sai:&lt;/strong&gt; \(\mathrm{Var}(aX + b) = a^2\mathrm{Var}(X)\), và với hai biến bất kỳ: \(\mathrm{Var}(X + Y) = \mathrm{Var}(X) + \mathrm{Var}(Y) + 2\mathrm{Cov}(X, Y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệp phương sai &amp;amp; Tương quan không thứ nguyên:&lt;/strong&gt; \(\mathrm{Cov}(X, Y) = \mathbb{E}[XY] - \mathbb{E}[X]\mathbb{E}[Y]\) phụ thuộc đơn vị đo; chia cho \(\sigma_X\sigma_Y\) cho hệ số tương quan \(\rho \in [-1, 1]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Định luật Phương sai Toàn phần (Nền tảng Bayes phân cấp):&lt;/strong&gt; \(\mathrm{Var}(Y) = \mathbb{E}[\mathrm{Var}(Y\mid\theta)] + \mathrm{Var}(\mathbb{E}[Y\mid\theta])\) tách tổng bất định dự báo thành &lt;em&gt;nhiễu nội tại&lt;/em&gt; cộng &lt;em&gt;bất định tham số&lt;/em&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu kỳ vọng như “giá trị trung bình dài hạn”, phương sai như “độ phân tán quanh trung bình”, hiệp phương sai như “mức độ biến thiên cùng chiều hay ngược chiều” giữa hai biến, và nắm rõ vì sao ba đại lượng này xuất hiện xuyên suốt trong các mô hình Bayesian.&lt;/p&gt;

&lt;h2 id=&quot;giới-thiệu-ba-đại-lượng-mô-tả-trung-tâm-và-độ-bất-định&quot;&gt;Giới thiệu: Ba đại lượng mô tả trung tâm và độ bất định&lt;/h2&gt;

&lt;p&gt;Trong suy luận xác suất, không phải lúc nào ta cũng cần đọc toàn bộ dạng chi tiết của phân phối. Nhiều câu hỏi thực hành bắt đầu từ ba đặc trưng cơ bản: giá trị điển hình nằm ở đâu, mức dao động lớn đến mức nào, và các biến có biến thiên cùng nhau hay không. Kỳ vọng, phương sai và hiệp phương sai trả lời trực tiếp ba câu hỏi đó.&lt;/p&gt;

&lt;h2 id=&quot;1-kỳ-vọng-giá-trị-trung-bình-theo-phân-phối&quot;&gt;1) Kỳ vọng: Giá trị trung bình theo phân phối&lt;/h2&gt;

&lt;p&gt;Với biến ngẫu nhiên rời rạc:&lt;/p&gt;

\[\mathbb{E}[X] = \sum_x x\,p(x)\]

&lt;p&gt;Với biến ngẫu nhiên liên tục:&lt;/p&gt;

\[\mathbb{E}[X] = \int x f(x)\,dx\]

&lt;p&gt;Kỳ vọng không nhất thiết là giá trị xuất hiện nhiều nhất; nó đóng vai trò như “trọng tâm xác suất” của phân phối.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/expectation_center_histogram.png&quot; alt=&quot;Kỳ vọng như trọng tâm của phân phối&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1a: Kỳ vọng có thể được nhìn như trọng tâm của phân phối, không nhất thiết trùng với đỉnh cao nhất của histogram.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-phương-sai-độ-bất-định-quanh-trung-bình&quot;&gt;2) Phương sai: Độ bất định quanh trung bình&lt;/h2&gt;

&lt;p&gt;Phương sai được định nghĩa là kỳ vọng của bình phương độ lệch so với trung bình:&lt;/p&gt;

\[\mathrm{Var}(X)=\mathbb{E}\big[(X-\mathbb{E}[X])^2\big]\]

&lt;p&gt;Dạng khai triển thuận tiện khi tính toán:&lt;/p&gt;

\[\mathrm{Var}(X)=\mathbb{E}[X^2]-\mathbb{E}[X]^2\]

&lt;p&gt;Độ lệch chuẩn là căn bậc hai của phương sai:&lt;/p&gt;

\[\mathrm{SD}(X)=\sqrt{\mathrm{Var}(X)}\]

&lt;p&gt;Về trực giác, phương sai lớn cho thấy các giá trị phân tán rộng, còn phương sai nhỏ cho thấy phân phối tập trung chặt quanh kỳ vọng.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-tính-tuyến-tính-của-kỳ-vọng--phương-sai-tổng-hai-cổ-phiếu&quot;&gt;Video ngắn: Tính tuyến tính của Kỳ vọng &amp;amp; Phương sai Tổng hai Cổ phiếu&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-15a-linearity-sum-variance.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): trượt tương quan ρ từ +1 → 0 → −1 xem SD(X+Y) thay đổi từ 20% về 0%, tính tuyến tính kỳ vọng, số hạng chéo +2Cov và dự báo hồi quy Bayes.&lt;/p&gt;

&lt;h2 id=&quot;3-hiệp-phương-sai-mức-độ-cùng-biến-thiên&quot;&gt;3) Hiệp phương sai: Mức độ cùng biến thiên&lt;/h2&gt;

&lt;p&gt;Với hai biến ngẫu nhiên \(X\) và \(Y\), hiệp phương sai được định nghĩa là:&lt;/p&gt;

\[\mathrm{Cov}(X,Y)=\mathbb{E}\big[(X-\mathbb{E}[X])(Y-\mathbb{E}[Y])\big]\]

&lt;p&gt;Khi \(\mathrm{Cov}(X,Y) &amp;gt; 0\), hai biến có xu hướng cùng tăng hoặc cùng giảm; khi \(\mathrm{Cov}(X,Y) &amp;lt; 0\), biến này tăng thì biến kia có xu hướng giảm; còn khi hiệp phương sai gần 0, mối liên hệ tuyến tính giữa chúng yếu hoặc không đáng kể.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/covariance_positive_scatter.png&quot; alt=&quot;Hiệp phương sai dương giữa hai biến&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1b: Hiệp phương sai dương xuất hiện khi hai biến có xu hướng tăng cùng nhau.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/covariance_negative_scatter.png&quot; alt=&quot;Hiệp phương sai âm giữa hai biến&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1c: Hiệp phương sai âm xuất hiện khi một biến tăng thì biến kia có xu hướng giảm.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Lưu ý rằng hiệp phương sai phụ thuộc vào đơn vị đo của các biến. Để so sánh không phụ thuộc thang đo, thực hành thường chuẩn hóa thành hệ số tương quan:&lt;/p&gt;

\[\rho_{XY}=\frac{\mathrm{Cov}(X,Y)}{\mathrm{SD}(X)\mathrm{SD}(Y)}\]

&lt;h3 id=&quot;31-một-ví-dụ-ngắn-trong-quyết-định-hằng-ngày&quot;&gt;3.1) Một ví dụ ngắn trong quyết định hằng ngày&lt;/h3&gt;

&lt;p&gt;Giả sử hai tuyến xe buýt đều có thời gian di chuyển kỳ vọng là 30 phút:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Tuyến A thường mất quanh mức \(28, 30, 32\) phút.&lt;/li&gt;
  &lt;li&gt;Tuyến B thường dao động quanh mức \(20, 30, 40\) phút.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Dù cùng kỳ vọng, tuyến B có phương sai lớn hơn nhiều nên rủi ro đến trễ cao hơn hẳn. Nếu nhận thấy những ngày mưa lớn thời gian di chuyển cũng kéo dài hơn, đó chính là hiệp phương sai dương giữa lượng mưa và thời gian đi lại. Ví dụ này cho thấy chỉ xem trung bình là chưa đủ; quyết định thực tế phụ thuộc cả vào độ phân tán và mối liên hệ giữa các biến.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-hiệp-phương-sai-tương-quan--định-luật-phương-sai-toàn-phần&quot;&gt;Video ngắn: Hiệp phương sai, Tương quan &amp;amp; Định luật Phương sai Toàn phần&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-15b-covariance-total-variance.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): hình học 4 góc phần tư của Cov(X,Y), chuẩn hóa ρ ∈ [−1, 1], tách bất định Aleatoric + Epistemic qua Định luật Phương sai Toàn phần và phản ví dụ Y = X².&lt;/p&gt;

&lt;h2 id=&quot;4-các-tính-chất-cần-nhớ&quot;&gt;4) Các tính chất cần nhớ&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
\[\mathbb{E}[aX+b]=a\mathbb{E}[X]+b\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathrm{Var}(aX+b)=a^2\mathrm{Var}(X)\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathrm{Var}(X+Y)=\mathrm{Var}(X)+\mathrm{Var}(Y)+2\mathrm{Cov}(X,Y)\]
  &lt;/li&gt;
  &lt;li&gt;Nếu \(X,Y\) độc lập thì \(\mathrm{Cov}(X,Y)=0\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Lưu ý tính chất (4) chỉ đúng theo một chiều: hiệp phương sai bằng 0 chưa đủ kết luận hai biến độc lập.&lt;/p&gt;

&lt;h2 id=&quot;5-liên-hệ-với-thống-kê-bayesian&quot;&gt;5) Liên hệ với thống kê Bayesian&lt;/h2&gt;

&lt;p&gt;Trong suy diễn Bayesian, trung bình hậu nghiệm (posterior mean) chính là kỳ vọng theo phân phối hậu nghiệm; độ bất định thường được báo cáo qua độ lệch chuẩn hoặc phương sai hậu nghiệm; còn khi mô hình có nhiều tham số, ma trận hiệp phương sai hậu nghiệm cho biết mức độ phụ thuộc giữa các tham số đó. Vì vậy, nắm chắc kỳ vọng, phương sai và hiệp phương sai là điều kiện cần để diễn giải kết quả Bayesian.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt-nhanh&quot;&gt;Tóm tắt nhanh&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Kỳ vọng là trung bình có trọng số theo phân phối xác suất.&lt;/li&gt;
  &lt;li&gt;Phương sai đo mức độ phân tán quanh kỳ vọng.&lt;/li&gt;
  &lt;li&gt;Hiệp phương sai đo chiều hướng và mức độ cùng biến thiên tuyến tính của hai biến.&lt;/li&gt;
  &lt;li&gt;Ba đại lượng này là ngôn ngữ cơ bản để tóm tắt và diễn giải phân phối hậu nghiệm.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;ví-dụ-tính-tay-làm-từng-bước-kiểm-chứng-công-thức-phương-sai-của-tổng-với-hiệp-phương-sai-âm&quot;&gt;Ví dụ tính tay làm từng bước: Kiểm chứng công thức Phương sai của Tổng với Hiệp phương sai âm&lt;/h3&gt;

&lt;p&gt;Xét hai tài sản \((X, Y)\) trong 3 kịch bản thị trường có xác suất bằng nhau (mỗi kịch bản \(1/3\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Kịch bản&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Xác suất&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Lợi suất \(X\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Lợi suất \(Y\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Tổng \(X + Y\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Tăng mạnh&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1/3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+6\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+4\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Đi ngang&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1/3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Giảm mạnh&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1/3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-6\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-4\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kỳ vọng:&lt;/strong&gt; \(\mathbb{E}[X] = 0\), \(\mathbb{E}[Y] = 0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương sai từng tài sản:&lt;/strong&gt;
\(\mathrm{Var}(X) = \frac{36 + 0 + 36}{3} = 24, \qquad \mathrm{Var}(Y) = \frac{4 + 0 + 4}{3} = \frac{8}{3} \approx 2{,}67.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệp phương sai:&lt;/strong&gt;
\(\mathrm{Cov}(X, Y) = \mathbb{E}[XY] - 0 = \frac{6(-2) + 0 + (-6)(2)}{3} = \mathbf{-8}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng định luật tổng phương sai:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Theo công thức: \(\mathrm{Var}(X+Y) = 24 + \frac{8}{3} + 2(-8) = \frac{32}{3} \approx \mathbf{10{,}67}\).&lt;/li&gt;
      &lt;li&gt;Tính trực tiếp từ cột \(X+Y = (+4, 0, -4)\): \(\frac{16 + 0 + 16}{3} = \frac{32}{3} \approx \mathbf{10{,}67}\) — khớp khít tuyệt đối! Nhờ hiệp phương sai âm, rủi ro của danh mục giảm hơn một nửa so với giữ riêng \(X\)!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-bốn-lưu-ý-tránh-nhầm-lẫn-khi-tính-kỳ-vọng-và-hiệp-phương-sai&quot;&gt;Giải thích: Bốn lưu ý tránh nhầm lẫn khi tính Kỳ vọng và Hiệp phương sai&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hiệp phương sai bằng 0 KHÔNG chứng minh độc lập:&lt;/strong&gt; Nếu \(X \in \{-1, 0, 1\}\) đối xứng và \(Y = X^2\), ta có \(\mathrm{Cov}(X, Y) = 0\) dù \(Y\) phụ thuộc hoàn toàn vào \(X\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tuyệt đối không cộng độ lệch chuẩn — hãy cộng &lt;em&gt;phương sai&lt;/em&gt; (cộng \(2\mathrm{Cov}\)):&lt;/strong&gt; Cộng trực tiếp \(\sigma_X + \sigma_Y\) sẽ phóng đại sai số mỗi khi hai biến độc lập hoặc tương quan âm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trong hồi quy Bayes, hệ số chặn \(\alpha\) và hệ số góc \(\beta\) thường có hiệp phương sai âm mạnh:&lt;/strong&gt; Chuẩn hóa (đưa biến giải thích về trung bình 0) sẽ kéo \(\mathrm{Cov}(\alpha, \beta) \approx 0\), giúp MCMC chạy mượt hơn hẳn!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Monte Carlo biến mọi kỳ vọng phức tạp thành trung bình cộng:&lt;/strong&gt; Khi có \(S\) mẫu hậu nghiệm \(\theta^{(s)}\), \(\mathbb{E}[g(\theta)\mid y] \approx \frac{1}{S}\sum g(\theta^{(s)})\) hoạt động cho mọi hàm phi tuyến \(g\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh.&lt;/strong&gt; Trong bảng 3 kịch bản ở trên, hãy tính hệ số tương quan chính xác \(\rho(X, Y) = \frac{\mathrm{Cov}(X,Y)}{\sqrt{\mathrm{Var}(X)\mathrm{Var}(Y)}}\)!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KLs_7b7SKi4&quot;&gt;Expected Values, Main Ideas!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giải thích kỳ vọng như giá trị trung bình dài hạn của một biến ngẫu nhiên.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qtaqvPAeEJY&quot;&gt;Covariance, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Minh họa trực quan hiệp phương sai dương, âm và bằng không.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vikkiwjQqfU&quot;&gt;Population and Estimated Parameters, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Phân biệt tham số quần thể với đại lượng ước lượng từ mẫu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Vì sao kỳ vọng không phải lúc nào cũng trùng với đỉnh cao nhất của phân phối?&lt;/li&gt;
  &lt;li&gt;Nêu một ví dụ thực tế về hai biến có hiệp phương sai âm.&lt;/li&gt;
  &lt;li&gt;Vì sao hiệp phương sai bằng 0 chưa đủ để kết luận hai biến độc lập?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Wasserman, L. (2004). &lt;em&gt;All of Statistics&lt;/em&gt;. Springer.&lt;/li&gt;
  &lt;li&gt;McElreath, R. (2020). &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.). CRC Press.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_14_law_large_numbers_clt/&quot;&gt;0.16 Luật số lớn và Định lý giới hạn trung tâm&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.14: Mô hình Thống kê là gì?</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_12_statistical_model_definition/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_12_statistical_model_definition</id>
   <content type="html">&lt;p&gt;Thực chất một &lt;strong&gt;mô hình thống kê (statistical model)&lt;/strong&gt; là gì? Nó không phải là một hàm hộp đen &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.fit()&lt;/code&gt; vô hồn — mà là &lt;strong&gt;một câu chuyện toán học mô tả cách dữ liệu được sinh ra (generative story)!&lt;/strong&gt; Trong tư duy Bayes, viết một mô hình thống kê nghĩa là nêu tường minh hai mảnh ghép: quy luật sinh dữ liệu khi biết tham số (&lt;strong&gt;hàm hợp lý&lt;/strong&gt; \(p(y\mid\theta)\)) và những giá trị tham số khả dĩ trước khi nhìn dữ liệu (&lt;strong&gt;tiên nghiệm&lt;/strong&gt; \(p(\theta)\)).&lt;/p&gt;

&lt;p&gt;Bài học này giúp bạn đọc và viết lưu loát ký hiệu mô hình sinh, phân biệt rạch ròi &lt;strong&gt;tham số&lt;/strong&gt;, &lt;strong&gt;dữ liệu&lt;/strong&gt; và &lt;strong&gt;siêu tham số&lt;/strong&gt;, đồng thời biết kiểm tra mô hình bằng mô phỏng tiên nghiệm trước khi chạm vào dữ liệu thật.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-thành-phần-của-một-mô-hình-thống-kê-sinh-generative-model&quot;&gt;Kiến thức cần nhớ: Bốn thành phần của một Mô hình Thống kê Sinh (Generative Model)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cấu trúc sinh dữ liệu (Hàm hợp lý \(p(y\mid\theta)\)):&lt;/strong&gt; Họ phân phối xác suất mô tả cách tín hiệu và nhiễu kết hợp để tạo ra quan sát \(y\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối tiên nghiệm \(p(\theta\mid\phi)\):&lt;/strong&gt; Mã hóa miền hợp lệ và thang đo hợp lý của tham số \(\theta\), được điều khiển bởi các &lt;strong&gt;siêu tham số&lt;/strong&gt; \(\phi\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô phỏng chiều thuận (Prior Predictive):&lt;/strong&gt; Vì mô hình Bayes có tính sinh hoàn chỉnh, ta có thể rút \(\theta \sim p(\theta)\) rồi sinh dữ liệu giả \(y_{\text{sim}} \sim p(y\mid\theta)\) &lt;em&gt;trước khi&lt;/em&gt; khớp dữ liệu — phát hiện ngay những tiên nghiệm vô lý (như dự báo điểm thi âm!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;“Mọi mô hình đều sai, nhưng có những mô hình hữu ích” (George Box):&lt;/strong&gt; Mô hình là sự đơn giản hóa có chủ đích; giá trị của nó nằm ở khả năng giải thích cấu trúc, định lượng bất định và dự báo tốt trên dữ liệu mới.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu định nghĩa thực dụng của mô hình thống kê như một mô tả xác suất về cách dữ liệu được sinh ra, phân biệt rõ dữ liệu quan sát với tham số chưa biết, và thấy vì sao việc nắm rõ giả định của mô hình luôn quan trọng hơn việc thuộc công thức.&lt;/p&gt;

&lt;h2 id=&quot;giới-thiệu-mô-hình-như-ngôn-ngữ-trung-gian-của-suy-luận&quot;&gt;Giới thiệu: Mô hình như ngôn ngữ trung gian của suy luận&lt;/h2&gt;

&lt;p&gt;Trong thống kê, dữ liệu quan sát mới chỉ là điểm khởi đầu. Để đi từ dữ liệu đến kết luận về cơ chế thực tế đằng sau nó, ta cần một cấu trúc trung gian giúp phát biểu giả định, tạo dự báo và cập nhật hiểu biết khi có thêm thông tin. Cấu trúc đó chính là mô hình thống kê.&lt;/p&gt;

&lt;h2 id=&quot;1-động-cơ-dữ-liệu-không-tự-trả-lời-nếu-thiếu-mô-hình&quot;&gt;1) Động cơ: Dữ liệu không tự trả lời nếu thiếu mô hình&lt;/h2&gt;

&lt;p&gt;Từ một tập dữ liệu, ta có thể tính trung bình, độ lệch chuẩn hay vẽ histogram. Tuy nhiên, những con số mô tả đó chưa tự trả lời được các câu hỏi suy luận như tỷ lệ thật trong quần thể là bao nhiêu, hiệu ứng có đủ lớn về mặt thực tiễn hay không, hoặc dự báo tương lai bất định đến mức nào. Để giải quyết các câu hỏi này, ta cần cầu nối từ “tham số chưa biết” sang “dữ liệu có thể quan sát” — đó chính là mô hình thống kê.&lt;/p&gt;

&lt;h2 id=&quot;2-định-nghĩa-cốt-lõi&quot;&gt;2) Định nghĩa cốt lõi&lt;/h2&gt;

&lt;p&gt;Một &lt;strong&gt;mô hình thống kê&lt;/strong&gt; là một họ các phân phối xác suất cho dữ liệu \(x\), được chỉ số hóa bởi tham số \(\theta\):&lt;/p&gt;

\[\mathcal{M} = \{p(x\mid \theta): \theta \in \Theta\}\]

&lt;p&gt;Trong đó, \(x\) là dữ liệu quan sát được, \(\theta\) là đại lượng chưa biết chi phối cơ chế sinh dữ liệu, và \(\Theta\) là không gian tham số — tập tất cả các giá trị hợp lệ mà \(\theta\) có thể nhận. Nói ngắn gọn, mô hình thống kê mô tả “nếu tham số nhận giá trị \(\theta\), dữ liệu sẽ có xu hướng phân bố như thế nào”.&lt;/p&gt;

&lt;h2 id=&quot;3-góc-nhìn-sinh-dữ-liệu-generative-story&quot;&gt;3) Góc nhìn sinh dữ liệu (generative story)&lt;/h2&gt;

&lt;p&gt;Trong khóa học này, ta ưu tiên đọc mô hình theo cơ chế sinh dữ liệu: trước hết tồn tại một tham số \(\theta\) chưa biết, từ \(\theta\) dữ liệu \(x\) được sinh ra theo \(p(x\mid\theta)\), và nhiệm vụ của phân tích là đối chiếu dữ liệu quan sát được với những gì mô hình dự kiến dưới các giá trị khả dĩ của \(\theta\).&lt;/p&gt;

&lt;p&gt;Xét ví dụ tung đồng xu: \(\theta\) là xác suất ra Ngửa, mỗi lần tung cho một quan sát \(y_i \sim \text{Bernoulli}(\theta)\), và sau \(n\) lần tung thì tổng số lần ra Ngửa \(k=\sum_i y_i\) tuân theo \(\text{Binomial}(n,\theta)\). Ở đây, mô hình không chỉ là công thức nhị thức, mà còn bao gồm các giả định: mỗi lần tung có cùng xác suất \(\theta\), các lần tung độc lập nhau, và thông tin được tóm tắt qua số lần ra Ngửa trong \(n\) phép thử.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/statistical_model_definition_flow.png&quot; alt=&quot;Mô hình thống kê như cầu nối giữa tham số và dữ liệu&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1: Mô hình thống kê đóng vai trò cầu nối giữa tham số chưa biết \(\theta\) và dữ liệu quan sát \(x\) thông qua cơ chế sinh dữ liệu \(p(x\mid\theta)\), từ đó cập nhật thành phân phối hậu nghiệm \(p(\theta\mid x)\).&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-mô-hình-thống-kê--câu-chuyện-sinh-dữ-liệu&quot;&gt;Video ngắn: Mô hình Thống kê = Câu chuyện Sinh dữ liệu&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-14a-generative-story.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): luồng sinh dữ liệu 3 tầng (Siêu tham số → Tham số → Dữ liệu), suy diễn ngược Bayes, tách Tín hiệu + Nhiễu và vòng lặp George Box.&lt;/p&gt;

&lt;h2 id=&quot;31-mô-hình-và-mô-phỏng-khác-nhau-thế-nào&quot;&gt;3.1) Mô hình và mô phỏng khác nhau thế nào?&lt;/h2&gt;

&lt;p&gt;Hai khái niệm này dễ bị nhầm lẫn nhưng giữ vai trò khác nhau: &lt;strong&gt;mô hình&lt;/strong&gt; là bản thiết kế khái niệm mô tả cơ chế xác suất sinh ra dữ liệu, còn &lt;strong&gt;mô phỏng&lt;/strong&gt; là việc chạy bản thiết kế đó trên máy tính với tham số cụ thể để tạo dữ liệu giả nhiều lần.&lt;/p&gt;

&lt;p&gt;Với ví dụ đồng xu, mô hình phát biểu \(y_i\sim\text{Bernoulli}(\theta)\), còn mô phỏng là chọn một giá trị cụ thể như \(\theta = 0.6\) rồi lặp lại việc tung nhiều lần để quan sát sự dao động của tỷ lệ ra Ngửa.&lt;/p&gt;

&lt;p&gt;Ví dụ mô phỏng ngắn bằng Python:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n_tosses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n_simulations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10_000&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;heads_counts&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_tosses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_simulations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;head_rates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;heads_counts&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_tosses&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heads_counts&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;head_rates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;head_rates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Trong đoạn mã này, mô hình là \(K \sim \text{Binomial}(20, 0.6)\). Bước mô phỏng giúp ta thấy nếu mô hình đó đúng, số mặt Ngửa trong 20 lần tung thường nằm quanh mức nào và dao động bao nhiêu giữa các lần lặp. Trung bình của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;head_rates&lt;/code&gt; sẽ tiến sát 0.6, nhưng từng mẫu riêng lẻ vẫn biến thiên quanh giá trị đó — minh họa rằng mô hình sinh ra một phân phối kết quả chứ không phải một con số cố định. Như vậy, mô phỏng không thay thế mô hình mà là công cụ kiểm tra trực giác và hệ quả của mô hình.&lt;/p&gt;

&lt;h2 id=&quot;4-mô-hình-không-phải-sự-thật-mà-là-xấp-xỉ-hữu-ích&quot;&gt;4) Mô hình không phải “sự thật” mà là xấp xỉ hữu ích&lt;/h2&gt;

&lt;p&gt;Một hiểu lầm phổ biến là tin rằng tồn tại một “mô hình đúng tuyệt đối”. Trên thực tế, mô hình chỉ là bản đồ chứ không phải lãnh thổ: mọi mô hình đều lược bỏ một phần chi tiết, và giá trị của nó nằm ở khả năng dự báo, giải thích và hỗ trợ quyết định. Do đó, khi xây dựng mô hình, ta luôn cần tự hỏi những giả định nào đang được đặt ra, chúng có phù hợp với bối cảnh dữ liệu không, và kết luận sẽ lệch theo hướng nào nếu giả định bị vi phạm.&lt;/p&gt;

&lt;h2 id=&quot;5-liên-hệ-trực-tiếp-với-suy-diễn-bayesian&quot;&gt;5) Liên hệ trực tiếp với suy diễn Bayesian&lt;/h2&gt;

&lt;p&gt;Trong thống kê Bayesian, mô hình thống kê đi vào định lý Bayes qua hàm hợp lý (likelihood):&lt;/p&gt;

\[p(\theta\mid x) \propto p(x\mid\theta)\,p(\theta)\]

&lt;p&gt;Trong đó, \(p(x\mid\theta)\) xuất phát từ mô hình thống kê, \(p(\theta)\) là phân phối tiên nghiệm (prior), và \(p(\theta\mid x)\) là phân phối hậu nghiệm (posterior) sau khi cập nhật dữ liệu. Nếu mô hình được đặc tả thiếu rõ ràng, hàm hợp lý sẽ mơ hồ và phân phối hậu nghiệm cũng mất ý nghĩa.&lt;/p&gt;

&lt;h2 id=&quot;6-một-ví-dụ-ngắn-đo-chiều-cao-sinh-viên&quot;&gt;6) Một ví dụ ngắn: Đo chiều cao sinh viên&lt;/h2&gt;

&lt;p&gt;Giả sử \(x_1,\dots,x_n\) là chiều cao (cm) của sinh viên trong một lớp. Một mô hình đơn giản là:&lt;/p&gt;

\[x_i \sim \mathcal{N}(\mu,\sigma^2),\quad i=1,\dots,n\]

&lt;p&gt;với \(\mu\) là chiều cao trung bình và \(\sigma\) là độ lệch chuẩn. Mô hình này ngầm giả định dữ liệu gần phân phối chuẩn, các quan sát độc lập có điều kiện khi biết tham số, và tất cả quan sát đều phát sinh từ cùng một cơ chế. Từ đó ta có thể ước lượng \(\mu, \sigma\), dự báo quan sát mới và kiểm tra xem mô hình có bỏ sót cấu trúc nào trong dữ liệu hay không.&lt;/p&gt;

&lt;h3 id=&quot;61-chọn-mô-hình-theo-bản-chất-dữ-liệu&quot;&gt;6.1) Chọn mô hình theo bản chất dữ liệu&lt;/h3&gt;

&lt;p&gt;Nếu dữ liệu không phải chiều cao mà là số cuộc gọi đến tổng đài mỗi giờ (\(0, 1, 3, 2, 4, \dots\)), mô hình Poisson sẽ hợp lý hơn vì tôn trọng bản chất đếm nguyên không âm. Nếu ép dùng mô hình Normal, ta vẫn tính được trung bình và độ lệch chuẩn nhưng mô hình lại ngầm gán xác suất dương cho các giá trị âm vốn vô nghĩa trong thực tế. Vì thế, chọn mô hình là chọn một câu chuyện hợp lý về cơ chế sinh dữ liệu, và lựa chọn đó quyết định loại suy luận nào có ý nghĩa.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt-nhanh&quot;&gt;Tóm tắt nhanh&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Mô hình thống kê là họ phân phối \(\{p(x\mid\theta)\}\) cho dữ liệu.&lt;/li&gt;
  &lt;li&gt;Nó kết nối tham số chưa biết với dữ liệu quan sát qua cơ chế sinh dữ liệu.&lt;/li&gt;
  &lt;li&gt;Mọi mô hình đều gắn với giả định; hiểu rõ giả định quan trọng hơn thuộc công thức.&lt;/li&gt;
  &lt;li&gt;Trong thống kê Bayesian, mô hình cung cấp hàm hợp lý để cập nhật từ tiên nghiệm sang hậu nghiệm.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;ví-dụ-tính-tay-làm-từng-bước-kiểm-tra-mô-hình-điểm-thi-qua-phân-phối-dự-báo-tiên-nghiệm&quot;&gt;Ví dụ tính tay làm từng bước: Kiểm tra mô hình điểm thi qua Phân phối Dự báo Tiên nghiệm&lt;/h3&gt;

&lt;p&gt;Giả sử bạn mô hình hóa điểm thi \(Y\) với nhiễu đo lường đã biết \(\sigma = 10\) và điểm trung bình lớp chưa biết \(\mu\):&lt;/p&gt;

\[\mu \sim \mathcal{N}(70,\; 5^2), \qquad Y \mid \mu \sim \mathcal{N}(\mu,\; 10^2).\]

&lt;p&gt;Trước khi chấm bất kỳ bài thi nào, một điểm thi tương lai \(Y = \mu + \varepsilon\) tuân theo phân phối dự báo tiên nghiệm nào? Vì \(\mu\) và \(\varepsilon\) độc lập:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kỳ vọng dự báo tiên nghiệm:&lt;/strong&gt; \(\mathbb{E}[Y] = 70 + 0 = \mathbf{70}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương sai dự báo tiên nghiệm (phương sai hai nguồn độc lập cộng nhau!):&lt;/strong&gt;
\(\mathrm{Var}(Y) = \mathrm{Var}(\mu) + \mathrm{Var}(\varepsilon) = 5^2 + 10^2 = 25 + 100 = \mathbf{125} \implies \mathrm{SD}(Y) = \sqrt{125} \approx \mathbf{11{,}18}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng 95% dự báo tiên nghiệm:&lt;/strong&gt; \(70 \pm 1{,}96(11{,}18) = \mathbf{[48{,}1;\; 91{,}9]}\) — nằm gọn gàng trong thang điểm 0–100! &lt;em&gt;(Trái lại, một tiên nghiệm “phẳng” cẩu thả \(\mu \sim \mathcal{N}(70, 1000^2)\) sẽ dự báo điểm thi từ \(-1890\) đến \(+2030\)!)&lt;/em&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h4 id=&quot;video-ngắn-prior-predictive-check-bắt-lỗi-tiên-nghiệm-trước-khi-chạm-dữ-liệu&quot;&gt;Video ngắn: Prior Predictive Check: Bắt lỗi Tiên nghiệm trước khi chạm Dữ liệu&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-14b-prior-predictive-check.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): phát hiện prior N(0, 10²) sinh điểm thi vô lý ngoài [0, 10], sửa sang N(6.5, 1.8²), bẫy phi tuyến trên thang logit và pm.sample_prior_predictive().&lt;/p&gt;

&lt;h3 id=&quot;giải-thích-bốn-nguyên-tắc-xây-dựng-mô-hình-thống-kê-chuẩn-mực&quot;&gt;Giải thích: Bốn nguyên tắc xây dựng mô hình thống kê chuẩn mực&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Luôn viết mô hình bằng 2–3 dòng ký hiệu toán trước khi gõ code:&lt;/strong&gt; Ký hiệu giúp mọi giả định ẩn hiện ra công khai để đồng nghiệp phản biện.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tách bất định tham số (epistemic) khỏi nhiễu dữ liệu (aleatoric):&lt;/strong&gt; Thu thêm dữ liệu làm \(\mathrm{Var}(\mu\mid y) \to 0\), nhưng không bao giờ làm biến mất nhiễu cá thể \(\sigma^2 = 100\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Luôn chạy kiểm tra dự báo tiên nghiệm (Prior Predictive Check):&lt;/strong&gt; Một biểu đồ 5 giây cứu bạn khỏi hàng giờ gỡ lỗi MCMC vô ích.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bắt đầu đơn giản rồi mở rộng dần:&lt;/strong&gt; Dựng mô hình nền tối giản trước, kiểm tra chỗ nào nó không khớp thực tế (PPC), rồi mới thêm phân cấp hoặc đuôi nặng Student-\(t\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh.&lt;/strong&gt; Trong mô hình điểm thi ở trên, nếu bạn đã biết chắc chắn điểm trung bình lớp \(\mu = 70\) (tức \(\mathrm{SD}(\mu) = 0\)), thì độ lệch chuẩn dự báo của một bài thi mới \(Y\) sẽ còn lại bằng bao nhiêu?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=3d5ivs_8amQ&quot;&gt;What is a statistical model?&lt;/a&gt; — Very Normal, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giải thích định nghĩa mô hình thống kê như mô tả xác suất về cách dữ liệu được sinh ra.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=FdnMWdICdRs&quot;&gt;Statistical Rethinking 2023 - 01 - The Golem of Prague&lt;/a&gt; — Richard McElreath, English. Phân tích vai trò của giả định và vì sao mô hình cần được kiểm soát thay vì dùng máy móc.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kn8fyNzvcPo&quot;&gt;Regression and Other Stories: Generative models and statistical inference (ros02 4)&lt;/a&gt; — Data Science Learning Community Videos, English. Minh họa mối liên hệ giữa mô hình sinh dữ liệu và suy luận thống kê.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Với ví dụ tung đồng xu, hãy liệt kê ba giả định ngầm của mô hình Binomial.&lt;/li&gt;
  &lt;li&gt;Nêu một tình huống thực tế mà giả định độc lập giữa các quan sát bị vi phạm.&lt;/li&gt;
  &lt;li&gt;Vì sao nói “mô hình là bản đồ, không phải lãnh thổ”?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;McElreath, R. (2020). &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.). CRC Press.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.). CRC Press.&lt;/li&gt;
  &lt;li&gt;Wasserman, L. (2004). &lt;em&gt;All of Statistics&lt;/em&gt;. Springer.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_13_expectation_variance_covariance/&quot;&gt;0.15 Kỳ vọng, Phương sai, và Hiệp phương sai&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.13: Phân phối đồng thời (Joint Distribution)</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_11_joint_distribution/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_11_joint_distribution</id>
   <content type="html">&lt;p&gt;Mọi mô hình Bayes trong suốt khóa học này thực chất đều quy về đúng một đối tượng trung tâm: &lt;strong&gt;phân phối đồng thời (joint distribution) \(p(\theta, y)\)&lt;/strong&gt; trên tham số ẩn \(\theta\) và dữ liệu quan sát \(y\)! Một khi bạn dựng xong mặt phân phối đồng thời đó bằng cách nhân tiên nghiệm \(p(\theta)\) với hàm hợp lý \(p(y\mid\theta)\), mọi phép toán suy diễn Bayes chỉ còn là hai thao tác cực kỳ trực quan: &lt;strong&gt;cắt lát theo dữ liệu đã thấy (conditioning)&lt;/strong&gt; để lấy hậu nghiệm, hoặc &lt;strong&gt;cộng/tích phân gộp một trục (marginalization)&lt;/strong&gt; để tính bằng chứng \(p(y)\) và phân phối dự báo.&lt;/p&gt;

&lt;p&gt;Bài học này rèn luyện phản xạ làm việc với bảng phân phối đồng thời, phân phối biên và phân phối có điều kiện để bạn nhìn thấy định lý Bayes hiện ra rõ mồn một ngay trên một bảng số \(2\times 2\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-phép-toán-nền-tảng-trên-mọi-phân-phối-đồng-thời&quot;&gt;Kiến thức cần nhớ: Ba phép toán nền tảng trên mọi Phân phối Đồng thời&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối đồng thời \(p(x, y)\):&lt;/strong&gt; Lưu giữ &lt;em&gt;trọn vẹn&lt;/em&gt; thông tin về cả hai biến cùng lúc (kể cả mối phụ thuộc giữa chúng); tổng (hoặc tích phân) trên toàn bộ không gian bằng đúng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biên hóa (Marginalization — Cộng/Tích phân gộp):&lt;/strong&gt; \(p(x) = \sum_y p(x, y)\) loại bỏ một biến phụ để nhìn riêng phân phối của \(X\) — đây chính là cơ chế tính bằng chứng \(p(y) = \int p(y,\theta)\,d\theta\) và khử tham số nhiễu trong thống kê Bayes!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điều kiện hóa (Conditioning — Cắt lát &amp;amp; Chuẩn hóa lại):&lt;/strong&gt; Cố định \(X = x\) cắt ra đúng một hàng/cột của bảng đồng thời rồi chia cho tổng biên của hàng/cột đó: \(p(y\mid x) = \frac{p(x, y)}{p(x)}\) — chính là &lt;strong&gt;định lý Bayes&lt;/strong&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu phân phối đồng thời là phần mở rộng tự nhiên của hàm phân phối một biến sang nhiều biến, biết cách rút ra phân phối biên và phân phối có điều kiện từ phân phối đồng thời, và thấy rõ vì sao cấu trúc này là nền tảng trực tiếp của suy luận Bayesian.&lt;/p&gt;

&lt;h2 id=&quot;1-động-cơ-một-biến-là-chưa-đủ&quot;&gt;1) Động cơ: Một biến là chưa đủ&lt;/h2&gt;

&lt;p&gt;Ở các bài trước, ta đã làm việc với hàm phân phối của &lt;strong&gt;một biến&lt;/strong&gt;: với biến rời rạc là \(p(x)=P(X=x)\), còn với biến liên tục là hàm mật độ \(f(x)\) kèm xác suất khoảng \(P(a\le X\le b)=\int_a^b f(x)\,dx\).&lt;/p&gt;

&lt;p&gt;Khi mở rộng từ một chiều sang hai chiều (và tổng quát là nhiều chiều), ta chuyển từ \(p(x)\) hoặc \(f(x)\) sang \(p(x,y)\) hoặc \(f(x,y)\). Phân phối đồng thời (joint distribution) vì thế không phải khái niệm tách biệt, mà là &lt;strong&gt;bước mở rộng trực tiếp sang không gian nhiều biến&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/joint_distribution_marginalization.png&quot; alt=&quot;Mở rộng từ 1 biến sang nhiều biến&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1: Minh họa mở rộng từ hàm phân phối 1 biến sang phân phối đồng thời 2 biến. Ở giữa là mật độ đồng thời \(f(x,y)\); phía trên và bên phải là hai phân phối biên thu được bằng cách lấy tích phân theo trục còn lại; đường ngang nét đứt thể hiện một lát cắt giúp hình dung phân phối có điều kiện.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Trong thực tế, ta thường quan tâm nhiều biến cùng lúc — chẳng hạn chiều cao \(H\) và cân nặng \(W\), thời gian học \(T\) và điểm kiểm tra \(S\), hay trạng thái bệnh \(D\) và kết quả xét nghiệm \(X\). Nếu chỉ mô tả riêng từng biến, ta sẽ bỏ sót mối liên hệ giữa chúng. Phân phối đồng thời cho phép trả lời các câu hỏi dạng: “xác suất để &lt;strong&gt;đồng thời&lt;/strong&gt; \(H\) nằm trong khoảng này và \(W\) nằm trong khoảng kia là bao nhiêu?”&lt;/p&gt;

&lt;h2 id=&quot;2-định-nghĩa-phân-phối-đồng-thời&quot;&gt;2) Định nghĩa phân phối đồng thời&lt;/h2&gt;

&lt;h3 id=&quot;21-trường-hợp-rời-rạc&quot;&gt;2.1 Trường hợp rời rạc&lt;/h3&gt;

&lt;p&gt;Với hai biến rời rạc \(X, Y\), phân phối đồng thời là:&lt;/p&gt;

\[p(x,y) = P(X=x, Y=y)\]

&lt;p&gt;Để phân phối hợp lệ, cần có \(p(x,y) \ge 0\) với mọi \(x,y\) và tổng kép \(\sum_x\sum_y p(x,y)=1\). Giá trị \(p(x,y)\) chính là xác suất hai biến đồng thời nhận cặp giá trị \((x, y)\).&lt;/p&gt;

&lt;h3 id=&quot;22-trường-hợp-liên-tục&quot;&gt;2.2 Trường hợp liên tục&lt;/h3&gt;

&lt;p&gt;Với hai biến liên tục \(X, Y\), ta sử dụng hàm mật độ đồng thời \(f(x,y)\) thỏa mãn:&lt;/p&gt;

\[P((X,Y)\in A)=\iint_A f(x,y)\,dx\,dy\]

&lt;p&gt;và điều kiện chuẩn hóa:&lt;/p&gt;

\[\iint_{\mathbb{R}^2} f(x,y)\,dx\,dy=1\]

&lt;p&gt;Tương tự bài PDF một biến, \(f(x,y)\) không phải xác suất tại một điểm mà là mật độ xác suất trên mặt phẳng.&lt;/p&gt;

&lt;h2 id=&quot;3-từ-đồng-thời-sang-phân-phối-biên-marginal&quot;&gt;3) Từ đồng thời sang phân phối biên (marginal)&lt;/h2&gt;

&lt;p&gt;Phân phối biên mô tả phân phối của một biến khi ta “cộng gộp” (bỏ qua) biến còn lại. Với trường hợp rời rạc:&lt;/p&gt;

\[p_X(x)=\sum_y p(x,y),\qquad p_Y(y)=\sum_x p(x,y)\]

&lt;p&gt;Với trường hợp liên tục:&lt;/p&gt;

\[f_X(x)=\int_{-\infty}^{\infty} f(x,y)\,dy,\qquad f_Y(y)=\int_{-\infty}^{\infty} f(x,y)\,dx\]

&lt;p&gt;Về trực giác, phân phối biên thu được bằng cách lấy tổng hoặc tích phân dọc theo trục của biến còn lại.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-phân-phối-đồng-thời-px-y--phép-biên-hóa&quot;&gt;Video ngắn: Phân phối Đồng thời p(x, y) &amp;amp; Phép Biên hóa&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-13a-joint-marginal-table.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): bảng đồng thời 2×2, cộng ngang/dọc ra phân phối biên, kiểm tra phụ thuộc và vai trò biên hóa trong bằng chứng Bayes p(y).&lt;/p&gt;

&lt;h2 id=&quot;4-phân-phối-có-điều-kiện-và-quy-tắc-nhân&quot;&gt;4) Phân phối có điều kiện và quy tắc nhân&lt;/h2&gt;

&lt;p&gt;Khi đã biết \(Y=y\) (với \(p_Y(y) &amp;gt; 0\)), phân phối có điều kiện của \(X\) là:&lt;/p&gt;

\[p(x\mid y)=\frac{p(x,y)}{p_Y(y)}\]

&lt;p&gt;(với biến liên tục, thay bằng các hàm mật độ tương ứng).&lt;/p&gt;

&lt;p&gt;Từ định nghĩa này ta suy ra quy tắc nhân:&lt;/p&gt;

\[p(x,y)=p(x\mid y)p_Y(y)=p(y\mid x)p_X(x)\]

&lt;p&gt;Đây chính là nền tảng trực tiếp của định lý Bayes:&lt;/p&gt;

\[p(\theta\mid x)=\frac{p(x\mid\theta)p(\theta)}{p(x)}\]

&lt;p&gt;trong đó điểm chính là phân tách phân phối đồng thời thành tích của hàm hợp lý và phân phối tiên nghiệm:&lt;/p&gt;

\[p(\theta,x)=p(x\mid\theta)p(\theta)\]

&lt;h3 id=&quot;video-ngắn-điều-kiện-hóa-cắt-lát-bảng-đồng-thời-ra-định-lý-bayes&quot;&gt;Video ngắn: Điều kiện hóa: Cắt lát Bảng Đồng thời ra Định lý Bayes&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-13b-conditioning-slice-bayes.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): cắt bỏ cột Y = 0 khi quan sát Y = 1, chia tổng cột 0.55 để ra hậu nghiệm 81.8%, quy tắc nhân và cắt lát mặt liên tục.&lt;/p&gt;

&lt;h2 id=&quot;5-độc-lập-và-phụ-thuộc&quot;&gt;5) Độc lập và phụ thuộc&lt;/h2&gt;

&lt;p&gt;Hai biến \(X, Y\) độc lập khi và chỉ khi với mọi \(x, y\):&lt;/p&gt;

\[p(x,y)=p_X(x)p_Y(y)\]

&lt;p&gt;(hoặc \(f(x,y)=f_X(x)f_Y(y)\) trong trường hợp liên tục).&lt;/p&gt;

&lt;p&gt;Nếu đẳng thức trên đúng, việc biết \(Y\) không làm thay đổi phân phối của \(X\). Ngược lại, khi hai biến phụ thuộc, thông tin về biến này sẽ làm thay đổi đánh giá về biến kia — và đây chính là tình huống trung tâm trong phần lớn mô hình Bayesian.&lt;/p&gt;

&lt;h2 id=&quot;6-ví-dụ-rời-rạc-ngắn&quot;&gt;6) Ví dụ rời rạc ngắn&lt;/h2&gt;

&lt;p&gt;Xét hai biến nhị phân: \(X \in \{0,1\}\) cho biết sinh viên có đi học đầy đủ hay không, và \(Y \in \{0,1\}\) cho biết sinh viên có qua môn hay không, với bảng phân phối đồng thời:&lt;/p&gt;

\[\begin{array}{c|cc}
 &amp;amp; y=0 &amp;amp; y=1 \\
\hline
x=0 &amp;amp; 0.30 &amp;amp; 0.10 \\
x=1 &amp;amp; 0.15 &amp;amp; 0.45
\end{array}\]

&lt;p&gt;Tổng bốn ô bằng 1 nên bảng hợp lệ. Từ bảng trên, ta tính được phân phối biên \(p_X(1)=0.15+0.45=0.60\), \(p_Y(1)=0.10+0.45=0.55\), và xác suất có điều kiện \(p(Y=1\mid X=1)=0.45/0.60=0.75\). So với xác suất biên \(p_Y(1)=0.55\), việc biết \(X=1\) làm xác suất qua môn tăng lên rõ rệt, chứng tỏ hai biến có phụ thuộc.&lt;/p&gt;

&lt;h3 id=&quot;61-đọc-bảng-bằng-số-lượng-cụ-thể&quot;&gt;6.1) Đọc bảng bằng số lượng cụ thể&lt;/h3&gt;

&lt;p&gt;Nếu quy đổi bảng trên sang một lớp 100 sinh viên:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;45 sinh viên đi học đầy đủ và qua môn,&lt;/li&gt;
  &lt;li&gt;15 sinh viên đi học đầy đủ nhưng không qua môn,&lt;/li&gt;
  &lt;li&gt;10 sinh viên không đi học đầy đủ nhưng vẫn qua môn,&lt;/li&gt;
  &lt;li&gt;30 sinh viên không đi học đầy đủ và không qua môn.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tỷ lệ qua môn ở nhóm đi học đầy đủ là \(45/(45+15)=75\%\), còn ở nhóm không đi học đầy đủ chỉ là \(10/(10+30)=25\%\). Cách đọc này cho thấy phân phối đồng thời không chỉ là bảng ký hiệu trừu tượng, mà phản ánh trực tiếp cấu trúc liên hệ giữa hai biến.&lt;/p&gt;

&lt;h2 id=&quot;7-liên-hệ-thực-hành-bayesian&quot;&gt;7) Liên hệ thực hành Bayesian&lt;/h2&gt;

&lt;p&gt;Trong mô hình Bayesian, ta thường xuất phát từ phân phối đồng thời của tham số và dữ liệu:&lt;/p&gt;

\[p(\theta, x)=p(x\mid\theta)p(\theta)\]

&lt;p&gt;Sau đó biên hóa theo \(\theta\) để thu được bằng chứng biên (evidence):&lt;/p&gt;

\[p(x)=\int p(x\mid\theta)p(\theta)\,d\theta\]

&lt;p&gt;và chuẩn hóa để nhận phân phối hậu nghiệm:&lt;/p&gt;

\[p(\theta\mid x)=\frac{p(x\mid\theta)p(\theta)}{p(x)}\]

&lt;p&gt;Do đó, nắm vững mối liên hệ đồng thời – biên – có điều kiện là bước đệm thiết yếu cho các bài suy diễn Bayesian phía sau.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt-nhanh&quot;&gt;Tóm tắt nhanh&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Phân phối đồng thời mô tả xác suất (hoặc mật độ) của nhiều biến cùng lúc.&lt;/li&gt;
  &lt;li&gt;Phân phối biên thu được từ phân phối đồng thời bằng phép lấy tổng (rời rạc) hoặc tích phân (liên tục).&lt;/li&gt;
  &lt;li&gt;Phân phối có điều kiện bằng phân phối đồng thời chia cho phân phối biên.&lt;/li&gt;
  &lt;li&gt;Quy tắc nhân nối phân phối đồng thời với phân phối có điều kiện: \(p(x,y)=p(x\mid y)p(y)\).&lt;/li&gt;
  &lt;li&gt;Hai biến độc lập khi và chỉ khi \(p(x,y)=p(x)p(y)\).&lt;/li&gt;
  &lt;li&gt;Suy diễn Bayesian dựa trực tiếp vào bộ ba cấu trúc đồng thời – biên – có điều kiện.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;ví-dụ-tính-tay-làm-từng-bước-cắt-lát-và-biên-hóa-bảng-đồng-thời-thời-tiết--giao-thông&quot;&gt;Ví dụ tính tay làm từng bước: Cắt lát và Biên hóa bảng đồng thời Thời tiết – Giao thông&lt;/h3&gt;

&lt;p&gt;Xét bảng phân phối đồng thời giữa &lt;strong&gt;Thời tiết&lt;/strong&gt; (\(W \in \{\text{Mưa}, \text{Nắng}\}\)) và &lt;strong&gt;Giao thông&lt;/strong&gt; (\(T \in \{\text{Tắc}, \text{Thông}\}\)) có tổng toàn bảng bằng \(1{,}00\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Thời tiết \ Giao thông&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Tắc đường (\(T=1\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Thông thoáng (\(T=0\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Biên \(P(W)\)&lt;/strong&gt;&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Mưa (\(W=1\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0{,}24\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0{,}06\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0{,}30\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Nắng (\(W=0\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0{,}16\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0{,}54\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0{,}70\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Biên \(P(T)\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0{,}40\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0{,}60\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(1{,}00\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra độc lập:&lt;/strong&gt; \(P(W=1)\cdot P(T=1) = 0{,}30 \times 0{,}40 = 0{,}12 \neq 0{,}24\) \(\implies\) Mưa và Tắc đường &lt;strong&gt;phụ thuộc mạnh&lt;/strong&gt; vào nhau!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cắt lát theo sự kiện “Đang tắc đường” (\(T=1\)):&lt;/strong&gt; Lấy cột &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tắc đường&lt;/code&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0.24, 0.16]&lt;/code&gt; chia cho tổng biên \(0{,}40\):
\(P(\text{Mưa} \mid \text{Tắc}) = \frac{0{,}24}{0{,}40} = \mathbf{0{,}60}, \qquad P(\text{Nắng} \mid \text{Tắc}) = \frac{0{,}16}{0{,}40} = \mathbf{0{,}40}.\)
Trước khi mở bản đồ giao thông, xác suất tiên nghiệm trời mưa là \(30\%\); chỉ cần thấy đường tắc, xác suất hậu nghiệm trời mưa lập tức tăng gấp đôi lên &lt;strong&gt;\(60\%\)&lt;/strong&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-bốn-quy-tắc-vàng-khi-tư-duy-bằng-phân-phối-đồng-thời&quot;&gt;Giải thích: Bốn quy tắc vàng khi tư duy bằng phân phối đồng thời&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Định lý Bayes chỉ là hai cách tách tích của cùng một phân phối đồng thời:&lt;/strong&gt; \(p(\theta, y) = p(y\mid\theta)p(\theta) = p(\theta\mid y)p(y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích phân biên bảo toàn trung thực độ bất định:&lt;/strong&gt; Thay vì chốt cứng một điểm ước lượng cho tham số phụ \(\sigma\), thống kê Bayes lấy tích phân trên đồng thời \(p(\mu, \sigma\mid y)\) để bất định của \(\sigma\) phản ánh đúng vào khoảng tin cậy của \(\mu\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân biệt bảng đồng thời với bảng điều kiện:&lt;/strong&gt; Bảng đồng thời có tổng &lt;em&gt;tất cả các ô&lt;/em&gt; bằng 1; bảng điều kiện \(P(T\mid W)\) có tổng &lt;em&gt;từng hàng&lt;/em&gt; bằng 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độc lập là trường hợp rất đặc biệt:&lt;/strong&gt; Chỉ khi \(p(x,y) = p(x)p(y)\) ở &lt;em&gt;mọi&lt;/em&gt; ô bạn mới được nhân hai biên; trong mô hình Bayes phân cấp, các quan sát cùng nhóm luôn phụ thuộc nhau qua tham số chung!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh.&lt;/strong&gt; Từ bảng Thời tiết – Giao thông ở trên, nếu bạn thấy đường đang &lt;strong&gt;Thông thoáng&lt;/strong&gt; (\(T = 0\)), xác suất hậu nghiệm \(P(\text{Mưa} \mid \text{Thông})\) bằng bao nhiêu?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pribJ8bUBzo&quot;&gt;Joint Probability Distributions: Marginal and Conditional Densities&lt;/a&gt; — Steve Brunton, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Minh họa cách đi từ mật độ đồng thời sang phân phối biên và phân phối có điều kiện.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Marginal distribution and conditional distribution&lt;/td&gt;
          &lt;td&gt;AP Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=CAXQvTKP8sg) — Khan Academy, English. Trình bày trường hợp rời rạc từ bảng hai chiều sang phân phối biên và có điều kiện.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qtaqvPAeEJY&quot;&gt;Covariance, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Giới thiệu hiệp phương sai như một thước đo tóm tắt sự phụ thuộc trong phân phối đồng thời.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài 1.&lt;/strong&gt; Từ bảng phân phối đồng thời ở Mục 6, hãy tính:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(p_X(0)\) và \(p_X(1)\).&lt;/li&gt;
  &lt;li&gt;\(p_Y(0)\) và \(p_Y(1)\).&lt;/li&gt;
  &lt;li&gt;\(p(X=1\mid Y=1)\) và \(p(Y=1\mid X=1)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Bài 2.&lt;/strong&gt; Chứng minh từ định nghĩa rằng:&lt;/p&gt;

\[p(x,y)=p(x\mid y)p(y)=p(y\mid x)p(x)\]

&lt;p&gt;&lt;strong&gt;Bài 3.&lt;/strong&gt; Cho hai biến liên tục có hàm mật độ đồng thời \(f(x,y)=c(x+y)\) trên miền \(0&amp;lt;x&amp;lt;1, 0&amp;lt;y&amp;lt;1\) và bằng 0 ngoài miền đó.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Tìm hằng số \(c\) để \(f\) là hàm mật độ hợp lệ.&lt;/li&gt;
  &lt;li&gt;Tìm các hàm mật độ biên \(f_X(x)\) và \(f_Y(y)\).&lt;/li&gt;
  &lt;li&gt;Kiểm tra xem \(X\) và \(Y\) có độc lập hay không.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Wasserman, L. (2004). &lt;em&gt;All of Statistics&lt;/em&gt;. Springer.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.). CRC Press.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. (2015). &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.). Academic Press.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_12_statistical_model_definition/&quot;&gt;0.14 Mô hình Thống kê là gì?&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.12: T-test và Phân phối T</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_09_t_test_and_t_distribution/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_09_t_test_and_t_distribution</id>
   <content type="html">&lt;p&gt;Đầu thế kỷ 20, William Sealy Gosset làm kỹ sư kiểm soát chất lượng tại nhà máy bia Guinness ở Dublin. Khác với các nhà toán học quen làm việc trên tập mẫu hàng nghìn người, Gosset chỉ có thể thử nghiệm trên những mẻ lúa mạch rất nhỏ (3 đến 5 mẫu mỗi lần). Ông nhận ra khi thay độ lệch chuẩn quần thể \(\sigma\) chưa biết bằng độ lệch chuẩn mẫu \(s\), thống kê chuẩn hóa không còn tuân theo phân phối Chuẩn nữa mà có &lt;strong&gt;đuôi dày hơn hẳn&lt;/strong&gt;. Vì Guinness cấm nhân viên công bố bí mật công nghiệp dưới tên thật, Gosset ký bút danh “Student” năm 1908 — khai sinh ra &lt;strong&gt;phân phối Student-\(t\)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Trong thống kê Bayes hiện đại, phân phối Student-\(t\) còn có một đời sống thứ hai cực kỳ rực rỡ: nó xuất hiện &lt;strong&gt;tự nhiên&lt;/strong&gt; khi ta tích phân hóa tham số phương sai chưa biết \(\sigma^2\) (hậu nghiệm biên của \(\mu\) trong mô hình Normal–Inverse-Gamma chính là Student-\(t\)!) và là lựa chọn hàng đầu để làm &lt;strong&gt;hồi quy bền vững trước ngoại lai&lt;/strong&gt; (BEST — Bayesian Estimation Supersedes the t-Test).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu Học tập&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành bài học này, bạn sẽ hiểu rõ bản chất của &lt;strong&gt;thống kê t (t-statistic)&lt;/strong&gt;, &lt;strong&gt;phân phối t&lt;/strong&gt; và &lt;strong&gt;kiểm định t (t-test)&lt;/strong&gt; — một trong những công cụ thống kê được dùng phổ biến nhất trong nghiên cứu. Bạn sẽ nắm được vì sao cần dùng phân phối t thay cho phân phối chuẩn, cách tính và diễn giải giá trị t, cách phân biệt các dạng t-test, cũng như các giả định và hạn chế của chúng để chuẩn bị đối chiếu với cách tiếp cận Bayesian ở các chương sau.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bất-định-của-phương-sai-phân-phối-đuôi-nặng-và-hậu-nghiệm-biên-student-t&quot;&gt;Kiến thức cần nhớ: Bất định của phương sai, Phân phối đuôi nặng và Hậu nghiệm biên Student-\(t\)&lt;/h2&gt;

&lt;p&gt;Ba trụ cột kết nối bài T-test cổ điển với tư duy Bayes chuyên sâu:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hậu quả của việc ước lượng \(\sigma\) từ mẫu nhỏ:&lt;/strong&gt; Khi cỡ mẫu \(n\) nhỏ, độ lệch chuẩn mẫu \(s\) có thể ngẫu nhiên bị ước lượng &lt;em&gt;quá nhỏ&lt;/em&gt;, làm tỷ số \(t = (\bar{x} - \mu_0)/(s/\sqrt{n})\) phình to bất thường. Bậc tự do \(\nu = n - 1\) điều chỉnh độ dày của hai đuôi để bù đắp cho chính sự bất định này.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biểu diễn hỗn hợp tỷ lệ (Scale Mixture of Normals):&lt;/strong&gt; Về mặt giải tích, một phân phối Student-\(t\) thực chất là hỗn hợp vô hạn các phân phối Chuẩn có cùng trung bình nhưng phương sai biến thiên theo phân phối Inverse-Gamma. Chính cấu trúc hỗn hợp này giúp Student-\(t\) “chấp nhận” ngoại lai mà không bị kéo lệch tâm mạnh như phân phối Chuẩn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Thống kê Bayes (Mô hình BEST của Kruschke):&lt;/strong&gt; Thay vì chỉ ra một p-value nhị phân từ T-test, cách tiếp cận Bayes đặt likelihood Student-\(t\) cho từng nhóm và tính phân phối hậu nghiệm của hiệu hai trung bình \(\mu_1 - \mu_2\), hiệu độ lệch chuẩn \(\sigma_1 - \sigma_2\) và độ lớn hiệu ứng (&lt;em&gt;effect size&lt;/em&gt;) cùng một lúc.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-vấn-đề-khi-chưa-biết-độ-lệch-chuẩn-quần-thể&quot;&gt;Giới thiệu: Vấn đề khi Chưa biết Độ lệch Chuẩn Quần thể&lt;/h2&gt;

&lt;p&gt;Giả sử bạn muốn kiểm tra chiều cao trung bình của nam sinh viên một trường đại học có khác 170 cm hay không. Vì không thể đo toàn bộ sinh viên, bạn chọn ngẫu nhiên 25 người và tính được trung bình mẫu \(\bar{x} = 172.5\) cm cùng độ lệch chuẩn mẫu \(s = 6.2\) cm. Câu hỏi đặt ra là chênh lệch giữa 172.5 cm và 170 cm có đủ lớn để bác bỏ giả thuyết ban đầu hay chỉ là biến động ngẫu nhiên do lấy mẫu.&lt;/p&gt;

&lt;p&gt;Trong thống kê cổ điển, nếu &lt;strong&gt;biết trước độ lệch chuẩn quần thể&lt;/strong&gt; \(\sigma\), ta dùng &lt;strong&gt;thống kê z (z-statistic)&lt;/strong&gt;:&lt;/p&gt;

\[z = \frac{\bar{x} - \mu_0}{\sigma / \sqrt{n}}\]

&lt;p&gt;Khi đó \(z\) tuân theo phân phối chuẩn tắc \(\mathcal{N}(0, 1)\). Tuy nhiên, trên thực tế ta &lt;strong&gt;hiếm khi biết&lt;/strong&gt; \(\sigma\) mà chỉ ước lượng nó bằng độ lệch chuẩn mẫu \(s\). Việc thay \(\sigma\) bằng \(s\) làm tăng độ bất định, khiến phân phối của thống kê kiểm định không còn là phân phối chuẩn nữa. Đây chính là lý do ra đời của &lt;strong&gt;phân phối t&lt;/strong&gt; và &lt;strong&gt;thống kê t&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;t-statistic-định-nghĩa-và-ý-nghĩa&quot;&gt;T-statistic: Định nghĩa và Ý nghĩa&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Thống kê t&lt;/strong&gt; (hay t-value) có công thức tương tự z-statistic, nhưng thay \(\sigma\) bằng độ lệch chuẩn mẫu \(s\):&lt;/p&gt;

\[t = \frac{\bar{x} - \mu_0}{s / \sqrt{n}}\]

&lt;p&gt;Trong đó, \(\bar{x}\) là trung bình mẫu, \(\mu_0\) là giá trị giả thuyết trong \(H_0\), \(s\) là độ lệch chuẩn mẫu, \(n\) là cỡ mẫu, còn \(s / \sqrt{n}\) là &lt;strong&gt;sai số chuẩn của trung bình&lt;/strong&gt; (standard error of the mean — SE), phản ánh mức độ bất định của trung bình mẫu.&lt;/p&gt;

&lt;h3 id=&quot;diễn-giải-giá-trị-t&quot;&gt;Diễn giải giá trị T&lt;/h3&gt;

&lt;p&gt;Giá trị t cho biết trung bình mẫu nằm cách giá trị giả thuyết \(\mu_0\) bao nhiêu lần sai số chuẩn. Nếu &lt;strong&gt;\(\vert t\vert\) lớn&lt;/strong&gt;, trung bình mẫu cách xa \(\mu_0\) đáng kể, tạo bằng chứng mạnh hơn chống lại \(H_0\); ngược lại, nếu &lt;strong&gt;\(\vert t\vert\) nhỏ&lt;/strong&gt;, trung bình mẫu nằm gần \(\mu_0\) nên chưa có nhiều bằng chứng để nghi ngờ giả thuyết không.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Bốn biểu đồ dưới đây minh họa các mức độ cực đoan khác nhau của giá trị t và sự thay đổi tương ứng của p-value.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_value_small_example.png&quot; alt=&quot;T-value nhỏ với bằng chứng yếu chống lại H0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1a: Với \(t = 0.5\) và \(df = 15\), p-value lớn (khoảng 0.62) nên dữ liệu phù hợp với \(H_0\).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_value_borderline_example.png&quot; alt=&quot;T-value ở vùng lưng chừng gần ngưỡng 0.05&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1b: Với \(t = 2.0\), p-value khoảng 0.064, nằm ở vùng lưng chừng sát ngưỡng 0.05.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_value_large_example.png&quot; alt=&quot;T-value lớn với bằng chứng mạnh hơn chống lại H0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1c: Với \(t = 3.0\), p-value nhỏ (khoảng 0.009) nên bằng chứng chống lại \(H_0\) rõ rệt hơn.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_value_chocolate_example.png&quot; alt=&quot;Ví dụ chocolate với t âm nhỏ về độ lớn&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1d: Minh họa trường hợp \(t = -0.70\) cho \(p = 0.495\), thể hiện chưa có đủ bằng chứng chống lại giả thuyết không.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Phần diện tích tô màu ở hai đuôi trong mỗi hình biểu thị “vùng cực đoan” dùng để tính p-value hai phía (two-tailed test).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ cụ thể:&lt;/strong&gt; quay lại bài toán chiều cao với \(\bar{x} = 172.5\) cm, \(\mu_0 = 170\) cm, \(s = 6.2\) cm và \(n = 25\):&lt;/p&gt;

\[t = \frac{172.5 - 170}{6.2 / \sqrt{25}} = \frac{2.5}{1.24} \approx 2.02\]

&lt;p&gt;Giá trị \(t \approx 2.02\) cho thấy trung bình mẫu lệch khoảng 2 sai số chuẩn so với 170 cm.&lt;/p&gt;

&lt;h2 id=&quot;phân-phối-t-tại-sao-không-phải-phân-phối-chuẩn&quot;&gt;Phân phối T: Tại sao Không phải Phân phối Chuẩn?&lt;/h2&gt;

&lt;p&gt;Khi thay \(\sigma\) bằng \(s\), thống kê t tuân theo &lt;strong&gt;phân phối t&lt;/strong&gt; (Student’s t-distribution) thay vì phân phối chuẩn.&lt;/p&gt;

&lt;h3 id=&quot;đặc-điểm-của-phân-phối-t&quot;&gt;Đặc điểm của Phân phối T&lt;/h3&gt;

&lt;p&gt;Phân phối t có dạng hình chuông đối xứng giống phân phối chuẩn nhưng &lt;strong&gt;đuôi dày hơn&lt;/strong&gt;, phản ánh phần bất định tăng thêm do phải ước lượng \(\sigma\) bằng \(s\). Hình dạng của nó phụ thuộc vào tham số &lt;strong&gt;bậc tự do&lt;/strong&gt; (degrees of freedom, ký hiệu \(df\); bằng \(n - 1\) trong kiểm định t một mẫu). Khi cỡ mẫu \(n\) tăng lên, ước lượng \(s\) ngày càng gần \(\sigma\) nên phân phối t hội tụ dần về phân phối chuẩn tắc; với mẫu trên 30 quan sát, hai đường cong gần như trùng nhau khi nhìn bằng mắt thường.&lt;/p&gt;

&lt;h3 id=&quot;vì-sao-đuôi-dày-hơn&quot;&gt;Vì sao đuôi dày hơn?&lt;/h3&gt;

&lt;p&gt;Khi cỡ mẫu nhỏ, \(s\) dao động mạnh quanh \(\sigma\). Trong những mẫu mà \(s\) ngẫu nhiên nhỏ hơn \(\sigma\) thật, giá trị \(\vert t\vert\) sẽ bị phóng đại lên. Phần đuôi dày hơn của phân phối t giúp điều chỉnh cho sự bất định này, đòi hỏi bằng chứng mạnh hơn mới bác bỏ \(H_0\) khi mẫu nhỏ.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_vs_normal_distribution.png&quot; alt=&quot;So sánh Phân phối T và Phân phối Chuẩn&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình minh họa: So sánh phân phối t theo các bậc tự do khác nhau với phân phối chuẩn tắc. Với &lt;strong&gt;df = 2&lt;/strong&gt; (mẫu rất nhỏ), đuôi rất dày do bất định trong ước lượng \(\sigma\) lớn; với &lt;strong&gt;df = 5&lt;/strong&gt; đuôi vẫn dày hơn chuẩn rõ rệt; với &lt;strong&gt;df = 10&lt;/strong&gt; sai khác thu hẹp; còn ở &lt;strong&gt;df = 30&lt;/strong&gt;, đường cong gần như trùng với phân phối chuẩn (giới hạn khi \(df \to \infty\)).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Điều này thể hiện trực tiếp qua các giá trị tới hạn (critical value) ở mức \(\alpha = 0.05\) (kiểm định hai phía): với \(df = 2\), ngưỡng tới hạn là \(\pm 4.303\), trong khi ở phân phối chuẩn chỉ là \(\pm 1.96\). Do đó, khi mẫu nhỏ, việc bác bỏ \(H_0\) thận trọng hơn nhiều.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-phân-phối-t-với-mẫu-nhỏ&quot;&gt;Thử nghiệm: phân phối t với mẫu nhỏ&lt;/h3&gt;

&lt;p&gt;Mô phỏng thống kê t và so với mật độ t và chuẩn khi n tăng.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;pvalue-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;tdist&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;video-ngắn-phân-phối-student-t-tại-sao-mẫu-nhỏ-tạo-ra-đuôi-dày&quot;&gt;Video ngắn: Phân phối Student-t: Tại sao mẫu nhỏ tạo ra Đuôi dày?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-12a-student-t-heavy-tails.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): câu chuyện Guinness, biến đổi đuôi dày từ df = 2 → 5 → 30, giá trị tới hạn 1.96 vs 4.30 và nguồn gốc Bayes khi biên hóa σ².&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-ví-dụ-lịch-sử-nhà-máy-bia-guinness-1908--sự-ra-đời-của-phân-phối-student-t&quot;&gt;Video ngắn: Ví dụ lịch sử: Nhà máy bia Guinness (1908) &amp;amp; Sự ra đời của Phân phối Student-t&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-12c-gosset-guinness-student-t.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 37 giây (dữ liệu lịch sử thực tế &amp;amp; mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): mô phỏng 205 mẻ lúa mạch mẫu nhỏ (n = 4) của William Gosset (‘Student’) cho thấy vì sao ước lượng s làm đuôi t(df = 3) dày hơn hẳn Normal, rồi trượt mượt df từ 1.5 → 30.&lt;/p&gt;

&lt;h2 id=&quot;các-loại-t-test&quot;&gt;Các Loại T-test&lt;/h2&gt;

&lt;p&gt;Tùy thiết kế nghiên cứu, có ba dạng t-test thường gặp:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_test_type_summary_table.png&quot; alt=&quot;Bảng tóm tắt ba loại t-test&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 2: Bảng tóm tắt mục đích, công thức và bậc tự do của ba dạng kiểm định t phổ biến.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;1-kiểm-định-t-một-mẫu-one-sample-t-test&quot;&gt;1. Kiểm định T một mẫu (One-sample T-test)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Mục đích:&lt;/strong&gt; So sánh trung bình của một mẫu với một giá trị tham chiếu \(\mu_0\) đã biết.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Công thức:&lt;/strong&gt;&lt;/p&gt;

\[t = \frac{\bar{x} - \mu_0}{s / \sqrt{n}}\]

&lt;p&gt;&lt;strong&gt;Bậc tự do:&lt;/strong&gt; \(df = n - 1\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; Kiểm tra chiều cao trung bình của nam sinh viên có khác 170 cm hay không.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_test_type_one_sample.png&quot; alt=&quot;One-sample t-test so sánh một mẫu với giá trị giả thuyết&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 2a: One-sample t-test so sánh trung bình của một mẫu với một giá trị giả thuyết cho trước.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;2-kiểm-định-t-hai-mẫu-độc-lập-independent-two-sample-t-test&quot;&gt;2. Kiểm định T hai mẫu độc lập (Independent Two-sample T-test)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Mục đích:&lt;/strong&gt; So sánh trung bình của hai nhóm độc lập.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Công thức (với giả định phương sai hai nhóm bằng nhau):&lt;/strong&gt;&lt;/p&gt;

\[t = \frac{\bar{x}_1 - \bar{x}_2}{s_p \sqrt{\frac{1}{n_1} + \frac{1}{n_2}}}\]

&lt;p&gt;trong đó \(s_p\) là &lt;strong&gt;độ lệch chuẩn gộp&lt;/strong&gt; (pooled standard deviation):&lt;/p&gt;

\[s_p = \sqrt{\frac{(n_1-1)s_1^2 + (n_2-1)s_2^2}{n_1 + n_2 - 2}}\]

&lt;p&gt;&lt;strong&gt;Bậc tự do:&lt;/strong&gt; \(df = n_1 + n_2 - 2\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; So sánh chiều cao trung bình giữa nam sinh viên khoa A và khoa B.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_test_type_independent.png&quot; alt=&quot;Independent two-sample t-test so sánh hai nhóm độc lập&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 2b: Independent two-sample t-test so sánh trung bình giữa hai nhóm độc lập.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;3-kiểm-định-t-ghép-cặp-paired-t-test&quot;&gt;3. Kiểm định T ghép cặp (Paired T-test)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Mục đích:&lt;/strong&gt; So sánh trung bình của hai phép đo trên cùng một nhóm đối tượng (trước–sau, hoặc các cặp ghép tương ứng).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Công thức:&lt;/strong&gt;&lt;/p&gt;

\[t = \frac{\bar{d}}{s_d / \sqrt{n}}\]

&lt;p&gt;trong đó \(\bar{d}\) là trung bình các hiệu số của từng cặp đo và \(s_d\) là độ lệch chuẩn của các hiệu số đó.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bậc tự do:&lt;/strong&gt; \(df = n - 1\) (với \(n\) là số cặp).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; So sánh cân nặng bệnh nhân trước và sau khi dùng thuốc giảm cân.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_test_type_paired.png&quot; alt=&quot;Paired t-test so sánh trước và sau trên cùng một nhóm&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 2c: Paired t-test theo dõi cùng một nhóm ở hai thời điểm và phân tích hiệu số của từng cặp quan sát.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;các-giả-định-của-t-test&quot;&gt;Các Giả định của T-test&lt;/h2&gt;

&lt;p&gt;Kết quả t-test dựa trên ba giả định chính; nếu các giả định này bị vi phạm nghiêm trọng, kết luận có thể sai lệch:&lt;/p&gt;

&lt;h3 id=&quot;1-dữ-liệu-phân-phối-chuẩn-hoặc-cỡ-mẫu-đủ-lớn&quot;&gt;1. Dữ liệu phân phối chuẩn (hoặc cỡ mẫu đủ lớn)&lt;/h3&gt;

&lt;p&gt;Dữ liệu trong mỗi nhóm cần xấp xỉ phân phối chuẩn, hoặc cỡ mẫu đủ lớn (quy tắc kinh nghiệm thường lấy \(n &amp;gt; 30\)) để định lý giới hạn trung tâm (CLT) phát huy tác dụng. Ta có thể kiểm tra bằng histogram, biểu đồ Q-Q (Q-Q plot) hoặc kiểm định Shapiro–Wilk (lưu ý kiểm định này rất nhạy khi cỡ mẫu lớn). Nếu mẫu nhỏ và vi phạm mạnh tính chuẩn, nên cân nhắc kiểm định phi tham số như Wilcoxon; với mẫu lớn, t-test thường vẫn khá bền vững nhờ CLT.&lt;/p&gt;

&lt;h3 id=&quot;2-tính-độc-lập-giữa-các-quan-sát&quot;&gt;2. Tính độc lập giữa các quan sát&lt;/h3&gt;

&lt;p&gt;Các quan sát trong mẫu phải độc lập với nhau. Giả định này thường bị vi phạm khi đo lặp lại nhiều lần trên cùng đối tượng, khi dữ liệu có cấu trúc phân cấp theo nhóm, hoặc khi dữ liệu là chuỗi thời gian có tự tương quan.&lt;/p&gt;

&lt;h3 id=&quot;3-phương-sai-bằng-nhau-đối-với-two-sample-t-test&quot;&gt;3. Phương sai bằng nhau (đối với two-sample t-test)&lt;/h3&gt;

&lt;p&gt;Student’s two-sample t-test giả định hai nhóm có cùng phương sai (homogeneity of variance). Có thể kiểm tra bằng kiểm định Levene hoặc kiểm tra nhanh xem tỷ số \(\frac{s_1}{s_2}\) có vượt quá 2 hay không. Nếu phương sai khác nhau đáng kể, nên dùng &lt;strong&gt;Welch’s t-test&lt;/strong&gt; vì kiểm định này không đòi hỏi giả định phương sai bằng nhau.&lt;/p&gt;

&lt;h2 id=&quot;diễn-giải-kết-quả-t-test&quot;&gt;Diễn giải Kết quả T-test&lt;/h2&gt;

&lt;p&gt;Một kiểm định t trả về hai đại lượng chính:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giá trị t (t-value)&lt;/strong&gt;: đo khoảng cách giữa dữ liệu quan sát và giả thuyết không theo đơn vị sai số chuẩn; \(\vert t\vert\) càng lớn thì bằng chứng chống lại \(H_0\) càng mạnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;P-value&lt;/strong&gt;: xác suất quan sát được giá trị t ít nhất cực đoan như vậy nếu \(H_0\) đúng. P-value nhỏ hơn mức \(\alpha\) (thường là 0.05) thường được gọi là “có ý nghĩa thống kê”, còn p-value lớn chỉ cho biết chưa có đủ bằng chứng để bác bỏ \(H_0\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Lưu ý quan trọng:&lt;/strong&gt; p-value &lt;strong&gt;không&lt;/strong&gt; cho biết xác suất \(H_0\) đúng và &lt;strong&gt;không&lt;/strong&gt; đo tầm quan trọng thực tiễn của hiệu ứng; do đó luôn cần báo cáo kèm &lt;strong&gt;kích thước hiệu ứng (effect size)&lt;/strong&gt; và &lt;strong&gt;khoảng tin cậy (confidence interval)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;ví-dụ-đầy-đủ-one-sample-t-test&quot;&gt;Ví dụ Đầy đủ: One-sample T-test&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bối cảnh:&lt;/strong&gt; Một nhà sản xuất tuyên bố mỗi thanh chocolate nặng 100 g. Ta cân ngẫu nhiên 16 thanh để kiểm chứng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dữ liệu (gram):&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;98, 102, 97, 99, 101, 103, 98, 100, 
99, 101, 97, 102, 100, 98, 101, 99
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Bước 1: Thiết lập giả thuyết.&lt;/strong&gt; Đặt \(H_0: \mu = 100\) (trọng lượng trung bình bằng 100 g), \(H_1: \mu \neq 100\) (trọng lượng trung bình khác 100 g), và chọn mức ý nghĩa \(\alpha = 0.05\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 2: Tính các thống kê mẫu.&lt;/strong&gt; Từ 16 quan sát, ta thu được \(n = 16\), trung bình mẫu \(\bar{x} = 99.69\) g (chính xác là \(1595/16 = 99.6875\) g), và độ lệch chuẩn mẫu \(s = 1.85\) g (chính xác là \(\sqrt{51.4375 / 15} \approx 1.852\) g).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 3: Tính thống kê t.&lt;/strong&gt;&lt;/p&gt;

\[t = \frac{99.6875 - 100}{1.852 / \sqrt{16}} = \frac{-0.3125}{0.463} \approx -0.68\]

&lt;p&gt;&lt;strong&gt;Bước 4: Xác định bậc tự do.&lt;/strong&gt;&lt;/p&gt;

\[df = n - 1 = 16 - 1 = 15\]

&lt;p&gt;&lt;strong&gt;Bước 5: Tính p-value.&lt;/strong&gt; Với \(t \approx -0.68\) và \(df = 15\), kiểm định hai phía cho:&lt;/p&gt;

\[p \approx 0.510\]

&lt;p&gt;&lt;strong&gt;Bước 6: Kết luận.&lt;/strong&gt; Vì \(p = 0.510 &amp;gt; 0.05\), ta &lt;strong&gt;không bác bỏ&lt;/strong&gt; \(H_0\). Chưa có đủ bằng chứng thống kê để kết luận trọng lượng trung bình của thanh chocolate khác 100 g; mức chênh lệch quan sát được (99.69 g so với 100 g) hoàn toàn có thể do biến động lấy mẫu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Khoảng tin cậy 95%:&lt;/strong&gt;&lt;/p&gt;

\[\bar{x} \pm t_{0.025, 15} \times \frac{s}{\sqrt{n}} = 99.69 \pm 2.131 \times 0.463 = [98.70, 100.67]\]

&lt;p&gt;Khoảng tin cậy này chứa giá trị 100 g, nhất quán với kết luận không bác bỏ \(H_0\).&lt;/p&gt;

&lt;h3 id=&quot;đọc-thêm-bằng-kích-thước-hiệu-ứng-effect-size&quot;&gt;Đọc thêm bằng kích thước hiệu ứng (effect size)&lt;/h3&gt;

&lt;p&gt;Chuẩn hóa độ lệch trung bình theo độ lệch chuẩn mẫu (Cohen’s \(d\)):&lt;/p&gt;

\[d = \frac{99.6875 - 100}{1.852} \approx -0.17\]

&lt;p&gt;Đây là kích thước hiệu ứng rất nhỏ: không chỉ p-value lớn mà bản thân độ lệch trung bình cũng không đáng kể về mặt thực tế. Ví dụ này cho thấy một kết quả thống kê nên được đọc qua cả ba góc độ: chiều hướng hiệu ứng, độ lớn hiệu ứng và độ bất định xung quanh ước lượng.&lt;/p&gt;

&lt;h2 id=&quot;so-sánh-t-test-với-z-test&quot;&gt;So sánh T-test với Z-test&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Đặc điểm&lt;/th&gt;
      &lt;th&gt;Z-test&lt;/th&gt;
      &lt;th&gt;T-test&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Điều kiện sử dụng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Biết \(\sigma\) quần thể&lt;/td&gt;
      &lt;td&gt;Không biết \(\sigma\) (ước lượng bằng \(s\))&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Phân phối&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;\(\mathcal{N}(0, 1)\)&lt;/td&gt;
      &lt;td&gt;Phân phối t theo bậc tự do \(df\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Độ dày đuôi&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Mỏng hơn&lt;/td&gt;
      &lt;td&gt;Dày hơn&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Giá trị tới hạn&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Cố định&lt;/td&gt;
      &lt;td&gt;Phụ thuộc vào \(df\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Mức độ sử dụng thực tế&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Ít gặp&lt;/td&gt;
      &lt;td&gt;Rất phổ biến&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Mối liên hệ:&lt;/strong&gt; khi \(n \to \infty\), phân phối t hội tụ về phân phối chuẩn tắc.&lt;/p&gt;

&lt;h2 id=&quot;hạn-chế-của-t-test-và-hướng-tiếp-cận-bayesian&quot;&gt;Hạn chế của T-test và Hướng tiếp cận Bayesian&lt;/h2&gt;

&lt;p&gt;T-test kế thừa các giới hạn cốt lõi của p-value: nó chỉ trả về \(P(\text{data} \mid H_0)\) thay vì \(P(H_0 \mid \text{data})\), dễ dẫn tới quyết định nhị phân theo ngưỡng cố định, không tích hợp được kiến thức tiên nghiệm và có thể sai lệch khi các giả định bị vi phạm.&lt;/p&gt;

&lt;h3 id=&quot;hướng-tiếp-cận-bayesian&quot;&gt;Hướng tiếp cận Bayesian&lt;/h3&gt;

&lt;p&gt;Trong các chương tiếp theo, bạn sẽ thấy thống kê Bayesian khắc phục những điểm này như thế nào: &lt;strong&gt;ước lượng Bayesian&lt;/strong&gt; cung cấp toàn bộ phân phối hậu nghiệm của tham số thay vì chỉ một giá trị t; &lt;strong&gt;khoảng credible&lt;/strong&gt; có diễn giải xác suất trực tiếp; &lt;strong&gt;Bayes factor&lt;/strong&gt; so sánh định lượng mức độ ủng hộ của dữ liệu giữa các giả thuyết; và &lt;strong&gt;phân phối tiên nghiệm (prior)&lt;/strong&gt; cho phép đưa hiểu biết nền vào mô hình một cách minh bạch.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-các-dạng-t-test-cổ-điển--mô-hình-bayes-bền-vững-best&quot;&gt;Video ngắn: Các dạng T-test cổ điển &amp;amp; Mô hình Bayes Bền vững (BEST)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-12b-ttest-robust-best.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): phân biệt 3 dạng t-test, ưu tiên Welch, điểm yếu trước ngoại lai và mô hình Bayes BEST dùng likelihood Student-t.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tính-tay-một-phép-kiểm-định-t-và-nhìn-thấy-hậu-nghiệm-biên-student-t&quot;&gt;Giải thích: Tính tay một phép kiểm định \(t\) và nhìn thấy hậu nghiệm biên Student-\(t\)&lt;/h2&gt;

&lt;p&gt;Hãy đi chậm qua 4 bước để vừa làm chủ phép tính tay T-test cổ điển, vừa nhìn thấy bản chất Bayes ẩn bên trong:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính trung bình mẫu \(\bar{x}\) và độ lệch chuẩn mẫu \(s\)&lt;/strong&gt; (chia cho \(n - 1\), bậc tự do \(\nu = n - 1\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính sai số chuẩn \(\text{SE} = s/\sqrt{n}\):&lt;/strong&gt; Đo độ dao động dự kiến của trung bình mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính thống kê \(t = \frac{\bar{x} - \mu_0}{\text{SE}}\)&lt;/strong&gt; và so với giá trị tới hạn \(t_{\nu, 0.975}\) (với \(\nu = 3\) là \(3.182\), lớn hơn hẳn mốc \(1.96\) của phân phối Chuẩn!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Góc nhìn Bayes tương ứng:&lt;/strong&gt; Với prior không thông tin chuẩn hóa \(p(\mu, \sigma^2) \propto 1/\sigma^2\), phân phối hậu nghiệm chính xác của \(\mu\) sau khi tích phân hóa \(\sigma^2\) chính là phân phối Student-\(t\) dịch chuyển:
\(\frac{\mu - \bar{x}}{s/\sqrt{n}} \;\Big\vert\; \text{data} \;\sim\; t_{n-1}.\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-4-mẻ-thí-nghiệm-nhỏ-kiểm-tra-hàm-lượng-chuẩn-mu_0--100&quot;&gt;Ví dụ tính toán làm từng bước: 4 mẻ thí nghiệm nhỏ kiểm tra hàm lượng chuẩn \(\mu_0 = 100\)&lt;/h3&gt;

&lt;p&gt;Bạn đo hàm lượng hoạt chất trên \(n = 4\) mẫu thử độc lập và thu được: \(x = \{104, 108, 102, 106\}\).&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Trung bình và độ lệch chuẩn mẫu:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(\bar{x} = \frac{104 + 108 + 102 + 106}{4} = \frac{420}{4} = 105\).&lt;/li&gt;
      &lt;li&gt;Độ lệch so với \(105\): \(-1, +3, -3, +1\); tổng bình phương \(= 1 + 9 + 9 + 1 = 20\).&lt;/li&gt;
      &lt;li&gt;\(s^2 = \frac{20}{4 - 1} = \frac{20}{3} \approx 6.667 \implies s \approx 2.582\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Sai số chuẩn và thống kê \(t\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(\text{SE} = \frac{2.582}{\sqrt{4}} = \frac{2.582}{2} = 1.291\).&lt;/li&gt;
      &lt;li&gt;\(t = \frac{105 - 100}{1.291} \approx 3.873\) với bậc tự do \(\nu = 3\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Đối chiếu hai trường phái trên cùng con số:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;em&gt;Frequentist:&lt;/em&gt; Vì \(t = 3.873 &amp;gt; t_{3, 0.975} = 3.182\), ta bác bỏ \(H_0: \mu = 100\) ở mức \(\alpha = 0.05\) (\(p \approx 0.030\)).&lt;/li&gt;
      &lt;li&gt;&lt;em&gt;Bayes (với prior tham chiếu \(1/\sigma^2\)):&lt;/em&gt; Khoảng tin cậy hậu nghiệm 95% của \(\mu\) là \(105 \pm 3.182 \times 1.291 = [100.89, 109.11]\), và ta được phép phát biểu trực tiếp: &lt;em&gt;“Xác suất hậu nghiệm để hàm lượng thật lớn hơn 100 là \(1 - P(T_3 \le -3.873) \approx 98.5\%\).”&lt;/em&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Dùng mốc \(\pm 1.96 \times \text{SE}\) cho mẫu nhỏ \(n = 4\): khoảng thu được sẽ chỉ là \([102.47, 107.53]\) — hẹp giả tạo tới gần 40% vì đã bỏ qua bất định của \(\sigma\)!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Khi \(n\) tăng lên trên 30, giá trị tới hạn \(t_{n-1, 0.975}\) tiến rất sát về \(1.96\) (ví dụ \(t_{30, 0.975} \approx 2.042\)), cho thấy sự bất định do chưa biết \(\sigma\) dần tan biến khi có nhiều dữ liệu.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Uv6nGIgZMVw&quot;&gt;Introduction to the t Distribution (non-technical)&lt;/a&gt; — jbstatistics, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giải thích trực quan vì sao phải dùng phân phối t thay cho phân phối chuẩn khi ước lượng độ lệch chuẩn từ mẫu.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Introduction to t statistics&lt;/td&gt;
          &lt;td&gt;Confidence intervals&lt;/td&gt;
          &lt;td&gt;AP Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=a2rd4Qy8yNI) — Khan Academy, English. Trình bày thống kê t và khoảng tin cậy tương ứng qua ví dụ cụ thể.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=nnBJeb_I-q8&quot;&gt;StatQuickie: Which t test to use&lt;/a&gt; — StatQuest with Josh Starmer, English. Hướng dẫn chọn đúng loại t-test theo thiết kế thu thập mẫu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 1: Tính thống kê t thủ công.&lt;/strong&gt; Đo điểm kiểm tra của 10 sinh viên học theo phương pháp mới: 78, 82, 75, 80, 77, 83, 79, 81, 76, 84. Biết điểm trung bình toàn quốc là 75. (a) Tính \(\bar{x}\) và \(s\). (b) Tính thống kê t cho giả thuyết \(H_0: \mu = 75\). (c) Với \(\alpha = 0.05\) (hai phía), tra bảng t và nêu kết luận.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 2: Phân biệt các loại t-test.&lt;/strong&gt; Xác định dạng t-test phù hợp cho từng tình huống: (a) so sánh điểm thi của học sinh nam và nữ; (b) so sánh huyết áp trước và sau khi tập thể dục của cùng một nhóm người; (c) kiểm tra nhiệt độ trung bình hàng ngày có khác 25°C hay không; (d) so sánh hiệu quả hai loại thuốc trên hai nhóm bệnh nhân độc lập.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 3: Diễn giải kết quả.&lt;/strong&gt; Một kiểm định t cho kết quả \(t(24) = 2.35, p = 0.027\). (a) \(df = 24\) cho biết điều gì? (b) Với \(\alpha = 0.05\), kết luận ra sao? (c) Nếu chuyển sang kiểm định một phía (đúng chiều), p-value thay đổi thế nào? (d) Viết một câu diễn giải chuẩn xác cho p-value này.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 4: Kiểm tra giả định.&lt;/strong&gt; Bạn có dữ liệu chiều cao của 15 người trong đó xuất hiện một giá trị ngoại lai rõ rệt. (a) Giả định nào của t-test có nguy cơ bị vi phạm? (b) Kiểm tra giả định phân phối chuẩn bằng cách nào? (c) Khi giả định bị vi phạm nặng ở mẫu nhỏ, nên xử lý ra sao? (d) Có phương pháp nào thay thế tốt hơn t-test trong tình huống này không?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 5: T-test và Bayesian (suy ngẫm).&lt;/strong&gt; Xem lại ví dụ chocolate ở trên. (a) Khoảng tin cậy 95% \([98.70, 100.67]\) có ý nghĩa chính xác là gì theo quan điểm tần suất? (b) Ở góc độ nhà sản xuất, kết luận “chưa đủ bằng chứng bác bỏ \(H_0\)” đã đủ cho quyết định thực tế chưa? (c) Những thông tin nào bạn muốn biết mà t-test không cung cấp trực tiếp? (d) Phương pháp Bayesian có thể giải quyết những câu hỏi đó như thế nào?&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu Tham khảo&lt;/h2&gt;

&lt;h3 id=&quot;primary-references&quot;&gt;Primary References:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., &amp;amp; Rubin, D. B. (2013).&lt;/strong&gt; &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 4: Asymptotics and connections to non-Bayesian approaches&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kruschke, J. K. (2015).&lt;/strong&gt; &lt;em&gt;Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan&lt;/em&gt; (2nd Edition). Academic Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 11: Null Hypothesis Significance Testing&lt;/li&gt;
  &lt;li&gt;Chapter 16: Metric-Predicted Variable on One or Two Groups&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;classic-reference&quot;&gt;Classic Reference:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Student (W.S. Gosset). (1908).&lt;/strong&gt; The probable error of a mean. &lt;em&gt;Biometrika&lt;/em&gt;, 6(1), 1-25.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Bài báo gốc giới thiệu phân phối t.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;supplementary-reading&quot;&gt;Supplementary Reading:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Zimmerman, D. W. (1997).&lt;/strong&gt; A note on interpretation of the paired-samples t test. &lt;em&gt;Journal of Educational and Behavioral Statistics&lt;/em&gt;, 22(3), 349-360.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Delacre, M., Lakens, D., &amp;amp; Leys, C. (2017).&lt;/strong&gt; Why psychologists should by default use Welch’s t-test instead of Student’s t-test. &lt;em&gt;International Review of Social Psychology&lt;/em&gt;, 30(1), 92-101.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_11_joint_distribution/&quot;&gt;0.13 Phân phối đồng thời (Joint Distribution)&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.11: P-values và Kiểm định Giả thuyết</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_08_pvalues_and_hypothesis_testing/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_08_pvalues_and_hypothesis_testing</id>
   <content type="html">&lt;p&gt;Một buổi chiều mùa hè thập niên 1920 ở Cambridge, một nữ đồng nghiệp tuyên bố bà có thể nếm ra tách trà được rót sữa trước hay rót trà trước. Ronald Fisher lập tức thiết kế thí nghiệm pha 8 tách trà (4 sữa trước, 4 trà trước) và tính xác suất đoán đúng hết nếu chỉ đoán mò: \(1 / \binom{8}{4} = 1/70 \approx 0.014\). Từ tách trà ấy, khái niệm &lt;strong&gt;p-value&lt;/strong&gt; ra đời — ban đầu chỉ là một thước đo bằng chứng nhẹ nhàng chống lại giả thuyết ngẫu nhiên, nhưng về sau bị biến thành “cửa ải \(p &amp;lt; 0.05\)” đầy tranh cãi trong khoa học hiện đại.&lt;/p&gt;

&lt;p&gt;Muốn hiểu vì sao thống kê Bayes ngày càng được giới nghiên cứu ưa chuộng, trước hết ta phải hiểu &lt;strong&gt;chính xác&lt;/strong&gt; kiểm định giả thuyết cổ điển đang tính cái gì — và đâu là ranh giới nó không thể vượt qua.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu Học tập&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành bài học này, bạn sẽ hiểu rõ bản chất của &lt;strong&gt;p-value&lt;/strong&gt; và kiểm định giả thuyết theo quan điểm tần suất (&lt;strong&gt;frequentist&lt;/strong&gt;), không chỉ để áp dụng đúng mà quan trọng hơn là nhận diện rõ các giới hạn của chúng. Bạn sẽ hiểu vì sao p-value thường bị diễn giải sai, vì sao nó không trả lời trực tiếp nhiều câu hỏi mà nhà khoa học quan tâm, và vì sao &lt;strong&gt;phương pháp Bayesian mang lại cách tiếp cận tự nhiên và mạch lạc hơn cho suy diễn thống kê&lt;/strong&gt;. Mục tiêu không phải loại bỏ hoàn toàn kiểm định giả thuyết, mà là sử dụng nó một cách phản biện và biết khi nào cần chuyển sang công cụ khác.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-kiểm-định-frequentist-sai-lầm-loại-iii-và-góc-nhìn-đối-sánh-bayes&quot;&gt;Kiến thức cần nhớ: Kiểm định Frequentist, Sai lầm loại I/II và Góc nhìn đối sánh Bayes&lt;/h2&gt;

&lt;p&gt;Ba trụ cột giúp bạn đọc sâu bài này mà không rơi vào tranh cãi cảm tính giữa hai trường phái:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm định ý nghĩa thống kê (NHST — Fisher &amp;amp; Neyman–Pearson):&lt;/strong&gt; Giả định trước giả thuyết không \(H_0\) là đúng, rồi tính xác suất thu được dữ liệu cực đoan bằng hoặc hơn dữ liệu đã quan sát: \(p\text{-value} = P(\text{dữ liệu cực đoan} \ge \text{quan sát} \mid H_0)\). Chú ý chiều điều kiện: \(H_0\) nằm ở &lt;em&gt;vế sau&lt;/em&gt; dấu gạch đứng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lực thống kê &amp;amp; Tỷ lệ dương tính giả (Power &amp;amp; Base Rate):&lt;/strong&gt; Ngưỡng \(\alpha = 0.05\) chỉ kiểm soát tỷ lệ báo động giả &lt;em&gt;khi \(H_0\) đúng&lt;/em&gt;. Nó hoàn toàn phớt lờ xác suất tiên nghiệm \(P(H_1)\) (giả thuyết có hợp lý không trước khi làm thí nghiệm?) và lực kiểm định \(1 - \beta\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Thống kê Bayes (Posterior &amp;amp; Bayes Factor):&lt;/strong&gt; Điều nhà khoa học thực sự muốn biết là \(P(H_0 \mid \text{data})\) hoặc phân phối hậu nghiệm của độ lớn hiệu ứng \(\delta \mid \text{data}\). Định lý Bayes cho thấy muốn đảo chiều từ \(P(\text{data} \mid H_0)\) sang \(P(H_0 \mid \text{data})\), ta &lt;em&gt;bắt buộc&lt;/em&gt; phải đưa vào prior \(P(H_0)\) và so sánh với likelihood dưới \(H_1\).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-tại-sao-chúng-ta-cần-nói-về-p-values&quot;&gt;Giới thiệu: Tại sao chúng ta cần nói về P-values?&lt;/h2&gt;

&lt;p&gt;Trong một khóa học về phân tích dữ liệu Bayesian, việc tìm hiểu kỹ p-value và kiểm định giả thuyết theo trường phái tần suất xuất phát từ ba lý do chính:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính phổ biến trong nghiên cứu&lt;/strong&gt;: p-value và kiểm định giả thuyết vẫn là công cụ được dùng rộng rãi nhất trong y học, tâm lý học, kinh tế học và nhiều ngành khoa học khác. Để đọc và đánh giá bài báo khoa học một cách phản biện, cần hiểu chính xác ý nghĩa của p-value.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tần suất hiểu sai rất cao&lt;/strong&gt;: p-value thuộc nhóm khái niệm thống kê dễ bị hiểu nhầm nhất, kể cả trong cộng đồng nghiên cứu. Nắm đúng định nghĩa giúp tránh các diễn giải sai lệch.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Động lực cho cách tiếp cận Bayesian&lt;/strong&gt;: thấy rõ những câu hỏi mà p-value không trả lời được sẽ giúp bạn hiểu vì sao khuôn khổ Bayesian phù hợp và trực tiếp hơn trong nhiều bài toán suy luận.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;khung-kiểm-định-giả-thuyết-một-cách-tiếp-cận-gián-tiếp&quot;&gt;Khung Kiểm định Giả thuyết: Một Cách Tiếp cận Gián tiếp&lt;/h2&gt;

&lt;p&gt;Kiểm định giả thuyết theo quan điểm tần suất dựa trên lập luận gián tiếp. Thay vì đánh giá trực tiếp bằng chứng ủng hộ giả thuyết ta quan tâm, ta đặt ra một &lt;strong&gt;giả thuyết không&lt;/strong&gt; (null hypothesis), ký hiệu \(H_0\), biểu thị trạng thái “không có hiệu ứng” hay “không có sự khác biệt”, rồi tìm bằng chứng chống lại nó.&lt;/p&gt;

&lt;p&gt;Ví dụ, khi đánh giá một loại thuốc mới có làm giảm huyết áp hay không, thay vì hỏi trực tiếp “thuốc có hiệu quả không?” hoặc “mức giảm huyết áp là bao nhiêu?”, khung kiểm định giả thuyết yêu cầu thiết lập: &lt;strong&gt;giả thuyết không&lt;/strong&gt; \(H_0\) (thuốc không có tác dụng, mức thay đổi huyết áp trung bình bằng 0) và &lt;strong&gt;giả thuyết thay thế&lt;/strong&gt; \(H_1\) (thuốc có tác dụng, mức thay đổi trung bình khác 0).&lt;/p&gt;

&lt;p&gt;Logic kiểm định là: &lt;strong&gt;nếu dữ liệu quan sát được rất khó xảy ra trong trường hợp \(H_0\) đúng, thì ta có bằng chứng chống lại \(H_0\) và có thể “bác bỏ” nó&lt;/strong&gt;. Lập luận này tương tự phép chứng minh phản chứng trong toán học, nhưng có một điểm khác biệt cơ bản: &lt;strong&gt;trong thống kê, ta không chứng minh tuyệt đối được điều gì mà chỉ định lượng mức độ bất thường của dữ liệu dưới \(H_0\)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Khung tư duy này được phát triển từ đầu thế kỷ 20 bởi Ronald Fisher, Jerzy Neyman và Egon Pearson nhằm tạo ra một quy trình ra quyết định khách quan từ dữ liệu. Tuy nhiên, như ta sẽ thấy dưới đây, cách tiếp cận gián tiếp này cũng kéo theo nhiều giới hạn thực tế.&lt;/p&gt;

&lt;h2 id=&quot;p-value-định-nghĩa-chính-xác&quot;&gt;P-value: Định nghĩa Chính xác&lt;/h2&gt;

&lt;p&gt;Hãy bắt đầu bằng định nghĩa chuẩn xác của p-value:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;P-value là xác suất quan sát được dữ liệu ít nhất bất thường như dữ liệu thực tế (hoặc cực đoan hơn), với điều kiện giả thuyết không \(H_0\) là đúng.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Một cách hình thức, nếu \(T\) là &lt;strong&gt;thống kê kiểm định&lt;/strong&gt; (test statistic) tính từ dữ liệu và \(t_{obs}\) là giá trị quan sát được, thì (với kiểm định một phía bên phải):&lt;/p&gt;

\[p = P(T \geq t_{obs} \mid H_0)\]

&lt;p&gt;(và công thức tương tự cho kiểm định một phía bên trái hoặc hai phía).&lt;/p&gt;

&lt;p&gt;Định nghĩa này gồm ba thành phần then chốt:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;“Xác suất”&lt;/strong&gt;: p-value là một số nằm trong đoạn \([0, 1]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;“Ít nhất bất thường như dữ liệu thực tế”&lt;/strong&gt;: không chỉ tính xác suất của riêng kết quả quan sát được mà gộp cả mọi kết quả cực đoan hơn theo hướng kiểm định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;“Với điều kiện giả thuyết không là đúng”&lt;/strong&gt;: p-value &lt;strong&gt;không&lt;/strong&gt; phải xác suất để \(H_0\) đúng, mà là xác suất của dữ liệu &lt;strong&gt;nếu&lt;/strong&gt; \(H_0\) đúng.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Sự khác biệt giữa \(P(\text{dữ liệu} \mid H_0)\) và \(P(H_0 \mid \text{dữ liệu})\) mang tính nền tảng. P-value cho biết vế thứ nhất, trong khi câu hỏi nhà nghiên cứu thường muốn trả lời lại là vế thứ hai.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;giải-thích-từng-thành-phần&quot;&gt;Giải thích từng thành phần&lt;/h3&gt;

&lt;h4 id=&quot;1-giả-thuyết-không-là-đúng-h_0-đúng&quot;&gt;(1) “Giả thuyết không là đúng” (\(H_0\) đúng)&lt;/h4&gt;

&lt;p&gt;Ta luôn &lt;strong&gt;giả định trước&lt;/strong&gt; rằng \(H_0\) đúng, rồi hỏi: nếu \(H_0\) đúng thật, xác suất để dữ liệu xuất hiện cực đoan như thế này có thấp không? Ví dụ, nếu \(H_0\) cho rằng thuốc không có tác dụng nhưng dữ liệu lại có vẻ khả quan, p-value trả lời câu hỏi: “nếu thuốc thực sự vô tác dụng, xác suất để vẫn quan sát được kết quả ít nhất cực đoan như vậy là bao nhiêu?”&lt;/p&gt;

&lt;h4 id=&quot;2-dữ-liệu-bất-thường-nghĩa-là-gì&quot;&gt;(2) “Dữ liệu bất thường” nghĩa là gì?&lt;/h4&gt;

&lt;p&gt;“Bất thường” không phải cảm nhận chủ quan mà được đo bằng &lt;strong&gt;thống kê kiểm định&lt;/strong&gt; như z-score, t-statistic hay \(\chi^2\), phản ánh khoảng cách giữa dữ liệu quan sát và kỳ vọng dưới \(H_0\). Trung bình mẫu lệch càng xa giá trị giả thuyết, chênh lệch giữa hai nhóm càng lớn, hay giá trị thống kê rơi càng sâu vào phần đuôi phân phối, dữ liệu càng được xem là cực đoan.&lt;/p&gt;

&lt;h4 id=&quot;3-ít-nhất-bất-thường-như-dữ-liệu-quan-sát-hoặc-bất-thường-hơn&quot;&gt;(3) “Ít nhất bất thường như dữ liệu quan sát (hoặc bất thường hơn)”&lt;/h4&gt;

&lt;p&gt;P-value &lt;strong&gt;không chỉ&lt;/strong&gt; tính xác suất của đúng giá trị quan sát được, mà tính:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Xác suất của kết quả quan sát được &lt;strong&gt;và toàn bộ các kết quả còn cực đoan hơn&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ (kiểm định hai phía):&lt;/strong&gt; nếu quan sát được \(z = 2.1\), p-value là \(P(\mid Z \mid \geq 2.1 \mid H_0 \text{ đúng})\), tức gộp cả các giá trị như 2.5, 3.0 và mọi giá trị cực đoan hơn ở cả hai phía đuôi phân phối.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;những-điều-p-value-không-nói&quot;&gt;Những điều P-value KHÔNG nói&lt;/h3&gt;

&lt;p&gt;P-value không phải xác suất giả thuyết không đúng hay sai, không phải xác suất kết quả “xảy ra do ngẫu nhiên”, và cũng không đo trực tiếp kích thước hiệu ứng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Diễn giải sai:&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“P-value = 0.03 nghĩa là 97% khả năng \(H_0\) sai.” ❌&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Diễn giải đúng:&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Nếu \(H_0\) đúng, xác suất quan sát được dữ liệu ít nhất cực đoan như thế này là 3%.” ✅&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;diễn-giải-trực-giác-ngắn-gọn&quot;&gt;Diễn giải trực giác ngắn gọn&lt;/h3&gt;

&lt;p&gt;Có thể gói gọn bản chất của p-value như sau: &lt;strong&gt;p-value đo mức độ khó tin của dữ liệu dưới giả định rằng \(H_0\) đúng.&lt;/strong&gt; Khi p-value nhỏ, dữ liệu khó phù hợp với \(H_0\) nên ta có lý do nghi ngờ \(H_0\); khi p-value lớn, dữ liệu chưa mâu thuẫn mạnh với \(H_0\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;video-ngắn-thí-nghiệm-tách-trà-fisher--bản-chất-p-value&quot;&gt;Video ngắn: Thí nghiệm Tách trà Fisher &amp;amp; Bản chất P-value&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-11a-fisher-tea-pvalue.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): thí nghiệm 8 tách trà của Fisher (1/70 ≈ 0.0143), định nghĩa chuẩn p-value, ranh giới 0.05, bẫy cỡ mẫu lớn và kiểm định lặp.&lt;/p&gt;

&lt;h2 id=&quot;một-ví-dụ-cụ-thể-kiểm-định-t&quot;&gt;Một Ví dụ Cụ thể: Kiểm định T&lt;/h2&gt;

&lt;p&gt;Giả sử ta muốn kiểm tra chiều cao trung bình của nam sinh viên tại một trường đại học có khác 170 cm hay không. Ta đo ngẫu nhiên 25 nam sinh viên và thu được trung bình mẫu \(\bar{x} = 172.5\) cm, độ lệch chuẩn mẫu \(s = 6.2\) cm.&lt;/p&gt;

&lt;p&gt;Ta thiết lập \(H_0: \mu = 170\) (chiều cao trung bình quần thể bằng 170 cm) và \(H_1: \mu \neq 170\) (chiều cao trung bình quần thể khác 170 cm). Thống kê kiểm định t là:&lt;/p&gt;

\[t = \frac{\bar{x} - \mu_0}{s / \sqrt{n}} = \frac{172.5 - 170}{6.2 / \sqrt{25}} = \frac{2.5}{1.24} \approx 2.02\]

&lt;p&gt;Với \(n - 1 = 24\) bậc tự do, xác suất để quan sát được \(\mid t \mid \geq 2.02\) nếu \(H_0\) đúng (kiểm định hai phía) là \(p \approx 0.054\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_ttest_illustration.png&quot; alt=&quot;Minh họa P-value trong Kiểm định T&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Đường cong biểu diễn phân phối t dưới giả thuyết \(H_0\); phần diện tích tô màu ở hai đuôi ngoài mốc \(\pm 2.02\) chính là p-value hai phía.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Kết quả này có nghĩa là: &lt;strong&gt;nếu&lt;/strong&gt; chiều cao trung bình quần thể thực sự bằng 170 cm và ta lặp lại việc lấy mẫu ngẫu nhiên 25 người rất nhiều lần, khoảng 5.4% số lần sẽ cho trị tuyệt đối của thống kê t lớn hơn hoặc bằng 2.02. Nó không cho biết xác suất \(H_0\) đúng là 5.4%, không cho biết xác suất \(H_1\) đúng là 94.6%, và cũng không nói lên độ lớn hay ý nghĩa thực tiễn của sự chênh lệch.&lt;/p&gt;

&lt;h3 id=&quot;cách-đọc-hợp-lý-hơn-cho-p--0054&quot;&gt;Cách đọc hợp lý hơn cho \(p = 0.054\)&lt;/h3&gt;

&lt;p&gt;Con số \(0.054\) nằm rất sát ngưỡng 0.05. Thay vì coi đó là “thất bại hoàn toàn”, cách hiểu hợp lý hơn là dữ liệu tạo ra mức mâu thuẫn vừa phải với \(H_0\) nhưng chưa đủ mạnh theo quy ước truyền thống. Một nghiên cứu tương tự cho ra \(p = 0.049\) thực chất mang lượng bằng chứng gần như tương đương.&lt;/p&gt;

&lt;p&gt;Vì thế, nhiều nhà thống kê khuyến nghị không dùng p-value như một công tắc bật/tắt nhị phân, mà cần đọc song song với kích thước hiệu ứng (effect size), khoảng tin cậy (confidence interval), chất lượng thiết kế nghiên cứu và bối cảnh khoa học.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-p-value-dưới-h-phân-phối-đều&quot;&gt;Thử nghiệm: p-value dưới H₀ phân phối đều&lt;/h3&gt;

&lt;p&gt;Lặp thí nghiệm nhiều lần: khi không có hiệu ứng vẫn có ~5% thí nghiệm cho p &amp;lt; 0.05.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;pvalue-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;pnull&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;ngưỡng-ý-nghĩa-và-quyết-định-quy-ước-alpha--005&quot;&gt;Ngưỡng Ý nghĩa và Quyết định: Quy ước \(\alpha = 0.05\)&lt;/h2&gt;

&lt;p&gt;Trong thực hành, p-value thường được so sánh với &lt;strong&gt;mức ý nghĩa&lt;/strong&gt; (significance level) định trước \(\alpha\), phổ biến nhất là \(\alpha = 0.05\) (đôi khi là 0.01 hoặc 0.10).&lt;/p&gt;

&lt;h4 id=&quot;quy-tắc-quyết-định-truyền-thống&quot;&gt;Quy tắc quyết định truyền thống:&lt;/h4&gt;

&lt;p&gt;Nếu \(p &amp;lt; \alpha\), ta bác bỏ \(H_0\) và gọi kết quả là “có ý nghĩa thống kê”; nếu \(p \geq \alpha\), ta không bác bỏ \(H_0\) và kết luận chưa đủ bằng chứng chống lại nó.&lt;/p&gt;

&lt;p&gt;Trong ví dụ chiều cao ở trên, với \(p = 0.054\) và \(\alpha = 0.05\), ta &lt;strong&gt;không bác bỏ&lt;/strong&gt; \(H_0\). Tuy nhiên, hãy chú ý rằng chênh lệch giữa \(p = 0.054\) và \(p = 0.049\) rất nhỏ nhưng lại dẫn đến hai kết luận trái ngược nhau (“không có ý nghĩa thống kê” so với “có ý nghĩa thống kê”), dù bằng chứng thực tế trong dữ liệu gần như giống nhau.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_misinterpretation_alpha_cutoff.png&quot; alt=&quot;Hai p-value gần nhau nhưng rơi hai phía của ngưỡng alpha&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình minh họa: Khi p-value nằm sát ngưỡng \(\alpha = 0.05\), một chênh lệch rất nhỏ vẫn bị chia cắt thành hai kết luận nhị phân trái ngược.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Bản thân ngưỡng \(\alpha = 0.05\) cũng mang tính quy ước. Ronald Fisher khi đề xuất mốc này đã nhấn mạnh đây chỉ là chỉ dẫn sơ bộ, không phải ranh giới cứng nhắc. Việc áp dụng máy móc ngưỡng 0.05 dẫn đến nhiều hệ quả tiêu cực: khuyến khích hành vi “p-hacking”, thu hẹp suy luận thành câu hỏi nhị phân “có hay không có hiệu ứng”, và làm mờ đi kích thước hiệu ứng cùng độ bất định của ước lượng.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-công-suất-của-t-test&quot;&gt;Thử nghiệm: công suất của t-test&lt;/h3&gt;

&lt;p&gt;Công suất tăng theo cỡ mẫu và độ lớn hiệu ứng; tại d = 0 nó bằng α.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;pvalue-explainer&quot; data-lang=&quot;vi&quot; data-tab=&quot;power&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;những-hiểu-lầm-phổ-biến-về-p-values&quot;&gt;Những Hiểu lầm Phổ biến về P-values&lt;/h2&gt;

&lt;p&gt;Dưới đây là năm hiểu lầm hay gặp nhất khi diễn giải p-value:&lt;/p&gt;

&lt;h3 id=&quot;hiểu-lầm-1-p-value-là-xác-suất-giả-thuyết-không-đúng&quot;&gt;Hiểu lầm 1: P-value là xác suất giả thuyết không đúng&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Sai:&lt;/strong&gt; “\(p = 0.03\) nghĩa là có 3% khả năng giả thuyết không đúng.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đúng:&lt;/strong&gt; P-value là xác suất của dữ liệu (hoặc dữ liệu cực đoan hơn) &lt;strong&gt;khi giả định&lt;/strong&gt; \(H_0\) đúng, không phải xác suất \(H_0\) đúng sau khi đã quan sát dữ liệu. Muốn tính \(P(H_0 \mid \text{dữ liệu})\), cần dùng định lý Bayes cùng xác suất tiên nghiệm cho \(H_0\) — điều mà khung tần suất không cung cấp.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_misinterpretation_h0_probability.png&quot; alt=&quot;P-value không phải là xác suất của giả thuyết không&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình minh họa: P-value phản ánh xác suất theo chiều \(P(\text{dữ liệu} \mid H_0)\), chứ không phải chiều \(P(H_0 \mid \text{dữ liệu})\) mà nhà nghiên cứu thường muốn biết.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;hiểu-lầm-2-1---p-là-xác-suất-giả-thuyết-thay-thế-đúng&quot;&gt;Hiểu lầm 2: \(1 - p\) là xác suất giả thuyết thay thế đúng&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Sai:&lt;/strong&gt; “Nếu \(p = 0.05\) thì có 95% khả năng giả thuyết thay thế đúng.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đúng:&lt;/strong&gt; P-value không cung cấp thông tin trực tiếp về xác suất của giả thuyết thay thế.&lt;/p&gt;

&lt;h3 id=&quot;hiểu-lầm-3-p-value-nhỏ-có-nghĩa-là-hiệu-ứng-lớn&quot;&gt;Hiểu lầm 3: P-value nhỏ có nghĩa là hiệu ứng lớn&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Sai:&lt;/strong&gt; “\(p &amp;lt; 0.001\) nghĩa là hiệu ứng rất mạnh.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đúng:&lt;/strong&gt; P-value nhỏ chỉ cho thấy dữ liệu rất khó xảy ra nếu \(H_0\) đúng. Điều đó có thể đến từ hiệu ứng lớn, nhưng cũng có thể đến từ cỡ mẫu rất lớn kèm một hiệu ứng thực tế cực nhỏ và không có ý nghĩa ứng dụng.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_misinterpretation_small_p_large_effect.png&quot; alt=&quot;P-value nhỏ không đồng nghĩa hiệu ứng lớn&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình minh họa: Một p-value rất nhỏ vẫn có thể xuất hiện với hiệu ứng nhỏ nếu cỡ mẫu đủ lớn.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_large_n_small_effect.png&quot; alt=&quot;Mẫu lớn với hiệu ứng nhỏ&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1a: Với cỡ mẫu lớn (n = 1000), một hiệu ứng rất nhỏ vẫn có thể đạt ngưỡng “có ý nghĩa thống kê”.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_small_n_large_effect.png&quot; alt=&quot;Mẫu nhỏ với hiệu ứng lớn&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1b: Với cỡ mẫu nhỏ (n = 20), ngay cả hiệu ứng lớn cũng có thể không đạt ngưỡng ý nghĩa thống kê. Vì vậy, p-value không đo trực tiếp kích thước hiệu ứng.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;hiểu-lầm-4-p-value-lớn-chứng-minh-giả-thuyết-không-đúng&quot;&gt;Hiểu lầm 4: P-value lớn chứng minh giả thuyết không đúng&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Sai:&lt;/strong&gt; “\(p = 0.80\) chứng tỏ giả thuyết không là đúng.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đúng:&lt;/strong&gt; P-value lớn chỉ cho biết dữ liệu không mâu thuẫn mạnh với \(H_0\). Nguyên nhân có thể là \(H_0\) thực sự đúng, hoặc đơn giản là cỡ mẫu quá nhỏ chưa đủ công suất để phát hiện sự khác biệt. “Không có bằng chứng về hiệu ứng” không đồng nghĩa với “bằng chứng rằng không có hiệu ứng”.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_misinterpretation_large_p_h0_true.png&quot; alt=&quot;P-value lớn không chứng minh giả thuyết không đúng&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình minh họa: P-value lớn chỉ cho thấy dữ liệu không mâu thuẫn mạnh với \(H_0\), chứ không chứng minh \(H_0\) đúng.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;hiểu-lầm-5-p-value-đo-lường-khả-năng-tái-lập&quot;&gt;Hiểu lầm 5: P-value đo lường khả năng tái lập&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Sai:&lt;/strong&gt; “\(p = 0.05\) nghĩa là nếu lặp lại nghiên cứu, tôi có 95% cơ hội thu được kết quả tương tự.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đúng:&lt;/strong&gt; P-value không đo khả năng tái lập. Trên thực tế, nhiều kết quả có \(p\) sát mốc 0.05 rất khó tái lập trong các nghiên cứu độc lập sau đó.&lt;/p&gt;

&lt;h2 id=&quot;vấn-đề-với-kiểm-định-giả-thuyết-không&quot;&gt;Vấn đề với Kiểm định Giả thuyết Không&lt;/h2&gt;

&lt;p&gt;Một hạn chế nền tảng của kiểm định giả thuyết là bản thân \(H_0\) dạng điểm thường khó xảy ra chính xác trong thực tế. Chẳng hạn, giả thuyết “thuốc A và thuốc B có hiệu quả hoàn toàn bằng nhau” gần như chắc chắn sai ở mức sai khác rất nhỏ. Khi cỡ mẫu đủ lớn, ta gần như luôn bác bỏ được \(H_0\), nhưng kết quả đó không cho biết sự khác biệt có đủ lớn để có giá trị lâm sàng hay thực tiễn hay không.&lt;/p&gt;

&lt;p&gt;Câu hỏi trọng tâm của nghiên cứu khoa học thường là “hiệu ứng lớn đến mức nào?” và “độ bất định của ước lượng ra sao?” — những câu hỏi mà kiểm định giả thuyết không trả lời trực tiếp.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/multiple_testing_false_positive_example.png&quot; alt=&quot;Một ví dụ false positive khi kiểm định lặp lại nhiều lần&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 2a: Khi thực hiện nhiều kiểm định độc lập, chỉ riêng biến động ngẫu nhiên cũng dễ tạo ra một vài kết quả vượt ngưỡng ý nghĩa thống kê.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/multiple_testing_uniform_pvalues.png&quot; alt=&quot;Phân phối p-value gần uniform khi H0 đúng&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 2b: Khi \(H_0\) đúng, p-value phân bố đều trên đoạn \([0,1]\), nên thử đủ nhiều kiểm định gần như chắc chắn sẽ xuất hiện vài p-value nhỏ.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Đây chính là bản chất của bài toán kiểm định bội (multiple testing) và p-hacking: khi chạy 20 kiểm định độc lập với \(\alpha = 0.05\) dù tất cả \(H_0\) đều đúng, ta vẫn kỳ vọng gặp trung bình 1 kết quả “có ý nghĩa thống kê” thuần túy do ngẫu nhiên. Đây là một nguyên nhân lớn dẫn đến khủng hoảng tái lập trong khoa học.&lt;/p&gt;

&lt;h2 id=&quot;khoảng-tin-cậy-một-cách-tiếp-cận-tốt-hơn&quot;&gt;Khoảng Tin cậy: Một Cách Tiếp cận Tốt hơn?&lt;/h2&gt;

&lt;p&gt;Một công cụ tần suất khác thường được khuyến nghị thay cho việc chỉ báo cáo p-value là &lt;strong&gt;khoảng tin cậy&lt;/strong&gt; (confidence interval). Khoảng tin cậy 95% cho tham số \(\theta\) là một khoảng ngẫu nhiên \([L, U]\) xây dựng từ dữ liệu sao cho:&lt;/p&gt;

\[P(L \leq \theta \leq U) = 0.95\]

&lt;p&gt;trong đó xác suất được tính trên toàn bộ các mẫu lặp lại có thể (với \(\theta\) là hằng số cố định).&lt;/p&gt;

&lt;p&gt;Khoảng tin cậy cung cấp thêm thông tin về độ lớn hiệu ứng và độ bất định, nhưng cách diễn giải chuẩn vẫn dễ gây nhầm lẫn:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Diễn giải đúng:&lt;/strong&gt; “Nếu lặp lại quy trình lấy mẫu và dựng khoảng tin cậy 95% rất nhiều lần, thì 95% số khoảng thu được sẽ chứa giá trị thật của \(\theta\).”&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/confidence_interval_repeated_experiments.png&quot; alt=&quot;Nhiều confidence interval qua các lần lặp thí nghiệm&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 3a: Khoảng tin cậy tần suất là phát biểu về quy trình lặp lại thí nghiệm: trên nhiều lần lặp, khoảng 95% số khoảng chứa giá trị thật.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Diễn giải sai (nhưng rất phổ biến):&lt;/strong&gt; “Có 95% khả năng giá trị thật của \(\theta\) nằm trong khoảng cụ thể này.”&lt;/p&gt;

&lt;p&gt;Trong khung tần suất, \(\theta\) là hằng số chưa biết chứ không phải biến ngẫu nhiên, nên xác suất 95% gắn với bản thân quy trình tạo khoảng, không phải với \(\theta\). Trong khi đó, phát biểu thứ hai — đánh giá trực tiếp xác suất tham số nằm trong một khoảng dựa trên dữ liệu hiện có — lại chính là ý nghĩa của &lt;strong&gt;khoảng tin cậy Bayesian&lt;/strong&gt; (credible interval).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/credible_interval_single_posterior.png&quot; alt=&quot;Một credible interval trên posterior của một thí nghiệm cụ thể&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 3b: Khoảng credible được xác định trực tiếp từ phân phối hậu nghiệm của thí nghiệm hiện tại, cho phép phát biểu trực tiếp về xác suất tham số nằm trong khoảng đó.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;tại-sao-p-values-vẫn-được-sử-dụng-rộng-rãi&quot;&gt;Tại sao P-values Vẫn Được Sử dụng Rộng rãi?&lt;/h2&gt;

&lt;p&gt;Bất chấp các hạn chế trên, p-value vẫn phổ biến vì bốn lý do chính: quán tính lịch sử và giảng dạy kéo dài nhiều thập kỷ; vẻ ngoài đơn giản khi gói gọn phân tích vào một con số và một ngưỡng quyết định; áp lực xuất bản khi nhiều tạp chí vẫn ưu tiên kết quả có \(p &amp;lt; 0.05\); và việc nhiều nhà nghiên cứu chưa được đào tạo bài bản về các phương pháp thay thế như Bayesian. Dù vậy, xu hướng đang dần thay đổi khi nhiều hiệp hội thống kê và tạp chí khoa học lớn đã lên tiếng cảnh báo việc lạm dụng p-value.&lt;/p&gt;

&lt;h3 id=&quot;thử-nghiệm-khoảng-tin-cậy-và-khoảng-đáng-tin&quot;&gt;Thử nghiệm: khoảng tin cậy và khoảng đáng tin&lt;/h3&gt;

&lt;p&gt;Lặp thí nghiệm nhiều lần để thấy ý nghĩa tần suất của “95%”.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;interval-explainer&quot; data-lang=&quot;vi&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;phương-pháp-bayesian-một-cách-tiếp-cận-tự-nhiên-hơn&quot;&gt;Phương pháp Bayesian: Một Cách Tiếp cận Tự nhiên hơn&lt;/h2&gt;

&lt;p&gt;Thay vì hỏi gián tiếp “dữ liệu này bất thường đến mức nào nếu \(H_0\) đúng?”, phương pháp Bayesian hỏi trực tiếp: “với dữ liệu quan sát được, niềm tin của ta về tham số nên phân bố ra sao?” Quy trình gồm ba bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Thiết lập phân phối tiên nghiệm (prior)&lt;/strong&gt;: mã hóa hiểu biết ban đầu về tham số bằng phân phối \(P(\theta)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật bằng dữ liệu qua định lý Bayes&lt;/strong&gt;: kết hợp prior với hàm hợp lý (likelihood) để thu được phân phối hậu nghiệm (posterior):&lt;/li&gt;
&lt;/ol&gt;

\[P(\theta \mid \text{dữ liệu}) = \frac{P(\text{dữ liệu} \mid \theta) \cdot P(\theta)}{P(\text{dữ liệu})}\]

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Diễn giải trực tiếp phân phối hậu nghiệm&lt;/strong&gt;: đọc ngay xác suất của các vùng giá trị tham số dựa trên dữ liệu đã quan sát.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Ví dụ, thay vì phát biểu “bác bỏ giả thuyết hiệu quả thuốc bằng 0 với \(p = 0.03\)”, ta có thể nói trực tiếp: “với dữ liệu này, có 95% xác suất hậu nghiệm rằng hiệu quả giảm huyết áp của thuốc nằm trong khoảng từ 2 đến 8 mmHg”. Ngoài ra, khung Bayesian còn cho phép tính xác suất giữa các giả thuyết, kết hợp thông tin từ nhiều nghiên cứu, và đưa ra phân phối dự đoán cho dữ liệu mới.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-sai-lầm-loại-i-loại-ii--góc-nhìn-đối-sánh-bayes&quot;&gt;Video ngắn: Sai lầm Loại I, Loại II &amp;amp; Góc nhìn Đối sánh Bayes&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-11b-type12-vs-bayes.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 4 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): minh họa vùng α, β và lực kiểm định Power trên H₀ vs H₁, nghịch lý 1.000 giả thuyết, vùng ROPE và suy diễn hậu nghiệm Bayes.&lt;/p&gt;

&lt;h2 id=&quot;khi-nào-nên-sử-dụng-p-values&quot;&gt;Khi nào Nên Sử dụng P-values?&lt;/h2&gt;

&lt;p&gt;Dù có nhiều giới hạn, p-value vẫn hữu ích trong một số trường hợp: làm công cụ sàng lọc nhanh để phát hiện tín hiệu đáng xem xét thêm, kiểm tra sơ bộ độ phù hợp mô hình, hoặc hỗ trợ một số bài toán ra quyết định nhị phân có quy trình rõ ràng (như kiểm soát chất lượng). Ngay cả khi đó, p-value cần đi kèm kích thước hiệu ứng và khoảng tin cậy.&lt;/p&gt;

&lt;h2 id=&quot;hướng-dẫn-thực-hành&quot;&gt;Hướng dẫn Thực hành&lt;/h2&gt;

&lt;p&gt;Khi sử dụng hoặc đọc p-value, không nên báo cáo p-value đơn lẻ mà luôn kèm kích thước hiệu ứng, khoảng tin cậy và cỡ mẫu; tránh biến ngưỡng \(\alpha\) thành ranh giới nhị phân cứng nhắc; luôn nhớ p-value là \(P(\text{dữ liệu} \mid H_0)\) chứ không phải \(P(H_0 \mid \text{dữ liệu})\); và luôn đặt kết quả trong bối cảnh thực tiễn cùng chất lượng thiết kế nghiên cứu. Với nhiều câu hỏi ước lượng và ra quyết định, tiếp cận Bayesian sẽ rõ ràng và phù hợp hơn.&lt;/p&gt;

&lt;h2 id=&quot;ý-nghĩa-cho-phân-tích-dữ-liệu-bayesian&quot;&gt;Ý nghĩa cho Phân tích Dữ liệu Bayesian&lt;/h2&gt;

&lt;p&gt;Hiểu rõ kiểm định giả thuyết tần suất là nền tảng giúp bạn đánh giá đúng vai trò của thống kê Bayesian. Phương pháp Bayesian chuyển trọng tâm từ kiểm định nhị phân sang ước lượng tham số và dự đoán, cho phép diễn giải trực tiếp xác suất của tham số, không phụ thuộc ngưỡng cắt tùy ý và tích hợp minh bạch thông tin tiên nghiệm. Tất nhiên, thống kê Bayesian không phải lời giải vạn năng — nó có những thách thức riêng về tính toán và lựa chọn prior — nhưng đem lại một khung suy luận nhất quán cho rất nhiều bài toán thực tế.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tại-sao-p--004-không-có-nghĩa-96-giả-thuyết-là-đúng&quot;&gt;Giải thích: Tại sao \(p = 0.04\) KHÔNG có nghĩa “96% giả thuyết là đúng”?&lt;/h2&gt;

&lt;p&gt;Đây là nguồn gốc lớn nhất của khủng hoảng tái lập khoa học. Hãy đi chậm qua 4 bước để tự chứng minh bằng số học đơn giản:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tách biệt hai xác suất điều kiện:&lt;/strong&gt; \(p\text{-value}\) gắn với \(P(\text{kết quả đáng kể} \mid H_0)\), còn điều ta muốn biết là \(P(H_0 \mid \text{kết quả đáng kể})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đưa vào tỷ lệ nền (Base Rate):&lt;/strong&gt; Trong một lĩnh vực nghiên cứu thăm dò, giả sử chỉ có 10% giả thuyết thử nghiệm là thực sự có hiệu ứng (\(P(H_1) = 0.10\), \(P(H_0) = 0.90\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đưa vào ngưỡng \(\alpha\) và lực kiểm định (Power):&lt;/strong&gt; Với chuẩn \(\alpha = 0.05\) và lực kiểm định phổ biến \(1 - \beta = 0.80\), ta tính số phát hiện thật và phát hiện giả trên 1.000 thí nghiệm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính xác suất hậu nghiệm bị báo động giả (False Discovery Rate):&lt;/strong&gt; Lấy số dương tính giả chia cho tổng số kết quả đạt \(p &amp;lt; 0.05\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-1000-thí-nghiệm-đạt-chuẩn-p--005&quot;&gt;Ví dụ tính toán làm từng bước: 1.000 thí nghiệm đạt chuẩn \(p &amp;lt; 0.05\)&lt;/h3&gt;

&lt;p&gt;Xét 1.000 giả thuyết được kiểm định với \(\alpha = 0.05\), lực kiểm định \(1 - \beta = 0.80\), và tỷ lệ giả thuyết đúng thực sự là \(10\%\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Thực tế&lt;/th&gt;
      &lt;th&gt;Số thí nghiệm&lt;/th&gt;
      &lt;th&gt;Đạt \(p &amp;lt; 0.05\) (Bác bỏ \(H_0\))&lt;/th&gt;
      &lt;th&gt;Không đạt \(p &amp;lt; 0.05\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(H_1\) đúng (có hiệu ứng thật)&lt;/td&gt;
      &lt;td&gt;\(100\)&lt;/td&gt;
      &lt;td&gt;\(100 \times 0.80 = 80\) (dương tính thật)&lt;/td&gt;
      &lt;td&gt;\(20\) (âm tính giả)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(H_0\) đúng (không có hiệu ứng)&lt;/td&gt;
      &lt;td&gt;\(900\)&lt;/td&gt;
      &lt;td&gt;\(900 \times 0.05 = 45\) (dương tính giả)&lt;/td&gt;
      &lt;td&gt;\(855\) (âm tính thật)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Tổng cộng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(1\,000\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(80 + 45 = 125\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(875\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Nhìn vào cột “Đạt \(p &amp;lt; 0.05\)”: trong 125 kết quả “có ý nghĩa thống kê”, có tới &lt;strong&gt;45 kết quả hoàn toàn là nhiễu ngẫu nhiên&lt;/strong&gt;:
\(P(H_0 \mid p &amp;lt; 0.05) = \frac{45}{125} = 0.36 \quad (36\%!).\)
Dù chuẩn \(\alpha\) là \(5\%\), xác suất một phát hiện có \(p &amp;lt; 0.05\) là &lt;strong&gt;giả mạo&lt;/strong&gt; lại lên tới &lt;strong&gt;36%&lt;/strong&gt; — cao gấp 7 lần con số 5%!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Cho rằng \(p &amp;gt; 0.05\) chứng minh \(H_0\) đúng (không có hiệu ứng). Với cỡ mẫu nhỏ, \(p &amp;gt; 0.05\) thường chỉ nói lên rằng &lt;em&gt;dữ liệu chưa đủ mạnh để kết luận&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu tỷ lệ nền của giả thuyết đúng tăng từ \(10\%\) lên \(50\%\) (nhờ nghiên cứu có cơ sở lý thuyết vững), số dương tính thật là \(500 \times 0.80 = 400\), dương tính giả là \(500 \times 0.05 = 25\), lúc này tỷ lệ giả mạo giảm mạnh còn \(25 / 425 \approx 5.9\%\). Prior thực sự quyết định chất lượng suy luận!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vemZtEM63GY&quot;&gt;p-values: What they are and how to interpret them&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giải thích rõ định nghĩa p-value như xác suất của dữ liệu cực đoan dưới giả thuyết không.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=0oc49DyA3hU&quot;&gt;Hypothesis Testing and The Null Hypothesis, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Trình bày vai trò của giả thuyết không và quy trình kiểm định tần suất.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=TqOeMYtOc1w&quot;&gt;Confidence Intervals, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Minh họa cách dựng khoảng tin cậy qua lấy mẫu lặp lại để đối chiếu với khoảng credible Bayesian.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 1: Diễn giải P-value.&lt;/strong&gt; Một nghiên cứu so sánh hai phương pháp giảng dạy và báo cáo “\(p = 0.04\)”. Hãy viết: (a) một diễn giải đúng về p-value này, (b) một diễn giải sai phổ biến, và (c) giải thích vì sao cách hiểu sai đó không hợp lệ và gây hậu quả gì.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 2: Kích thước Mẫu và P-value.&lt;/strong&gt; Giả sử chiều cao trung bình của nam giới ở quần thể A là 175.0 cm và ở quần thể B là 175.5 cm (chênh lệch rất nhỏ), với độ lệch chuẩn ở cả hai quần thể là 7 cm. (a) Dựa vào kiểm định t hai mẫu, ước lượng cỡ mẫu cần thiết để thu được \(p &amp;lt; 0.05\). (b) Thảo luận xem “ý nghĩa thống kê” có đồng nghĩa với “ý nghĩa thực tiễn” hay không.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/sample_size_calculation.png&quot; alt=&quot;Tính toán Kích thước Mẫu&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình minh họa: Đường cong thể hiện mối quan hệ giữa kích thước hiệu ứng và cỡ mẫu cần thiết ở mức power = 0.80, \(\alpha = 0.05\). Để phát hiện hiệu ứng nhỏ (0.5 cm) cần hơn 1,500 người mỗi nhóm, trong khi hiệu ứng lớn (2.0 cm) chỉ cần khoảng 100 người mỗi nhóm.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 3: Kiểm định bội và P-hacking.&lt;/strong&gt; Một nhà nghiên cứu kiểm tra riêng rẽ 20 biến khác nhau xem có tương quan với biến kết quả hay không, mỗi kiểm định dùng mức \(\alpha = 0.05\). (a) Nếu thực tế không biến nào có tương quan và các kiểm định độc lập, xác suất tìm thấy ít nhất một kết quả “có ý nghĩa thống kê” là bao nhiêu? (b) Đây là ví dụ của vấn đề gì? (c) Đề xuất hai biện pháp khắc phục.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 4: So sánh Khoảng Tin cậy và Khoảng Credible.&lt;/strong&gt; Giả sử bạn đọc hai báo cáo: (a) “Khoảng tin cậy 95% cho hiệu quả thuốc là [2, 8] mmHg” (tần suất), và (b) “Khoảng credible 95% cho hiệu quả thuốc là [2, 8] mmHg” (Bayesian). Hãy viết diễn giải chuẩn xác cho từng báo cáo và giải thích khoảng nào trả lời trực tiếp hơn câu hỏi của bác sĩ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 5: Nghiên cứu Trường hợp.&lt;/strong&gt; Tìm một bài báo khoa học trong lĩnh vực bạn quan tâm có sử dụng p-value. (a) Tác giả có diễn giải p-value chính xác không? (b) Bài báo có trình bày kích thước hiệu ứng và khoảng tin cậy không? (c) Nếu làm phản biện, bạn sẽ đề xuất cải thiện phân tích thống kê ra sao? (d) Phương pháp Bayesian có phù hợp hơn cho câu hỏi nghiên cứu đó không và vì sao?&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu Tham khảo&lt;/h2&gt;

&lt;h3 id=&quot;primary-references&quot;&gt;Primary References:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., &amp;amp; Rubin, D. B. (2013).&lt;/strong&gt; &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 4: Asymptotics and connections to non-Bayesian approaches&lt;/li&gt;
  &lt;li&gt;Chapter 6: Model checking&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kruschke, J. K. (2015).&lt;/strong&gt; &lt;em&gt;Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan&lt;/em&gt; (2nd Edition). Academic Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 11: Null Hypothesis Significance Testing&lt;/li&gt;
  &lt;li&gt;Chapter 12: Bayesian Approaches to Testing a Point (“Null”) Hypothesis&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;critical-papers-on-p-values&quot;&gt;Critical Papers on P-values:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Wasserstein, R. L., &amp;amp; Lazar, N. A. (2016).&lt;/strong&gt; The ASA’s statement on p-values: context, process, and purpose. &lt;em&gt;The American Statistician&lt;/em&gt;, 70(2), 129-133.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ioannidis, J. P. (2005).&lt;/strong&gt; Why most published research findings are false. &lt;em&gt;PLoS Medicine&lt;/em&gt;, 2(8), e124.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nuzzo, R. (2014).&lt;/strong&gt; Scientific method: statistical errors. &lt;em&gt;Nature&lt;/em&gt;, 506(7487), 150-152.&lt;/p&gt;

&lt;h3 id=&quot;supplementary-reading&quot;&gt;Supplementary Reading:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;McShane, B. B., Gal, D., Gelman, A., Robert, C., &amp;amp; Tackett, J. L. (2019).&lt;/strong&gt; Abandon statistical significance. &lt;em&gt;The American Statistician&lt;/em&gt;, 73(sup1), 235-245.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Greenland, S., Senn, S. J., Rothman, K. J., Carlin, J. B., Poole, C., Goodman, S. N., &amp;amp; Altman, D. G. (2016).&lt;/strong&gt; Statistical tests, P values, confidence intervals, and power: a guide to misinterpretations. &lt;em&gt;European Journal of Epidemiology&lt;/em&gt;, 31(4), 337-350.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_09_t_test_and_t_distribution/&quot;&gt;0.12 T-test và Phân phối T&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.10: Hàm Mật độ Xác suất (Probability Density Function - PDF) - Chi tiết</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_07_probability_density_functions/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_07_probability_density_functions</id>
   <content type="html">&lt;p&gt;Một trong những cú sốc trực giác đầu tiên khi chuyển từ xác suất rời rạc sang liên tục là nghịch lý sau: nếu bạn chọn ngẫu nhiên một số thực trên đoạn \([0, 1]\), xác suất trúng đúng số \(0.500000\ldots\) là &lt;strong&gt;bằng 0&lt;/strong&gt;, thế nhưng khi bạn nhấn nút, máy tính vẫn trả về &lt;em&gt;một&lt;/em&gt; con số cụ thể nào đó! Làm sao hàng vô hạn biến cố có xác suất 0 lại cộng lại thành xác suất 1?&lt;/p&gt;

&lt;p&gt;Câu trả lời là &lt;strong&gt;Hàm Mật độ Xác suất (PDF)&lt;/strong&gt; — khái niệm tương tự mật độ khối lượng trong vật lý. Hiểu rõ sự khác biệt giữa &lt;em&gt;mật độ tại một điểm&lt;/em&gt; và &lt;em&gt;xác suất trên một khoảng&lt;/em&gt; là điều kiện bắt buộc để đọc đúng đồ thị prior/posterior, tránh bối rối khi thấy trục tung PDF cao vượt quá 1, và hiểu bản chất hàm hợp lý liên tục.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Bài học này trình bày có hệ thống về &lt;strong&gt;hàm mật độ xác suất (PDF)&lt;/strong&gt;, làm rõ &lt;strong&gt;sự khác biệt bản chất giữa PDF và hàm khối lượng xác suất (PMF)&lt;/strong&gt;, cũng như cách diễn giải chính xác PDF trong các mô hình xác suất liên tục.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-độ-đo-lebesgue-tích-phân-mật-độ-và-biểu-diễn-hậu-nghiệm-liên-tục&quot;&gt;Kiến thức cần nhớ: Độ đo Lebesgue, Tích phân mật độ và Biểu diễn Hậu nghiệm liên tục&lt;/h2&gt;

&lt;p&gt;Ba trụ cột toán học làm nên bản chất của PDF trong thống kê Bayes:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Từ PMF sang PDF (Hàm khối lượng vs. Hàm mật độ):&lt;/strong&gt; Với biến rời rạc, \(P(X = x)\) là xác suất trực tiếp nằm trong \([0, 1]\). Với biến liên tục, \(f(x)\) là &lt;strong&gt;mật độ xác suất trên mỗi đơn vị chiều dài&lt;/strong&gt; (đơn vị \([\text{đơn vị của } x]^{-1}\)), nên \(f(x)\) có thể lớn hơn 1 miễn là \(f(x) \ge 0\) và \(\int_{-\infty}^{\infty} f(x)\,dx = 1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm phân phối tích lũy (CDF) &amp;amp; Hàm phân vị (Quantile):&lt;/strong&gt; \(F(x) = \int_{-\infty}^x f(t)\,dt\) là cây cầu biến mật độ thành xác suất thật trên khoảng: \(P(a \le X \le b) = F(b) - F(a)\). Ngược lại, hàm phân vị \(F^{-1}(q)\) chính là công cụ xây dựng &lt;strong&gt;khoảng tin cậy Bayes&lt;/strong&gt; (&lt;em&gt;credible intervals&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Suy diễn Bayes:&lt;/strong&gt; Trong mô hình liên tục, cả prior \(p(\theta)\), likelihood \(p(y \mid \theta)\) (với \(y\) liên tục) và posterior \(p(\theta \mid y)\) đều là mật độ. Khi lấy mẫu MCMC, máy tính không tính trực tiếp tích phân \(F(x)\) mà sinh ra hàng nghìn điểm mẫu có mật độ dày đặc đúng theo chiều cao của \(p(\theta \mid y)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-từ-rời-rạc-đến-liên-tục&quot;&gt;1. Từ Rời rạc đến Liên tục&lt;/h2&gt;

&lt;h3 id=&quot;11-biến-ngẫu-nhiên-rời-rạc--pmf&quot;&gt;1.1. Biến Ngẫu nhiên Rời rạc — PMF&lt;/h3&gt;

&lt;p&gt;Với biến ngẫu nhiên &lt;strong&gt;rời rạc&lt;/strong&gt; \(X\), ta có &lt;strong&gt;hàm khối lượng xác suất (Probability Mass Function — PMF)&lt;/strong&gt; ký hiệu là \(P(X = x)\). Hàm này cho biết xác suất chính xác để biến ngẫu nhiên nhận một giá trị cụ thể. Chẳng hạn, khi tung một con xúc xắc công bằng, mỗi mặt từ 1 đến 6 có xác suất \(P(X = k) = 1/6\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Các tính chất cơ bản của PMF&lt;/strong&gt;: \(P(X = x) \geq 0\) với mọi \(x\), tổng toàn bộ các xác suất \(\sum_{\text{all } x} P(X = x) = 1\), và quan trọng nhất là \(P(X = x)\) mang trực tiếp ý nghĩa một xác suất nằm trong đoạn \([0, 1]\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_pmf_dice.png&quot; alt=&quot;PMF của xúc xắc công bằng&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Quan sát chiều cao từng cột riêng lẻ, vì ở PMF mỗi cột biểu thị trực tiếp xác suất tại một giá trị cụ thể.&lt;/em&gt;
&lt;em&gt;Hình 1: PMF của xúc xắc công bằng. Mỗi giá trị từ 1 đến 6 có xác suất \(1/6\) và tổng chiều cao các cột bằng 1.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;12-vấn-đề-với-biến-liên-tục&quot;&gt;1.2. Vấn đề với Biến Liên tục&lt;/h3&gt;

&lt;p&gt;Bây giờ xét một biến ngẫu nhiên liên tục, chẳng hạn chiều cao người trưởng thành tuân theo phân phối chuẩn \(X \sim \mathcal{N}(170, 10^2)\) cm. Câu hỏi đặt ra là \(P(X = 170)\) bằng bao nhiêu?&lt;/p&gt;

&lt;p&gt;Câu trả lời là &lt;strong&gt;bằng 0&lt;/strong&gt;. Thực chất, \(P(X = k) = 0\) với &lt;strong&gt;mọi&lt;/strong&gt; giá trị cụ thể \(k\), dù là 170, 170.5 hay 170.000001. Lý do là biến liên tục có &lt;strong&gt;vô số&lt;/strong&gt; giá trị khả dĩ: ngay giữa 170 cm và 171 cm đã có vô hạn điểm như 170.1, 170.01, 170.001… Nếu mỗi điểm riêng lẻ đều mang xác suất dương thì tổng xác suất sẽ vượt quá 1, trái với tiên đề chuẩn hóa.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_continuous_height.png&quot; alt=&quot;Biến liên tục và xác suất tại một điểm&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Phân biệt chấm đỏ với toàn bộ đường cong. Chấm đỏ chỉ thể hiện giá trị mật độ tại 170 cm, còn xác suất phải được tính bằng diện tích trên một khoảng.&lt;/em&gt;
&lt;em&gt;Hình 2: Với biến liên tục như chiều cao, \(P(X=170)=0\) dù \(f(170)\) khác 0; chỉ xác suất trên một khoảng mới có giá trị dương.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cách khắc phục&lt;/strong&gt;: thay vì hỏi xác suất tại một điểm đơn lẻ, ta hỏi xác suất biến ngẫu nhiên rơi vào một &lt;strong&gt;khoảng&lt;/strong&gt;:&lt;/p&gt;

\[P(a \leq X \leq b)\]

&lt;p&gt;Chẳng hạn, \(P(169.5 \leq X \leq 170.5)\) là xác suất chiều cao nằm giữa 169.5 cm và 170.5 cm — đại lượng này có thể tính được và mang giá trị dương.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-pmf-vs-pdf-tại-sao-px--05-lại-bằng-đúng-0&quot;&gt;Video ngắn: PMF vs PDF: Tại sao P(X = 0.5) lại bằng đúng 0?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-10a-pmf-vs-pdf-paradox.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 8 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): đối chiếu PMF rời rạc và PDF liên tục, thu hẹp khoảng về 0, phép tương tự mật độ khối lượng, thứ nguyên 1/đơn vị và CDF.&lt;/p&gt;

&lt;h2 id=&quot;2-hàm-mật-độ-xác-suất-pdf&quot;&gt;2. Hàm Mật độ Xác suất (PDF)&lt;/h2&gt;

&lt;h3 id=&quot;21-định-nghĩa-chính-thức&quot;&gt;2.1. Định nghĩa Chính thức&lt;/h3&gt;

&lt;p&gt;Với biến ngẫu nhiên liên tục \(X\), &lt;strong&gt;hàm mật độ xác suất (Probability Density Function — PDF)&lt;/strong&gt; \(f(x)\) là hàm thỏa mãn:&lt;/p&gt;

\[P(a \leq X \leq b) = \int_a^b f(x) \, dx\]

&lt;p&gt;Đây là định nghĩa trọng tâm của bài học: xác suất để \(X\) rơi vào đoạn \([a, b]\) bằng &lt;strong&gt;tích phân&lt;/strong&gt; (diện tích dưới đường cong) của \(f(x)\) từ \(a\) đến \(b\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lưu ý quan trọng&lt;/strong&gt;: \(f(x)\) không phải là xác suất, mà là mật độ xác suất. Chỉ tích phân — tức diện tích dưới đường cong \(f(x)\) trên một khoảng — mới là xác suất. Nhầm lẫn \(f(x)\) với xác suất tại điểm \(x\) là lỗi phổ biến nhất khi học về biến liên tục.&lt;/p&gt;

&lt;h3 id=&quot;22-tại-sao-gọi-là-mật-độ&quot;&gt;2.2. Tại sao gọi là “Mật độ”?&lt;/h3&gt;

&lt;p&gt;Khái niệm “mật độ” trong xác suất tương tự &lt;strong&gt;mật độ khối lượng&lt;/strong&gt; trong vật lý. Mật độ khối lượng \(\rho(x)\) (đơn vị: kg/m³) không phải là khối lượng mà cho biết khối lượng phân bố dày hay thưa trong không gian; muốn tính khối lượng trên một miền, ta phải lấy tích phân \(\text{Khối lượng} = \int \rho(x) \, dx\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_mass_density_analogy.png&quot; alt=&quot;Mật độ khối lượng trong vật lý&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 3: Trong vật lý, \(\rho(x)\) là mật độ khối lượng; khối lượng thực sự bằng diện tích dưới đường \(\rho(x)\) trên đoạn xét.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Tương tự, mật độ xác suất \(f(x)\) cho biết xác suất tập trung quanh \(x\) đến mức nào, còn xác suất thực tế là tích phân \(\int f(x)\,dx\) trên khoảng quan tâm. Khi \(f(x)\) lớn quanh một điểm \(x\), một khoảng nhỏ quanh \(x\) sẽ chứa nhiều xác suất hơn; khi \(f(x)\) nhỏ, xác suất quanh điểm đó thưa hơn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_probability_density_analogy.png&quot; alt=&quot;Mật độ xác suất trong thống kê&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 4: Trong xác suất, \(f(x)\) là mật độ; xác suất chỉ xuất hiện khi lấy diện tích dưới đường cong trên một khoảng, ví dụ \([-1,1]\).&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;23-tính-chất-của-pdf&quot;&gt;2.3. Tính chất của PDF&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Tính chất 1: Không âm.&lt;/strong&gt; \(f(x) \geq 0\) với mọi \(x\), vì mật độ âm sẽ dẫn đến xác suất âm khi lấy tích phân.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính chất 2: Tích phân toàn phần bằng 1.&lt;/strong&gt;&lt;/p&gt;

\[\int_{-\infty}^{\infty} f(x) \, dx = 1\]

&lt;p&gt;Tổng diện tích dưới toàn bộ đường cong mật độ bằng 1, tương ứng tổng xác suất của không gian mẫu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính chất 3: \(f(x)\) có thể lớn hơn 1.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Vì \(f(x)\) là mật độ chứ không phải xác suất, nó hoàn toàn có thể vượt quá 1 miễn là tổng diện tích dưới đường cong vẫn bằng 1.&lt;/p&gt;

&lt;p&gt;Ví dụ đầu tiên là một phân phối chuẩn rất hẹp: khi độ lệch chuẩn đủ nhỏ, đỉnh đường cong vượt trên 1 nhưng diện tích toàn phần vẫn bằng 1.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_exceeds_one_normal.png&quot; alt=&quot;Phân phối chuẩn hẹp có thể có đỉnh lớn hơn 1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 5: Với \(X \sim \mathcal{N}(0, 0.3^2)\), đỉnh \(f(0)\) vượt quá 1, nhưng toàn bộ diện tích dưới đường cong vẫn bằng 1.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Ví dụ thứ hai là phân phối đều trên đoạn \([0, 0.5]\): mật độ bằng 2 trên toàn đoạn, nhưng diện tích là \(2 \times 0.5 = 1\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_exceeds_one_uniform.png&quot; alt=&quot;Phân phối đều trên [0, 0.5] có mật độ bằng 2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 6: Phân phối đều trên \([0, 0.5]\) có \(f(x)=2&amp;gt;1\); điều kiện hợp lệ nằm ở diện tích toàn phần bằng 1, không phải chiều cao nhỏ hơn 1.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Ví dụ thứ ba là phân phối \(\text{Beta}(0.5, 0.5)\): mật độ tăng không bị chặn khi tiến gần hai đầu mút 0 và 1, nhưng tích phân toàn phần vẫn hữu hạn và bằng 1 nên vẫn là một PDF hợp lệ.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_exceeds_one_beta.png&quot; alt=&quot;Phân phối Beta có mật độ tăng rất mạnh ở đầu mút&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 7: Với \(\text{Beta}(0.5, 0.5)\), mật độ tăng rất cao gần 0 và 1, minh họa rõ hơn rằng \(f(x)\) không phải xác suất điểm.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-hiểu-sâu-về-pdf&quot;&gt;3. Hiểu Sâu về PDF&lt;/h2&gt;

&lt;h3 id=&quot;31-pdf-là-giới-hạn-của-histogram&quot;&gt;3.1. PDF là Giới hạn của Histogram&lt;/h3&gt;

&lt;p&gt;Một cách trực quan để hiểu PDF là thông qua histogram. Khi số lượng mẫu \(n\) tăng lên và độ rộng các khoảng (bin) \(\Delta x\) thu nhỏ dần, đường bao của histogram (được chuẩn hóa theo mật độ) tiến dần về đường cong PDF lý thuyết. Về mặt toán học, khi \(n \to \infty\) và \(\Delta x \to 0\), histogram hội tụ về PDF.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc chuỗi hình dưới đây: theo dõi từ \(n\) nhỏ đến \(n\) lớn để thấy histogram màu xanh dần ôm sát đường PDF lý thuyết màu đỏ.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n100.png&quot; alt=&quot;Histogram với n = 100&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 8: Với \(n=100\), histogram còn thô và dao động mạnh quanh đường cong lý thuyết.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n500.png&quot; alt=&quot;Histogram với n = 500&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 9: Khi \(n=500\), dạng hình chuông rõ hơn nhưng từng bin vẫn còn chênh lệch đáng kể.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n1000.png&quot; alt=&quot;Histogram với n = 1,000&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 10: Với \(n=1{,}000\), histogram bám khá sát đường PDF dù nhiễu lấy mẫu vẫn còn rõ.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n5000.png&quot; alt=&quot;Histogram với n = 5,000&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 11: Ở \(n=5{,}000\), đường bao chung của histogram đã rất gần PDF lý thuyết.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n10000.png&quot; alt=&quot;Histogram với n = 10,000&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 12: Khi \(n=10{,}000\), sai khác chỉ còn là các dao động nhỏ do lấy mẫu.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n50000.png&quot; alt=&quot;Histogram với n = 50,000&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 13: Với \(n=50{,}000\), histogram gần như trùng với PDF lý thuyết, cho thấy PDF là giới hạn lý tưởng khi cỡ mẫu rất lớn.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Mối liên hệ này nối PDF lý thuyết với dữ liệu thực tế: ta không bao giờ có vô hạn quan sát, nên phải ước lượng mật độ từ mẫu hữu hạn, và cỡ mẫu càng lớn thì ước lượng càng gần PDF thật.&lt;/p&gt;

&lt;h3 id=&quot;32-xác-suất-trong-khoảng-nhỏ&quot;&gt;3.2. Xác suất trong Khoảng Nhỏ&lt;/h3&gt;

&lt;p&gt;Trên một khoảng rất nhỏ \([x, x + \Delta x]\), xác suất có thể xấp xỉ bởi diện tích hình chữ nhật chiều cao \(f(x)\) và bề rộng \(\Delta x\):&lt;/p&gt;

\[P(x \leq X \leq x + \Delta x) \approx f(x) \cdot \Delta x\]

&lt;p&gt;Khi \(\Delta x\) càng nhỏ, xấp xỉ càng chính xác; lấy giới hạn khi \(\Delta x \to 0\), ta có:&lt;/p&gt;

\[f(x) = \lim_{\Delta x \to 0} \frac{P(x \leq X \leq x + \Delta x)}{\Delta x}\]

&lt;p&gt;Như vậy, \(f(x)\) đóng vai trò đạo hàm của xác suất tích lũy theo \(x\), đo tốc độ tích lũy xác suất dọc theo trục \(x\).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc chuỗi hình dưới đây: so sánh hình chữ nhật nét đứt màu xanh lá với diện tích thật màu cam khi \(\Delta x\) thu nhỏ dần.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_small_interval_dx_05.png&quot; alt=&quot;Xấp xỉ với delta x bằng 0.5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 14: Với \(\Delta x = 0.5\), hình chữ nhật xấp xỉ còn thô nên sai số hiện rõ.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_small_interval_dx_01.png&quot; alt=&quot;Xấp xỉ với delta x bằng 0.1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 15: Khi \(\Delta x = 0.1\), diện tích hình chữ nhật đã bám sát diện tích thật hơn nhiều.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_small_interval_dx_001.png&quot; alt=&quot;Xấp xỉ với delta x bằng 0.01&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 16: Với \(\Delta x = 0.01\), xấp xỉ \(f(x)\Delta x\) gần như trùng với xác suất thật trên khoảng rất nhỏ.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;33-đơn-vị-của-pdf&quot;&gt;3.3. Đơn vị của PDF&lt;/h3&gt;

&lt;p&gt;Một đặc điểm thường bị bỏ qua là PDF có đơn vị đo. Nếu biến ngẫu nhiên \(X\) mang đơn vị (như cm, kg hay giây), thì \(f(x)\) có đơn vị là &lt;strong&gt;1/(đơn vị của X)&lt;/strong&gt;, nhờ đó tích \(f(x)\cdot dx\) trở thành đại lượng không thứ nguyên và mang ý nghĩa xác suất.&lt;/p&gt;

&lt;p&gt;Ví dụ, nếu \(X\) là chiều cao đo bằng cm thì \(f(x)\) có đơn vị 1/cm; khi đổi sang mét, \(f(x)\) có đơn vị 1/m và giá trị số tăng gấp 100 lần: nếu \(f(170 \text{ cm}) = 0.04 \text{ (1/cm)}\) thì \(f(1.70 \text{ m}) = 4.0 \text{ (1/m)}\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_units_cm_only.png&quot; alt=&quot;PDF khi đo chiều cao bằng cm&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 17: Khi đo bằng cm, mật độ tại trung tâm khoảng \(f(170)=0.04\) với đơn vị 1/cm.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_units_m_only.png&quot; alt=&quot;PDF khi đo chiều cao bằng m&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 18: Cùng phân phối đó nhưng đổi sang mét, mật độ tại trung tâm là \(f(1.70)=4.0\) với đơn vị 1/m; bản chất phân phối không đổi, chỉ thang đo và đơn vị mật độ thay đổi.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Ngược lại, &lt;strong&gt;xác suất không phụ thuộc vào đơn vị đo&lt;/strong&gt;: \(P(160 \text{ cm} \leq X \leq 180 \text{ cm}) = P(1.60 \text{ m} \leq X \leq 1.80 \text{ m})\). Việc \(f(x)\) thay đổi theo đơn vị là một lý do nữa khẳng định \(f(x)\) không thể là xác suất.&lt;/p&gt;

&lt;h2 id=&quot;4-so-sánh-pmf-và-pdf&quot;&gt;4. So sánh PMF và PDF&lt;/h2&gt;

&lt;p&gt;Ở biến rời rạc, một PMF điển hình như \(\text{Binomial}(10, 0.5)\) gán xác suất trực tiếp cho từng giá trị nguyên.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_binomial_pmf_example.png&quot; alt=&quot;Ví dụ PMF của phân phối Binomial&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 19: Với PMF, độ cao cột tại \(x=5\) chính là xác suất \(P(X=5)=0.246\) và đọc được trực tiếp trên biểu đồ.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Ở biến liên tục, một PDF điển hình như \(\mathcal{N}(0,1)\) chỉ cho biết mật độ tại từng điểm, không phải xác suất tại điểm đó.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_normal_density_example.png&quot; alt=&quot;Ví dụ PDF của phân phối chuẩn tắc&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 20: Với PDF, giá trị \(f(0)=0.399\) là mật độ tại 0, còn xác suất tại đúng điểm đó vẫn là \(P(X=0)=0\).&lt;/em&gt;&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Đặc điểm&lt;/th&gt;
      &lt;th&gt;PMF (Rời rạc)&lt;/th&gt;
      &lt;th&gt;PDF (Liên tục)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Ký hiệu&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;\(P(X = x)\)&lt;/td&gt;
      &lt;td&gt;\(f(x)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Ý nghĩa&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Xác suất&lt;/td&gt;
      &lt;td&gt;Mật độ xác suất&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Giá trị&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;\(0 \leq P(X=x) \leq 1\)&lt;/td&gt;
      &lt;td&gt;\(f(x) \geq 0\) (có thể &amp;gt; 1)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;P(X = x)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Có nghĩa&lt;/td&gt;
      &lt;td&gt;= 0&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Tổng/Tích phân&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;\(\sum P(X=x) = 1\)&lt;/td&gt;
      &lt;td&gt;\(\int f(x)dx = 1\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Xác suất khoảng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;\(\sum_{a}^{b} P(X=x)\)&lt;/td&gt;
      &lt;td&gt;\(\int_a^b f(x)dx\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Đơn vị&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Không đơn vị&lt;/td&gt;
      &lt;td&gt;1/(đơn vị của X)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Điểm khác biệt cốt lõi: với PMF, \(P(X=x)\) &lt;strong&gt;là xác suất&lt;/strong&gt;; với PDF, \(f(x)\) &lt;strong&gt;chỉ là mật độ&lt;/strong&gt;, và xác suất chỉ xuất hiện khi lấy tích phân trên một khoảng.&lt;/p&gt;

&lt;h2 id=&quot;5-các-sai-lầm-thường-gặp&quot;&gt;5. Các Sai lầm Thường gặp&lt;/h2&gt;

&lt;h3 id=&quot;sai-lầm-1-nghĩ-fx-là-xác-suất&quot;&gt;Sai lầm 1: Nghĩ \(f(x)\) là xác suất&lt;/h3&gt;

&lt;p&gt;Với phân phối chuẩn chiều cao có trung bình 170 cm và độ lệch chuẩn 10 cm, ta tính được \(f(170) = 0.04\). Viết “\(P(X = 170) = f(170) = 0.04\)” là sai; diễn giải đúng là “\(P(X = 170) = 0\) vì đây là biến liên tục, còn \(f(170) = 0.04\) là mật độ xác suất tại 170 cm”.&lt;/p&gt;

&lt;h3 id=&quot;sai-lầm-2-nghĩ-fx-leq-1&quot;&gt;Sai lầm 2: Nghĩ \(f(x) \leq 1\)&lt;/h3&gt;

&lt;p&gt;Do xác suất không vượt quá 1, nhiều người suy luận nhầm rằng PDF cũng phải nhỏ hơn hoặc bằng 1. Thực tế, \(f(x)\) chỉ cần không âm và thỏa mãn \(\int f(x)dx = 1\). Ví dụ, phân phối đều trên \([0, 0.2]\) có \(f(x) = 5 &amp;gt; 1\) nhưng hoàn toàn hợp lệ vì diện tích bằng \(5 \times 0.2 = 1\).&lt;/p&gt;

&lt;h4 id=&quot;video-ngắn-tại-sao-pdf-fx-có-thể-lớn-hơn-1&quot;&gt;Video ngắn: Tại sao PDF f(x) có thể lớn hơn 1?&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-10b-pdf-area-above-one.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 8 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): nén đáy Uniform từ 1 xuống 0.2 làm chiều cao vọt lên 5.0, đỉnh Chuẩn N(0.5, 0.1²) ≈ 3.99 và log-density dương trong MCMC.&lt;/p&gt;

&lt;h3 id=&quot;sai-lầm-3-so-sánh-trực-tiếp-fx-giữa-các-đơn-vị-khác-nhau&quot;&gt;Sai lầm 3: So sánh trực tiếp \(f(x)\) giữa các đơn vị khác nhau&lt;/h3&gt;

&lt;p&gt;Vì \(f(x)\) phụ thuộc vào đơn vị đo, so sánh trực tiếp \(f(170 \text{ cm})\) với \(f(1.70 \text{ m})\) không có ý nghĩa. Thay vào đó, ta chỉ nên so sánh các xác suất trên những khoảng tương ứng vì xác suất là đại lượng không thứ nguyên.&lt;/p&gt;

&lt;h2 id=&quot;6-ứng-dụng-trong-thống-kê-bayesian&quot;&gt;6. Ứng dụng trong Thống kê Bayesian&lt;/h2&gt;

&lt;h3 id=&quot;61-prior-và-posterior-là-pdf&quot;&gt;6.1. Prior và Posterior là PDF&lt;/h3&gt;

&lt;p&gt;Trong phân tích Bayesian với tham số liên tục \(\theta\), cả phân phối tiên nghiệm (prior) \(p(\theta)\) và phân phối hậu nghiệm (posterior) \(p(\theta \mid x)\) đều là PDF. Điều đó có nghĩa là \(p(\theta)\) biểu diễn &lt;strong&gt;mật độ niềm tin&lt;/strong&gt; (density of belief) chứ không phải xác suất điểm: giá trị \(p(\theta = 0.5)\) có thể lớn hơn 1, còn xác suất có ý nghĩa luôn gắn với một khoảng, chẳng hạn \(P(a \leq \theta \leq b) = \int_a^b p(\theta)\,d\theta\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_bayesian_prior_posterior.png&quot; alt=&quot;Prior và posterior như hai hàm mật độ&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 21: Trong thống kê Bayesian, prior và posterior là hai đường PDF trên không gian tham số, thể hiện mật độ niềm tin trước và sau khi cập nhật dữ liệu.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Ví dụ, với prior \(\theta \sim \text{Beta}(2, 2)\) cho xác suất thành công của một thử nghiệm và dữ liệu gồm 7 lần thành công trong 10 phép thử, posterior là \(\theta \mid x \sim \text{Beta}(9, 5)\). Phát biểu “khoảng tin cậy 95% là [0.395, 0.827]” có nghĩa chính xác là:&lt;/p&gt;

\[P(0.395 \leq \theta \leq 0.827 \mid x) = \int_{0.395}^{0.827} p(\theta \mid x) \, d\theta = 0.95\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_bayesian_credible_interval.png&quot; alt=&quot;Khoảng tin cậy như diện tích dưới posterior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 22: Khoảng tin cậy 95% tương ứng phần diện tích màu xanh dưới đường posterior PDF, không phải chiều cao mật độ tại một điểm.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;62-hàm-hợp-lý-likelihood-function&quot;&gt;6.2. Hàm Hợp lý (Likelihood Function)&lt;/h3&gt;

&lt;p&gt;Hàm hợp lý \(L(\theta) = p(x \mid \theta)\) cũng được xây dựng từ PDF. Khi dữ liệu \(x\) đã cố định, hàm hợp lý được xem là hàm theo tham số \(\theta\). Với mô hình \(X \sim \mathcal{N}(\mu, \sigma^2)\) (\(\sigma\) đã biết):&lt;/p&gt;

\[L(\mu) = \prod_{i=1}^{n} f(x_i \mid \mu) = \prod_{i=1}^{n} \frac{1}{\sigma\sqrt{2\pi}} \exp\left(-\frac{(x_i-\mu)^2}{2\sigma^2}\right)\]

&lt;p&gt;Mỗi thừa số \(f(x_i \mid \mu)\) là giá trị PDF tại quan sát \(x_i\) ứng với tham số \(\mu\), và ước lượng hợp lý cực đại (MLE) là giá trị \(\hat{\mu}\) làm cực đại \(L(\mu)\).&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-tại-sao-pdf-có-thể-lớn-hơn-1--và-cách-đọc-diện-tích-bằng-tay&quot;&gt;Giải thích: Tại sao PDF có thể lớn hơn 1 — và cách đọc diện tích bằng tay&lt;/h2&gt;

&lt;p&gt;Hãy đọc chậm bốn quy tắc vàng để không bao giờ hiểu sai đồ thị PDF của prior hay posterior:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mật độ không phải xác suất:&lt;/strong&gt; \(f(x_0)\) không phải là \(P(X = x_0)\). Thay vào đó, với khoảng rất hẹp bề rộng \(\Delta x\), xác suất xấp xỉ bằng diện tích hình chữ nhật nhỏ: \(P(x_0 \le X \le x_0 + \Delta x) \approx f(x_0)\,\Delta x\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đổi đơn vị làm đổi chiều cao PDF:&lt;/strong&gt; Nếu đo chiều dài bằng mét thay vì centimet, miền giá trị bị nén lại 100 lần, nên chiều cao PDF bắt buộc phải &lt;strong&gt;tăng gấp 100 lần&lt;/strong&gt; để tổng diện tích vẫn giữ nguyên bằng 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tỷ số mật độ mới mang ý nghĩa bất biến theo đơn vị:&lt;/strong&gt; Khi so sánh hai điểm \(x_1\) và \(x_2\), tỷ số \(f(x_1)/f(x_2)\) cho biết một khoảng hẹp quanh \(x_1\) có xác suất lớn gấp bao nhiêu lần khoảng cùng bề rộng quanh \(x_2\) — đây chính là thứ thuật toán &lt;strong&gt;Metropolis–Hastings&lt;/strong&gt; sử dụng trong tỷ số chấp nhận!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng tin cậy Bayes là bài toán diện tích:&lt;/strong&gt; Tìm khoảng 95% hậu nghiệm nghĩa là tìm \([a, b]\) sao cho \(\int_a^b p(\theta \mid y)\,d\theta = 0.95\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-kiểm-tra-pdf-tam-giác-và-tính-xác-suất-khoảng&quot;&gt;Ví dụ tính toán làm từng bước: Kiểm tra PDF tam giác và tính xác suất khoảng&lt;/h3&gt;

&lt;p&gt;Xét một hàm mật độ đơn giản trên đoạn \([0, 0.5]\) (ví dụ một prior tam giác tập trung gần \(0.5\)):
\(f(\theta) = c\,\theta \quad \text{với } 0 \le \theta \le 0.5, \quad \text{và } f(\theta) = 0 \text{ ở ngoài.}\)&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Tìm hằng số chuẩn hóa \(c\) sao cho tổng diện tích bằng 1:&lt;/strong&gt;
\(\int_0^{0.5} c\,\theta\,d\theta = c \left[\frac{\theta^2}{2}
ight]_0^{0.5} = c \cdot \frac{0.25}{2} = \frac{c}{8} = 1 \implies c = 8.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Kiểm tra giá trị PDF tại đỉnh \(\theta = 0.5\):&lt;/strong&gt;
\(f(0.5) = 8 \times 0.5 = 4 &amp;gt; 1!\)
Điều này hoàn toàn hợp lệ: hình tam giác có đáy \(0.5\) và chiều cao \(4\) nên diện tích đúng bằng \(\frac{1}{2} \times 0.5 \times 4 = 1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Tính xác suất \(\theta\) rơi vào khoảng \([0.25, 0.50]\):&lt;/strong&gt;
\(P(0.25 \le \theta \le 0.50) = \int_{0.25}^{0.50} 8\theta\,d\theta = \left[4\theta^2
ight]_{0.25}^{0.50} = 4(0.25) - 4(0.0625) = 1 - 0.25 = 0.75.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 4 — Xấp xỉ xác suất trên khoảng hẹp \([0.40, 0.41]\) bằng công thức \(f(x)\Delta x\):&lt;/strong&gt;
\(f(0.405) \times 0.01 = (8 \times 0.405) \times 0.01 = 3.24 \times 0.01 = 0.0324\) (đúng tuyệt đối vì \(f\) tuyến tính!).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Thấy \(f(\theta) = 4\) rồi kết luận “mô hình bị lỗi vì xác suất vượt quá 1” hoặc dùng trực tiếp \(f(\theta)\) để cộng dồn mà quên nhân với bề rộng \(\Delta \theta\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Kỳ vọng của phân phối tam giác trên là \(\mathbb{E}[\theta] = \int_0^{0.5} \theta \cdot 8\theta\,d\theta = \left[\frac{8\theta^3}{3}
ight]_0^{0.5} = \frac{8 \times 0.125}{3} = \frac{1}{3} \approx 0.333\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=hDjcxi9p0ak&quot;&gt;Probability density and mass functions&lt;/a&gt; — Intelligent Systems Lab, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Phân biệt trực quan hàm khối lượng xác suất (PMF) và hàm mật độ xác suất (PDF).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YXLVjCKVP7U&quot;&gt;Probability Distribution Functions (PMF, PDF, CDF)&lt;/a&gt; — zedstatistics, English. Giải thích mối liên hệ giữa PMF, PDF và hàm phân phối tích lũy (CDF) khi tính xác suất trên khoảng.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Why “probability of 0” does not mean “impossible”&lt;/td&gt;
          &lt;td&gt;Probabilities of probabilities, part 2](https://www.youtube.com/watch?v=ZA4JkHKZM50) — 3Blue1Brown, English. Làm rõ vì sao xác suất tại một điểm bằng 0 với biến liên tục và vai trò của hàm mật độ.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 1&lt;/strong&gt;: Giải thích vì sao \(P(X = 170) = 0\) đối với biến liên tục nhưng \(f(170)\) vẫn có thể khác 0. Hai đại lượng này khác nhau ở điểm nào?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 2&lt;/strong&gt;: Cho \(f(x) = 2x\) trên đoạn \([0, 1]\) và \(f(x) = 0\) ngoài đoạn đó.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Kiểm tra xem đây có phải là PDF hợp lệ hay không (tích phân bằng 1).&lt;/li&gt;
  &lt;li&gt;Tính \(P(0.2 \leq X \leq 0.5)\).&lt;/li&gt;
  &lt;li&gt;Giá trị \(f(0.3) = 0.6\) có phải là xác suất không? Nếu không, nó có ý nghĩa gì?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 3&lt;/strong&gt;: Xét hai phân phối chuẩn có cùng trung bình nhưng khác độ lệch chuẩn (ví dụ \(\sigma = 1\) và \(\sigma = 2\)). So sánh giá trị \(f(\mu)\) tại trung bình; phân phối nào có \(f(\mu)\) lớn hơn và vì sao?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 4&lt;/strong&gt;: Cho chiều cao \(X \sim \mathcal{N}(170 \text{ cm}, 10^2)\).&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nếu \(f(170 \text{ cm}) = 0.04 \text{ (1/cm)}\), thì \(f(1.70 \text{ m})\) bằng bao nhiêu (đơn vị 1/m)?&lt;/li&gt;
  &lt;li&gt;Tính \(P(160 \leq X \leq 180)\) theo cả hai hệ đơn vị và đối chiếu kết quả.&lt;/li&gt;
  &lt;li&gt;Giải thích vì sao xác suất bất biến còn \(f(x)\) thay đổi theo đơn vị.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 5&lt;/strong&gt;: Cho phân phối tiên nghiệm \(\theta \sim \text{Beta}(1, 1)\) (phân phối đều) và dữ liệu gồm 3 lần thành công trong 5 phép thử.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tìm phân phối hậu nghiệm \(p(\theta \mid x)\).&lt;/li&gt;
  &lt;li&gt;Giá trị \(p(0.5 \mid x)\) có phải là xác suất không? Nếu không, nó có ý nghĩa gì?&lt;/li&gt;
  &lt;li&gt;Tính khoảng tin cậy 90% cho \(\theta\).&lt;/li&gt;
  &lt;li&gt;Diễn giải biểu thức “\(P(a \leq \theta \leq b \mid x) = 0.90\)” bằng ngôn ngữ tích phân của PDF.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Wasserman, L. (2004).&lt;/strong&gt; &lt;em&gt;All of Statistics: A Concise Course in Statistical Inference&lt;/em&gt;. Springer.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 2: Random Variables — phần trình bày về PDF và sự khác biệt với PMF.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Casella, G., &amp;amp; Berger, R. L. (2002).&lt;/strong&gt; &lt;em&gt;Statistical Inference&lt;/em&gt; (2nd Edition). Duxbury.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 1: Probability Theory — giải thích chi tiết về PDF và các tính chất toán học.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., et al. (2013).&lt;/strong&gt; &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Appendix A: Standard probability distributions — sử dụng PDF trong bối cảnh Bayesian.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Seeing Theory - Probability Distributions&lt;/strong&gt;: &lt;a href=&quot;https://seeing-theory.brown.edu/&quot;&gt;https://seeing-theory.brown.edu/&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Công cụ trực quan hóa tương tác về các khái niệm PDF.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Tóm lại, cần luôn phân biệt: \(f(x)\) là mật độ xác suất, không phải xác suất; chỉ tích phân của \(f(x)\) trên một khoảng mới là xác suất.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_08_pvalues_and_hypothesis_testing/&quot;&gt;0.11 P-values và Kiểm định Giả thuyết&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.9: Giải tích Cơ bản</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_06_calculus_basics/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_06_calculus_basics</id>
   <content type="html">&lt;p&gt;Thống kê Bayes về bản chất là một cuộc đối thoại giữa &lt;strong&gt;hai phép toán giải tích&lt;/strong&gt;: &lt;em&gt;đạo hàm&lt;/em&gt; và &lt;em&gt;tích phân&lt;/em&gt;. Khi bạn muốn tìm giá trị tham số hợp lý nhất (ước lượng cực đại hợp lý MLE hoặc cực đại hậu nghiệm MAP), bạn lấy đạo hàm và giải phương trình bằng 0. Nhưng khi bạn muốn biết &lt;em&gt;toàn bộ phân phối hậu nghiệm&lt;/em&gt;, tính xác suất biên \(p(y) = \int p(y \mid \theta)p(\theta)\,d\theta\) hay dự báo cho dữ liệu mới, bạn buộc phải đối mặt với &lt;strong&gt;tích phân&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Chính sự chênh lệch độ khó giữa hai phép toán này — lấy đạo hàm luôn có quy tắc máy móc (lan truyền ngược / autodiff), còn lấy tích phân nhiều chiều hầu như vô phương giải tay — đã sinh ra cả hai nhánh công nghệ lớn nhất của Bayes hiện đại: &lt;strong&gt;MCMC&lt;/strong&gt; (dùng lấy mẫu ngẫu nhiên để tính tích phân) và &lt;strong&gt;Variational Inference&lt;/strong&gt; (biến bài toán tích phân thành bài toán tối ưu bằng đạo hàm).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu vai trò của đạo hàm, tích phân và tối ưu hóa trong suy luận thống kê Bayesian. Cụ thể, bạn sẽ nắm cách dùng đạo hàm để phân tích độ nhạy và tìm cực trị, dùng tích phân để chuẩn hóa mật độ và tính xác suất trên miền liên tục, và dùng tối ưu hóa để tìm ước lượng xấp xỉ (như MAP) trước hoặc song song với lấy mẫu hậu nghiệm.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-đạo-hàmgradient-tích-phân-chuẩn-hóa-và-cầu-nối-sang-hmc--variational-inference&quot;&gt;Kiến thức cần nhớ: Đạo hàm–Gradient, Tích phân chuẩn hóa và Cầu nối sang HMC / Variational Inference&lt;/h2&gt;

&lt;p&gt;Ba trụ cột giải tích mà mọi nhà thực hành Bayes cần nắm chắc:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Vi phân, Gradient &amp;amp; Ma trận Hessian:&lt;/strong&gt; Gradient \(abla_\theta \log p(\theta \mid y)\) chỉ hướng tăng nhanh nhất của log-posterior, giúp tìm điểm MAP. Ma trận Hessian \(\mathbf{H} = \nabla^2_\theta \log p(\theta \mid y)\) đo độ cong tại đỉnh: đỉnh càng nhọn (độ cong âm lớn), phương sai hậu nghiệm càng nhỏ. Trong &lt;strong&gt;Hamiltonian Monte Carlo (HMC / NUTS)&lt;/strong&gt; — động cơ mặc định của Stan và PyMC — gradient của log-posterior đóng vai trò “lực hấp dẫn” dẫn đường cho hạt chuyển động mượt mà qua không gian hàng nghìn chiều.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích phân &amp;amp; Chuẩn hóa (Marginal Likelihood / Evidence):&lt;/strong&gt; Mẫu số \(Z = p(y) = \int p(y \mid \theta)p(\theta)\,d\theta\) là diện tích dưới đường cong chưa chuẩn hóa. Nếu không chuẩn hóa được bằng giải tích (như prior liên hợp), ta cần tích phân số (Grid), lấy mẫu (MCMC) hoặc cận dưới biến phân (ELBO trong Variational Inference).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biến đổi biến số &amp;amp; Định thức Jacobian:&lt;/strong&gt; Khi đổi tham số (ví dụ từ độ lệch chuẩn \(\sigma &amp;gt; 0\) sang \(\phi = \log \sigma \in \mathbb{R}\) để tối ưu không ràng buộc), mật độ xác suất phải nhân thêm \(\left\lvert \frac{d\sigma}{d\phi} 
ight
vert = e^\phi\) để bảo toàn tổng xác suất bằng 1.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-vì-sao-giải-tích-là-lõi-của-thống-kê-bayesian-liên-tục&quot;&gt;Giới thiệu: Vì sao giải tích là lõi của thống kê Bayesian liên tục?&lt;/h2&gt;

&lt;p&gt;Nhiều mô hình Bayesian làm việc với tham số liên tục, trong đó ba thao tác toán học xuất hiện thường xuyên: lấy đạo hàm để tối ưu hàm log-posterior, lấy tích phân để chuẩn hóa phân phối và biên hóa (marginalize) biến ẩn, và dùng gradient để thiết kế các thuật toán tính toán hiệu quả. Vì vậy, giải tích không phải phần phụ trợ mà là công cụ lõi giúp chuyển mô hình xác suất thành suy luận tính toán được.&lt;/p&gt;

&lt;p&gt;Trong bài này, mỗi công thức được tiếp cận theo hai tầng: ký hiệu toán học hình thức và ý nghĩa thống kê thực tế. Cách đọc hai tầng này sẽ hỗ trợ trực tiếp cho các chương MCMC, hồi quy Bayesian và kiểm tra mô hình (model checking).&lt;/p&gt;

&lt;h2 id=&quot;khung-liên-hệ-với-quy-trình-bayesian&quot;&gt;Khung liên hệ với quy trình Bayesian&lt;/h2&gt;

&lt;p&gt;Một quy trình Bayesian điển hình có thể tóm gọn như sau:&lt;/p&gt;

\[\text{prior} \times \text{likelihood} \propto \text{posterior (unnormalized)}.\]

&lt;p&gt;Từ biểu thức này, giải tích tham gia ở hai bước chính:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đạo hàm&lt;/strong&gt;: tìm điểm cực đại của log-posterior (ước lượng MAP, xấp xỉ Laplace).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích phân&lt;/strong&gt;: chuẩn hóa phân phối hậu nghiệm hoặc tính xác suất và kỳ vọng trên miền liên tục.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;1-đạo-hàm-derivatives&quot;&gt;1. Đạo hàm (Derivatives)&lt;/h2&gt;

&lt;h3 id=&quot;11-định-nghĩa&quot;&gt;1.1. Định nghĩa&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm&lt;/strong&gt; đo tốc độ thay đổi tức thời của hàm số:&lt;/p&gt;

\[f&apos;(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}\]

&lt;p&gt;&lt;strong&gt;Ý nghĩa hình học&lt;/strong&gt;: độ dốc của tiếp tuyến với đồ thị tại điểm \(x\).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Hàm số
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Đạo hàm (giải tích)
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Đạo hàm số (numerical)
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;numerical_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vẽ hàm và tiếp tuyến
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;slope&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tiếp tuyến: y - y0 = slope * (x - x0)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tangent_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;slope&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x) = x²&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tangent_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tiếp tuyến tại x=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zorder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đạo hàm là Độ dốc của Tiếp tuyến&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# So sánh đạo hàm giải tích vs số
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;numerical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;numerical_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đạo hàm tại x=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Giải tích: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Số: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numerical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;12-quy-tắc-đạo-hàm-cơ-bản&quot;&gt;1.2. Quy tắc Đạo hàm Cơ bản&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Hàm&lt;/th&gt;
      &lt;th&gt;Đạo hàm&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(c\) (hằng số)&lt;/td&gt;
      &lt;td&gt;\(0\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(x^n\)&lt;/td&gt;
      &lt;td&gt;\(nx^{n-1}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(e^x\)&lt;/td&gt;
      &lt;td&gt;\(e^x\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\ln(x)\)&lt;/td&gt;
      &lt;td&gt;\(\frac{1}{x}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\sin(x)\)&lt;/td&gt;
      &lt;td&gt;\(\cos(x)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\cos(x)\)&lt;/td&gt;
      &lt;td&gt;\(-\sin(x)\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Quy tắc tổng&lt;/strong&gt;: \((f + g)&apos; = f&apos; + g&apos;\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quy tắc tích&lt;/strong&gt;: \((fg)&apos; = f&apos;g + fg&apos;\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quy tắc thương&lt;/strong&gt;: \(\left(\frac{f}{g}\right)&apos; = \frac{f&apos;g - fg&apos;}{g^2}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quy tắc hàm hợp (Chain rule)&lt;/strong&gt;: \((f(g(x)))&apos; = f&apos;(g(x)) \cdot g&apos;(x)\)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Ví dụ: f(x) = (x² + 1)³
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Đạo hàm bằng chain rule:
# f&apos;(x) = 3(x² + 1)² · 2x = 6x(x² + 1)²
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;numerical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;numerical_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x) = (x² + 1)³ tại x=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Giải tích: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Số: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numerical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;13-đạo-hàm-riêng-partial-derivatives&quot;&gt;1.3. Đạo hàm Riêng (Partial Derivatives)&lt;/h3&gt;

&lt;p&gt;Với hàm nhiều biến \(f(x, y)\), đạo hàm riêng theo \(x\) (khi giữ \(y\) cố định) là:&lt;/p&gt;

\[\frac{\partial f}{\partial x} = \lim_{h \to 0} \frac{f(x+h, y) - f(x, y)}{h}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Hàm 2 biến: f(x, y) = x²y + y³
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Đạo hàm riêng
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;df_dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;df_dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vẽ hàm 3D
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mpl_toolkits.mplot3d&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Axes3D&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;meshgrid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Surface plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;add_subplot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;121&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;projection&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;3d&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot_surface&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;viridis&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_zlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x, y)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x, y) = x²y + y³&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Contour plot với gradient
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;add_subplot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;122&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;contour&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;contour&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;levels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;viridis&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;contour&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inline&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vẽ gradient tại một số điểm
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;xi&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yi&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;df_dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;df_dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.003&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Contour và Gradient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_aspect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tính tại điểm cụ thể
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tại (x, y) = (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  f = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ∂f/∂x = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;df_dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ∂f/∂y = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;df_dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;14-gradient&quot;&gt;1.4. Gradient&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gradient&lt;/strong&gt; là vector gồm tất cả các đạo hàm riêng của hàm số:&lt;/p&gt;

\[\nabla f = \begin{bmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_n} \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Ý nghĩa&lt;/strong&gt;: vector gradient chỉ hướng tăng nhanh nhất của hàm số.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;df_dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;df_dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient tại (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Độ lớn: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;video-ngắn-giải-tích-đạo-hàm-gradient--tìm-cực-đại-map&quot;&gt;Video ngắn: Giải tích: Đạo hàm, Gradient &amp;amp; Tìm cực đại MAP&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-09a-gradient-map-ascent.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 8 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): tiếp tuyến trượt dọc log-posterior, leo đồi Gradient Ascent lên đỉnh MAP, độ cong Hessian, Autodiff và động cơ HMC.&lt;/p&gt;

&lt;h2 id=&quot;2-tích-phân-integrals&quot;&gt;2. Tích phân (Integrals)&lt;/h2&gt;

&lt;h3 id=&quot;21-tích-phân-xác-định&quot;&gt;2.1. Tích phân Xác định&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ý nghĩa hình học&lt;/strong&gt;: diện tích (có dấu) giới hạn giữa đồ thị hàm số và trục hoành trên đoạn \([a, b]\):&lt;/p&gt;

\[\int_a^b f(x) dx\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Hàm số
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tích phân giải tích: ∫x² dx = x³/3
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tích phân từ 0 đến 2
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;integral_analytical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tích phân số (numerical)
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;integrate&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;integral_numerical&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;integrate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tích phân ∫₀² x² dx:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Giải tích: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;integral_analytical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Số: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;integral_numerical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vẽ
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x) = x²&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tô vùng tích phân
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_fill&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fill_between&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Diện tích = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;integral_analytical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tích phân = Diện tích dưới đường cong&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;22-tích-phân-trong-xác-suất&quot;&gt;2.2. Tích phân trong Xác suất&lt;/h3&gt;

&lt;p&gt;Một &lt;strong&gt;hàm mật độ xác suất (PDF)&lt;/strong&gt; hợp lệ phải thỏa mãn điều kiện chuẩn hóa:&lt;/p&gt;

\[\int_{-\infty}^{\infty} f(x) dx = 1\]

&lt;p&gt;Khi đó, &lt;strong&gt;xác suất&lt;/strong&gt; để biến ngẫu nhiên \(X\) rơi vào đoạn \([a, b]\) là:&lt;/p&gt;

\[P(a \leq X \leq b) = \int_a^b f(x) dx\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Normal distribution
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pdf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tính P(-1 ≤ X ≤ 1)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;integrate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;N(0, 1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tô vùng xác suất
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pdf_fill&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fill_between&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pdf_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;P(-1 ≤ X ≤ 1) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mật độ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Xác suất = Diện tích dưới PDF&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# So sánh với CDF
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob_cdf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;P(-1 ≤ X ≤ 1):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tích phân: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  CDF: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob_cdf&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;23-tích-phân-đa-biến&quot;&gt;2.3. Tích phân Đa biến&lt;/h3&gt;

\[\int \int f(x, y) \, dx \, dy\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Hàm 2 biến
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tích phân trên [0,1] × [0,2]
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;integrate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dblquad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;∫₀¹ ∫₀² xy dy dx = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Giải tích: ∫₀¹ x dx · ∫₀² y dy = [x²/2]₀¹ · [y²/2]₀² = 0.5 · 2 = 1
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Giải tích: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;video-ngắn-giải-tích-từ-tích-phân-chuẩn-hóa-đến-mcmc--vi&quot;&gt;Video ngắn: Giải tích: Từ Tích phân chuẩn hóa đến MCMC &amp;amp; VI&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-09b-integral-to-mcmc.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 8 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): tổng Riemann thu hẹp dx, nút thắt tích phân chuẩn hóa p(y), cơ chế triệt tiêu hằng số Z của MCMC và Suy diễn Biến phân VI.&lt;/p&gt;

&lt;h2 id=&quot;3-tối-ưu-hóa-optimization&quot;&gt;3. Tối ưu hóa (Optimization)&lt;/h2&gt;

&lt;h3 id=&quot;31-cực-trị&quot;&gt;3.1. Cực trị&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Điều kiện cần&lt;/strong&gt; (necessary condition) để điểm \(x\) là cực trị của hàm khả vi là:&lt;/p&gt;

\[f&apos;(x) = 0\]

&lt;p&gt;&lt;strong&gt;Điều kiện đủ&lt;/strong&gt; (sufficient condition) dựa trên đạo hàm bậc hai:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(f&apos;&apos;(x) &amp;gt; 0\): điểm cực tiểu (minimum).&lt;/li&gt;
  &lt;li&gt;\(f&apos;&apos;(x) &amp;lt; 0\): điểm cực đại (maximum).&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Hàm số: f(x) = x³ - 6x² + 9x + 1
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_double_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tìm điểm tới hạn: f&apos;(x) = 0
# 3x² - 12x + 9 = 0
# x² - 4x + 3 = 0
# (x-1)(x-3) = 0
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;critical_points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;critical_points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;yc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;f2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_double_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Minimum
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Min tại x=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Maximum
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Max tại x=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;yc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zorder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  f(x) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;yc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(x) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(x) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f2&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cực tiểu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cực đại&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tìm Cực trị&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;32-gradient-descent&quot;&gt;3.2. Gradient Descent&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Thuật toán&lt;/strong&gt; tìm cực tiểu bằng cách cập nhật ngược hướng gradient:&lt;/p&gt;

\[x_{n+1} = x_n - \alpha \nabla f(x_n)\]

&lt;p&gt;trong đó \(\alpha\) là tốc độ học (learning rate).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Hàm 2 biến: f(x, y) = x² + y²
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Gradient descent
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;path&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Chạy từ điểm khởi đầu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vẽ
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;meshgrid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;contour&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;contour&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;levels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;viridis&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;contour&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inline&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vẽ đường đi
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ro-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;markersize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient Descent&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;300&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;gold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
           &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Minimum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zorder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient Descent&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient Descent:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bắt đầu: (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;), f = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kết thúc: (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;), f = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;33-ước-lượng-hợp-lý-cực-đại-maximum-likelihood-estimation--mle&quot;&gt;3.3. Ước lượng Hợp lý Cực đại (Maximum Likelihood Estimation — MLE)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ&lt;/strong&gt;: ước lượng tham số \(\mu\) của phân phối Normal khi biết \(\sigma\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hàm hợp lý (Likelihood)&lt;/strong&gt;:&lt;/p&gt;

\[L(\mu) = \prod_{i=1}^{n} \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x_i - \mu)^2}{2\sigma^2}\right)\]

&lt;p&gt;&lt;strong&gt;Log-likelihood&lt;/strong&gt;:&lt;/p&gt;

\[\ell(\mu) = -\frac{n}{2}\log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\sum_{i=1}^{n}(x_i - \mu)^2\]

&lt;p&gt;&lt;strong&gt;Tìm cực đại&lt;/strong&gt; bằng cách giải \(\frac{d\ell}{d\mu} = 0\):&lt;/p&gt;

\[\Rightarrow \hat{\mu} = \frac{1}{n}\sum_{i=1}^{n} x_i\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Dữ liệu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;true_mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Log-likelihood function
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;log_likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vẽ log-likelihood
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_range&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ll_values&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# MLE
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ll_values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Log-likelihood&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
           &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;MLE: μ̂ = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mle&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
           &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True: μ = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_mu&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;μ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Log-likelihood&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Maximum Likelihood Estimation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True μ: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_mu&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;MLE μ̂: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mle&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sample mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;4-ứng-dụng-trong-thống-kê-bayesian&quot;&gt;4. Ứng dụng trong Thống kê Bayesian&lt;/h2&gt;

&lt;h3 id=&quot;41-điểm-cực-đại-hậu-nghiệm-map&quot;&gt;4.1. Điểm Cực đại Hậu nghiệm (MAP)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Maximum A Posteriori (MAP)&lt;/strong&gt; tìm mode (điểm có mật độ lớn nhất) của phân phối hậu nghiệm:&lt;/p&gt;

\[\hat{\theta}_{MAP} = \arg\max_\theta p(\theta \mid \mathbf{x})\]

&lt;p&gt;Tương đương trên thang log:&lt;/p&gt;

\[\hat{\theta}_{MAP} = \arg\max_\theta [\log p(\mathbf{x} \mid \theta) + \log p(\theta)]\]

&lt;h3 id=&quot;42-xấp-xỉ-laplace-laplace-approximation&quot;&gt;4.2. Xấp xỉ Laplace (Laplace Approximation)&lt;/h3&gt;

&lt;p&gt;Xấp xỉ phân phối hậu nghiệm bằng một phân phối Normal đặt tâm tại mode \(\hat{\theta}\):&lt;/p&gt;

\[p(\theta \mid \mathbf{x}) \approx \mathcal{N}\left(\hat{\theta}, \left[-\frac{d^2 \log p(\theta \mid \mathbf{x})}{d\theta^2}\bigg\vert _{\hat{\theta}}\right]^{-1}\right)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Ví dụ: Beta posterior
# Prior: Beta(2, 2)
# Likelihood: Binomial(n, theta)
# Data: 7 successes in 10 trials
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;alpha_prior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n_success&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Posterior: Beta(alpha_prior + n_success, beta_prior + n_total - n_success)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_success&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_success&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Log posterior (unnormalized)
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;log_posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;or&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inf&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;log_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;log_lik&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_success&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_success&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_lik&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# MAP (mode)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Laplace approximation
# Tính đạo hàm bậc 2
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;log_posterior_second_deriv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;variance_laplace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;log_posterior_second_deriv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;std_laplace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;variance_laplace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vẽ
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.99&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;laplace_approx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std_laplace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True Posterior (Beta)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;laplace_approx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Laplace Approximation (Normal)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
           &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;MAP: θ̂ = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;θ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mật độ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Laplace Approximation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;MAP: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Laplace std: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std_laplace&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True std: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;giải-thích-từ-đạo-hàm-tìm-đỉnh-map-đến-xấp-xỉ-laplace-bằng-tay&quot;&gt;Giải thích: Từ đạo hàm tìm đỉnh MAP đến xấp xỉ Laplace bằng tay&lt;/h2&gt;

&lt;p&gt;Hãy đọc chậm chuỗi 4 bước nối liền giải tích 1 với một công cụ cực mạnh của thống kê Bayes là &lt;strong&gt;xấp xỉ Laplace&lt;/strong&gt; (Laplace Approximation):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Viết log-posterior chưa chuẩn hóa:&lt;/strong&gt; \(g(\theta) = \log p(y \mid \theta) + \log p(\theta)\) (bỏ hằng số \(\log p(y)\) vì đạo hàm của hằng số bằng 0).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giải \(g&apos;(\theta) = 0\) để tìm đỉnh \(\hat{\theta}_{\text{MAP}}\):&lt;/strong&gt; Đây là điểm có mật độ hậu nghiệm cao nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính đạo hàm bậc hai \(g&apos;&apos;(\hat{\theta}_{\text{MAP}})\) để đo độ cong:&lt;/strong&gt; Vì là cực đại nên \(g&apos;&apos;(\hat{\theta}_{\text{MAP}}) &amp;lt; 0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khai triển Taylor bậc 2 quanh đỉnh:&lt;/strong&gt; \(g(\theta) \approx g(\hat{\theta}) + \frac{1}{2} g&apos;&apos;(\hat{\theta})(\theta - \hat{\theta})^2\). So sánh với log mật độ Chuẩn \(-\frac{(\theta - \mu)^2}{2\sigma^2}\), ta lập tức thu được xấp xỉ hậu nghiệm:
\(\theta \mid y \approx \mathcal{N}\!\left(\hat{\theta}_{\text{MAP}},\; \frac{-1}{g&apos;&apos;(\hat{\theta}_{\text{MAP}})}
ight).\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-tìm-map-và-phương-sai-xấp-xỉ-laplace-cho-mô-hình-betabinomial&quot;&gt;Ví dụ tính toán làm từng bước: Tìm MAP và phương sai xấp xỉ Laplace cho mô hình Beta–Binomial&lt;/h3&gt;

&lt;p&gt;Giả sử bạn dùng prior \(\text{Beta}(2, 2)\) và quan sát \(k = 7\) thành công trong \(n = 10\) lần thử. Ta đã biết hậu nghiệm chính xác là \(\text{Beta}(9, 5)\), nên đây là cơ hội tuyệt vời để kiểm chứng phép tính đạo hàm bằng tay!&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Log-posterior chưa chuẩn hóa:&lt;/strong&gt;
\(g(\theta) = 8 \ln \theta + 4 \ln(1 - \theta).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Lấy đạo hàm bậc 1 và cho bằng 0:&lt;/strong&gt;
\(g&apos;(\theta) = \frac{8}{\theta} - \frac{4}{1 - \theta} = 0 \implies 8(1 - \theta) = 4\theta \implies 12\theta = 8 \implies \hat{\theta}_{\text{MAP}} = \frac{2}{3} \approx 0.6667.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Lấy đạo hàm bậc 2 tại \(\hat{\theta} = 2/3\):&lt;/strong&gt;
\(g&apos;&apos;(\theta) = -\frac{8}{\theta^2} - \frac{4}{(1-\theta)^2}.\)
Thay \(\theta = 2/3\) và \(1 - \theta = 1/3\):
\(g&apos;&apos;(2/3) = -\frac{8}{4/9} - \frac{4}{1/9} = -18 - 36 = -54.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 4 — Suy ra phương sai và độ lệch chuẩn xấp xỉ Laplace:&lt;/strong&gt;
\(\hat{\sigma}^2 = \frac{-1}{-54} = \frac{1}{54} \approx 0.01852 \implies \hat{\sigma} \approx 0.1361.\)
Đối chiếu với độ lệch chuẩn chính xác của \(\text{Beta}(9, 5)\): \(\sqrt{\frac{9 \times 5}{14^2 \times 15}} = \sqrt{\frac{45}{2940}} \approx 0.1237\) — chỉ bằng vài dòng đạo hàm tay, ta đã xấp xỉ sát gần đúng!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nghĩ rằng tìm được MAP là đã làm xong suy diễn Bayes. MAP chỉ là &lt;em&gt;một điểm duy nhất&lt;/em&gt;; khi hậu nghiệm đa đỉnh hoặc lệch mạnh, MAP có thể nằm rất xa vùng chứa phần lớn khối lượng xác suất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu cỡ mẫu tăng gấp 10 lần (\(k=70, n=100\)), \(g&apos;&apos;(\hat{\theta})\) lớn gấp khoảng 10 lần, nên độ lệch chuẩn hậu nghiệm thu nhỏ lại khoảng \(\sqrt{10} \approx 3.16\) lần — đúng quy luật hội tụ \(1/\sqrt{n}\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[The paradox of the derivative&lt;/td&gt;
          &lt;td&gt;Chapter 2, Essence of calculus](https://www.youtube.com/watch?v=9vKqVkMQHKk) — 3Blue1Brown, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giải thích trực quan đạo hàm như độ nhạy của hàm số khi đầu vào thay đổi nhỏ.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Integration and the fundamental theorem of calculus&lt;/td&gt;
          &lt;td&gt;Chapter 8, Essence of calculus](https://www.youtube.com/watch?v=rfG8ce4nNh0) — 3Blue1Brown, English. Trình bày tích phân như phép cộng dồn các phần tử nhỏ, hỗ trợ chuẩn hóa phân phối và tính xác suất liên tục.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, English. Minh họa cơ chế đi ngược hướng dốc nhất của gradient descent, áp dụng trực tiếp cho phần tối ưu hóa trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đạo hàm&lt;/strong&gt;: Tính đạo hàm của các hàm sau:
    &lt;ul&gt;
      &lt;li&gt;
\[f(x) = 3x^4 - 2x^2 + 5\]
      &lt;/li&gt;
      &lt;li&gt;
\[g(x) = e^{x^2}\]
      &lt;/li&gt;
      &lt;li&gt;
\[h(x) = \ln(x^2 + 1)\]
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đạo hàm riêng&lt;/strong&gt;: Cho \(f(x, y) = x^2y + xy^2\). Tính \(\frac{\partial f}{\partial x}\) và \(\frac{\partial f}{\partial y}\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích phân&lt;/strong&gt;: Tính các tích phân sau:
    &lt;ul&gt;
      &lt;li&gt;
\[\int_0^1 x^2 dx\]
      &lt;/li&gt;
      &lt;li&gt;
\[\int_1^e \frac{1}{x} dx\]
      &lt;/li&gt;
      &lt;li&gt;\(\int_{-\infty}^{\infty} e^{-x^2} dx\) (gợi ý: \(\sqrt{\pi}\))&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tối ưu hóa&lt;/strong&gt;: Tìm cực trị của hàm số \(f(x) = x^3 - 3x + 1\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;MLE&lt;/strong&gt;: Cho dữ liệu lấy mẫu độc lập từ phân phối \(\text{Exponential}(\lambda)\). Tìm ước lượng MLE của \(\lambda\):
    &lt;ul&gt;
      &lt;li&gt;Hàm hợp lý: \(L(\lambda) = \prod_{i=1}^{n} \lambda e^{-\lambda x_i}\)&lt;/li&gt;
      &lt;li&gt;Gợi ý: \(\hat{\lambda} = \frac{n}{\sum x_i}\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Stewart, J. (2015).&lt;/strong&gt; &lt;em&gt;Calculus: Early Transcendentals&lt;/em&gt;. Cengage Learning.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;3Blue1Brown - Essence of Calculus&lt;/strong&gt; - https://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SciPy Integrate&lt;/strong&gt; - https://docs.scipy.org/doc/scipy/reference/integrate.html&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_07_probability_density_functions/&quot;&gt;0.10 Hàm Mật độ Xác suất (PDF)&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.8: Đại số Tuyến tính Cơ bản</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_05_linear_algebra/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_05_linear_algebra</id>
   <content type="html">&lt;p&gt;Khi mô hình thống kê chỉ có một tham số \(\theta\), ta có thể viết mọi thứ bằng đại số phổ thông. Nhưng đời thực hiếm khi dừng ở một biến: hồi quy đa biến có hàng chục hệ số \(\boldsymbol{\beta}\), phân phối Chuẩn đa biến có cả ma trận hiệp phương sai \(\boldsymbol{\Sigma}\), và mạng nơ-ron Bayes có hàng nghìn trọng số tương tác chéo. Đại số tuyến tính chính là chiếc kính viễn vọng giúp nén hàng nghìn phương trình lộn xộn thành một dòng gọn sắc: \(\mathbf{y} = \mathbf{X}\boldsymbol{\beta} + \boldsymbol{\varepsilon}\).&lt;/p&gt;

&lt;p&gt;Trong thống kê Bayes, đại số tuyến tính còn mang ý nghĩa hình học trực tiếp: &lt;strong&gt;trị riêng và vector riêng của ma trận hiệp phương sai cho ta biết các trục chính của “đám mây bất định” hậu nghiệm&lt;/strong&gt;, quyết định tốc độ hội tụ của mọi thuật toán MCMC.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu vì sao đại số tuyến tính là nền tảng toán học của mô hình thống kê Bayesian: dữ liệu được biểu diễn dưới dạng vector và ma trận, tham số hồi quy được viết thành toán tử tuyến tính, và nhiều thuật toán suy diễn dựa trực tiếp vào các phép biến đổi tuyến tính. Bạn cũng sẽ nắm được ý nghĩa hình học của các phép toán thay vì chỉ thao tác ký hiệu.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-không-gian-vector-ma-trận-xác-định-dương-và-hồi-quy-bayes-đa-biến&quot;&gt;Kiến thức cần nhớ: Không gian vector, Ma trận xác định dương và Hồi quy Bayes đa biến&lt;/h2&gt;

&lt;p&gt;Ba trụ cột đại số tuyến tính thiết yếu cho suy diễn Bayes:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tích ma trận &amp;amp; Chiếu trực giao (Linear Maps &amp;amp; Projections):&lt;/strong&gt; Ma trận thiết kế \(\mathbf{X}\) ánh xạ vector tham số \(\boldsymbol{\beta}\) sang không gian dự đoán \(\hat{\mathbf{y}} = \mathbf{X}\boldsymbol{\beta}\). Nghiệm bình phương tối thiểu cổ điển \(\hat{\boldsymbol{\beta}}_{\text{OLS}} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y}\) thực chất là phép chiếu trực giao vector dữ liệu \(\mathbf{y}\) xuống không gian cột của \(\mathbf{X}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ma trận đối xứng xác định dương &amp;amp; Phân rã phổ (SPD Matrices &amp;amp; Eigendecomposition):&lt;/strong&gt; Mọi ma trận hiệp phương sai \(\boldsymbol{\Sigma}\) và ma trận độ chính xác \(\boldsymbol{\Lambda} = \boldsymbol{\Sigma}^{-1}\) hợp lệ đều đối xứng và bán xác định dương (mọi trị riêng \(\lambda_i \ge 0\)). Phân rã Cholesky \(\boldsymbol{\Sigma} = \mathbf{L}\mathbf{L}^T\) là công cụ cốt lõi để sinh mẫu Chuẩn đa biến và tính log-determinant ổn định mà không cần nghịch đảo ma trận trực tiếp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Hồi quy Tuyến tính Bayes (Ridge = Gaussian Prior):&lt;/strong&gt; Khi đặt prior Chuẩn \(\boldsymbol{\beta} \sim \mathcal{N}(\mathbf{0}, \tau^2 \mathbf{I})\), ma trận độ chính xác hậu nghiệm trở thành \(\mathbf{X}^T\mathbf{X}/\sigma^2 + \mathbf{I}/\tau^2\). Phép cộng \(\lambda \mathbf{I}\) vào đường chéo làm tăng mọi trị riêng thêm \(\lambda &amp;gt; 0\), giúp ma trận &lt;strong&gt;luôn khả nghịch&lt;/strong&gt; ngay cả khi dữ liệu bị đa cộng tuyến!&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-từ-công-thức-rời-rạc-đến-cấu-trúc-tuyến-tính&quot;&gt;Giới thiệu: Từ công thức rời rạc đến cấu trúc tuyến tính&lt;/h2&gt;

&lt;p&gt;Khi số biến tăng lên, việc viết mô hình bằng từng phương trình riêng lẻ trở nên rườm rà và khó theo dõi. Đại số tuyến tính giải quyết vấn đề này bằng cách gom các đại lượng vào vector và ma trận, giúp nhìn mô hình như một cấu trúc gọn gàng và thống nhất. Hầu hết mô hình Bayesian hiện đại — từ hồi quy tuyến tính, GLM đến mô hình phân cấp — đều được biểu diễn và tính toán hiệu quả trên nền tảng này.&lt;/p&gt;

&lt;p&gt;Nếu Bài 0.7 cung cấp công cụ lập trình bằng Python, thì bài học này cung cấp ngôn ngữ toán học tương ứng cho các chương mô hình hóa phía sau.&lt;/p&gt;

&lt;h2 id=&quot;cầu-nối-sang-suy-luận-bayesian&quot;&gt;Cầu nối sang suy luận Bayesian&lt;/h2&gt;

&lt;p&gt;Nhiều mô hình Bayesian cơ bản có thể viết gọn bằng ký hiệu ma trận. Chẳng hạn, mô hình hồi quy Gaussian được viết là:&lt;/p&gt;

\[\mathbf{y}=\mathbf{X}\boldsymbol{\beta}+\boldsymbol{\epsilon},\qquad
\boldsymbol{\epsilon}\sim\mathcal{N}(\mathbf{0},\sigma^2\mathbf{I}).\]

&lt;p&gt;Cách viết này tách rõ ba thành phần: ma trận dữ liệu \(\mathbf{X}\), vector tham số \(\boldsymbol{\beta}\) và cấu trúc nhiễu \(\boldsymbol{\epsilon}\). Khi sang bước suy diễn hậu nghiệm, các đối tượng này sẽ xuất hiện xuyên suốt cả trong công thức lẫn mã tính toán.&lt;/p&gt;

&lt;h2 id=&quot;1-vectors-vectơ&quot;&gt;1. Vectors (Vectơ)&lt;/h2&gt;

&lt;h3 id=&quot;11-định-nghĩa&quot;&gt;1.1. Định nghĩa&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Vector&lt;/strong&gt; là một mảng số có thứ tự, có thể dùng để biểu diễn một điểm hoặc một hướng trong không gian.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vector cột&lt;/strong&gt; (thường dùng):&lt;/p&gt;

\[\mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Vector hàng&lt;/strong&gt;:&lt;/p&gt;

\[\mathbf{x}^T = \begin{bmatrix} x_1 &amp;amp; x_2 &amp;amp; \cdots &amp;amp; x_n \end{bmatrix}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo vectors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Vector 2D
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Vector 3D
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Số chiều (dimension): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Độ dài (length): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;12-trực-quan-hóa-vectors&quot;&gt;1.2. Trực quan hóa Vectors&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Vẽ vectors trong 2D
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;vectors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;for &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vectors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angles&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale_units&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
             &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₁&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₂&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vectors trong không gian 2D&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_aspect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;13-phép-toán-với-vectors&quot;&gt;1.3. Phép toán với Vectors&lt;/h3&gt;

&lt;h4 id=&quot;cộngtrừ-vectors&quot;&gt;Cộng/Trừ Vectors&lt;/h4&gt;

\[\mathbf{x} + \mathbf{y} = \begin{bmatrix} x_1 + y_1 \\ x_2 + y_2 \\ \vdots \\ x_n + y_n \end{bmatrix}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Cộng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v + w = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Trừ
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_minus_w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v - w = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_minus_w&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Trực quan hóa
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vector v (đỏ)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angles&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale_units&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
         &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vector w (xanh dương)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angles&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale_units&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
         &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vector v+w (xanh lá)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angles&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale_units&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
         &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.015&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v+w&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vẽ hình bình hành
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₁&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₂&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Phép cộng Vectors&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_aspect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;nhân-với-số-vô-hướng-scalar&quot;&gt;Nhân với số vô hướng (Scalar)&lt;/h4&gt;

\[c \mathbf{x} = \begin{bmatrix} c x_1 \\ c x_2 \\ \vdots \\ c x_n \end{bmatrix}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Nhân với scalars khác nhau
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;scalars&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;purple&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scalar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scalars&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scaled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scalar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scaled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scaled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angles&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale_units&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
             &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scalar&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₁&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₂&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nhân Vector với Scalar&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_aspect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;tích-vô-hướng-dot-product&quot;&gt;Tích Vô hướng (Dot Product)&lt;/h4&gt;

\[\mathbf{x} \cdot \mathbf{y} = \sum_{i=1}^{n} x_i y_i = x_1 y_1 + x_2 y_2 + \cdots + x_n y_n\]

&lt;p&gt;&lt;strong&gt;Ý nghĩa hình học&lt;/strong&gt;:&lt;/p&gt;

\[\mathbf{x} \cdot \mathbf{y} = \|\mathbf{x}\| \|\mathbf{y}\| \cos(\theta)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Dot product
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot_product&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v · w = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot_product&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Hoặc
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot_product2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v @ w = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot_product2&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tính góc giữa 2 vectors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm_v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;norm_w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;cos_theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dot_product&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm_v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;norm_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_rad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arccos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cos_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_deg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;degrees&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;||v|| = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm_v&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;||w|| = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm_w&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Góc giữa v và w: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_deg&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;°&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Tính chất quan trọng&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nếu \(\mathbf{x} \cdot \mathbf{y} = 0\): hai vector vuông góc (orthogonal).&lt;/li&gt;
  &lt;li&gt;Nếu \(\mathbf{x} \cdot \mathbf{y} &amp;gt; 0\): góc giữa hai vector là góc nhọn.&lt;/li&gt;
  &lt;li&gt;Nếu \(\mathbf{x} \cdot \mathbf{y} &amp;lt; 0\): góc giữa hai vector là góc tù.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;độ-dài-norm&quot;&gt;Độ dài (Norm)&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Chuẩn Euclid (L2 norm)&lt;/strong&gt;:&lt;/p&gt;

\[\|\mathbf{x}\| = \sqrt{\sum_{i=1}^{n} x_i^2} = \sqrt{\mathbf{x} \cdot \mathbf{x}}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;||v|| = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 5.0
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Vector đơn vị (unit vector)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_unit&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vector đơn vị: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_unit&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Độ dài: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_unit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1.0
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;2-matrices-ma-trận&quot;&gt;2. Matrices (Ma trận)&lt;/h2&gt;

&lt;h3 id=&quot;21-định-nghĩa&quot;&gt;2.1. Định nghĩa&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ma trận (matrix)&lt;/strong&gt; là một mảng số hai chiều:&lt;/p&gt;

\[\mathbf{A} = \begin{bmatrix} 
a_{11} &amp;amp; a_{12} &amp;amp; \cdots &amp;amp; a_{1n} \\
a_{21} &amp;amp; a_{22} &amp;amp; \cdots &amp;amp; a_{2n} \\
\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\
a_{m1} &amp;amp; a_{m2} &amp;amp; \cdots &amp;amp; a_{mn}
\end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Kích thước&lt;/strong&gt;: \(m \times n\) (\(m\) hàng, \(n\) cột).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Tạo matrices
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 3)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;B shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (3, 2)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Ma trận đặc biệt
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;I&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Ma trận đơn vị 3x3
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Ma trận 0
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;O&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Ma trận 1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;22-phép-toán-với-ma-trận&quot;&gt;2.2. Phép toán với Ma trận&lt;/h3&gt;

&lt;h4 id=&quot;cộngtrừ-cùng-kích-thước&quot;&gt;Cộng/Trừ (cùng kích thước)&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A + B =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A - B =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;nhân-với-số-vô-hướng&quot;&gt;Nhân với số vô hướng&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2A =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;nhân-ma-trận&quot;&gt;Nhân Ma trận&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Điều kiện&lt;/strong&gt;: số cột của \(\mathbf{A}\) phải bằng số hàng của \(\mathbf{B}\). Nếu \(\mathbf{A}\) có kích thước \(m \times n\) và \(\mathbf{B}\) có kích thước \(n \times p\), thì \(\mathbf{C} = \mathbf{AB}\) có kích thước \(m \times p\) với phần tử:&lt;/p&gt;

\[c_{ij} = \sum_{k=1}^{n} a_{ik} b_{kj}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2x3
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 3x2
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;C&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2x2
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A @ B =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Lưu ý: Nhân ma trận không giao hoán
# A @ B ≠ B @ A (thường)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;chuyển-vị-transpose&quot;&gt;Chuyển vị (Transpose)&lt;/h4&gt;

\[(\mathbf{A}^T)_{ij} = a_{ji}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;A_T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A^T =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tính chất: (A^T)^T = A
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(A^T)^T = A?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array_equal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;23-ma-trận-nghịch-đảo&quot;&gt;2.3. Ma trận Nghịch đảo&lt;/h3&gt;

&lt;p&gt;Với ma trận vuông \(\mathbf{A}\) kích thước \(n \times n\), ma trận nghịch đảo \(\mathbf{A}^{-1}\) (nếu tồn tại) thỏa mãn:&lt;/p&gt;

\[\mathbf{A} \mathbf{A}^{-1} = \mathbf{A}^{-1} \mathbf{A} = \mathbf{I}\]

&lt;p&gt;&lt;strong&gt;Lưu ý&lt;/strong&gt;: không phải ma trận vuông nào cũng khả nghịch; những ma trận không có nghịch đảo được gọi là ma trận suy biến (singular matrix).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tính nghịch đảo
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_inv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A^(-1) =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;I_check&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A_inv&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A @ A^(-1) =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;I_check&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ma trận không khả nghịch
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;singular&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                     &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Hàng 2 = 2 * Hàng 1
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;try&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;singular_inv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;singular&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;except&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LinAlgError&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Ma trận singular không có nghịch đảo!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;24-định-thức-determinant&quot;&gt;2.4. Định thức (Determinant)&lt;/h3&gt;

&lt;p&gt;Cho ma trận vuông \(\mathbf{A}\), với trường hợp \(2 \times 2\):&lt;/p&gt;

\[\det(\mathbf{A}) = \begin{vmatrix} a &amp;amp; b \\ c &amp;amp; d \end{vmatrix} = ad - bc\]

&lt;p&gt;&lt;strong&gt;Tính chất&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\det(\mathbf{A}) \neq 0\): ma trận khả nghịch.&lt;/li&gt;
  &lt;li&gt;\(\det(\mathbf{A}) = 0\): ma trận suy biến (không khả nghịch).&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;det_A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;det&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;det(A) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;det_A&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ma trận singular
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;singular&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                     &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;det_singular&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;det&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;singular&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;det(singular) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;det_singular&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ≈ 0
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;video-ngắn-đại-số-tuyến-tính-ma-trận-là-phép-biến-đổi-không-gian&quot;&gt;Video ngắn: Đại số Tuyến tính: Ma trận là Phép biến đổi Không gian&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-08a-matrix-linear-transform.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 8 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): kéo dãn &amp;amp; trượt lưới tọa độ bằng ma trận A, định thức det(A), hồi quy đa biến y = Xβ + ε và đa cộng tuyến.&lt;/p&gt;

&lt;h2 id=&quot;3-hệ-phương-trình-tuyến-tính&quot;&gt;3. Hệ Phương trình Tuyến tính&lt;/h2&gt;

&lt;p&gt;Xét hệ phương trình tuyến tính:&lt;/p&gt;

\[\begin{cases}
a_{11}x_1 + a_{12}x_2 + \cdots + a_{1n}x_n = b_1 \\
a_{21}x_1 + a_{22}x_2 + \cdots + a_{2n}x_n = b_2 \\
\vdots \\
a_{m1}x_1 + a_{m2}x_2 + \cdots + a_{mn}x_n = b_m
\end{cases}\]

&lt;p&gt;&lt;strong&gt;Dạng ma trận&lt;/strong&gt;: \(\mathbf{Ax} = \mathbf{b}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nghiệm&lt;/strong&gt; (khi \(\mathbf{A}\) vuông và khả nghịch): \(\mathbf{x} = \mathbf{A}^{-1}\mathbf{b}\). Trong tính toán số, nên dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.linalg.solve&lt;/code&gt; thay vì tính trực tiếp ma trận nghịch đảo để nhanh và ổn định hơn.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Hệ phương trình:
# 2x + 3y = 8
# 5x + 4y = 13
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Giải bằng nghịch đảo
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nghiệm (dùng inv): x = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Giải bằng solve (hiệu quả hơn)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_solve&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;solve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nghiệm (dùng solve): x = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_solve&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kiểm tra Ax = b: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;4-trị-riêng-và-vector-riêng-eigenvalues-và-eigenvectors&quot;&gt;4. Trị riêng và Vector riêng (Eigenvalues và Eigenvectors)&lt;/h2&gt;

&lt;p&gt;Cho ma trận vuông \(\mathbf{A}\), nếu tồn tại số \(\lambda\) và vector khác không \(\mathbf{v}\) sao cho:&lt;/p&gt;

\[\mathbf{A}\mathbf{v} = \lambda \mathbf{v}\]

&lt;p&gt;thì \(\lambda\) được gọi là &lt;strong&gt;trị riêng (eigenvalue)&lt;/strong&gt; và \(\mathbf{v}\) là &lt;strong&gt;vector riêng (eigenvector)&lt;/strong&gt; tương ứng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ý nghĩa hình học&lt;/strong&gt;: khi chịu phép biến đổi tuyến tính \(\mathbf{A}\), vector \(\mathbf{v}\) không đổi phương mà chỉ bị co giãn theo hệ số \(\lambda\).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tính eigenvalues và eigenvectors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvalues&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eigenvectors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Eigenvalues:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvalues&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Eigenvectors:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvectors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvalues&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambda_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eigenvalues&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eigenvectors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;Av&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambda_v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Eigenvalue &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: λ = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Av = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Av&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;λv = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_v&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Khớp? &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Av&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-ứng-dụng-trong-thống-kê&quot;&gt;5. Ứng dụng trong Thống kê&lt;/h2&gt;

&lt;h3 id=&quot;51-ma-trận-hiệp-phương-sai-covariance-matrix&quot;&gt;5.1. Ma trận Hiệp phương sai (Covariance Matrix)&lt;/h3&gt;

&lt;p&gt;Với ma trận dữ liệu \(\mathbf{X}\) kích thước \(n \times p\) đã được căn tâm (trừ đi trung bình từng cột), ma trận hiệp phương sai mẫu được tính bằng:&lt;/p&gt;

\[\mathbf{\Sigma} = \frac{1}{n-1} \mathbf{X}^T \mathbf{X}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Tạo dữ liệu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;multivariate_normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tính covariance matrix
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cov_matrix&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cov&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Covariance Matrix:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cov_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Trực quan hóa
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Scatter plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;X₁&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;X₂&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dữ liệu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_aspect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Covariance matrix heatmap
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seaborn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;heatmap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cov_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;annot&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;coolwarm&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
           &lt;span class=&quot;n&quot;&gt;square&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Covariance Matrix&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;video-ngắn-trị-riêng-vector-riêng--đám-mây-hiệp-phương-sai-σ&quot;&gt;Video ngắn: Trị riêng, Vector riêng &amp;amp; Đám mây Hiệp phương sai Σ&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-08b-eigen-covariance-ellipse.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 8 giây (bản hình ảnh trước, sẽ bổ sung thuyết minh): hai trục chính của elip hậu nghiệm 2D, tỷ số điều kiện ảnh hưởng tốc độ MCMC, phân rã Cholesky và mẹo chuẩn hóa biến.&lt;/p&gt;

&lt;h3 id=&quot;52-hồi-quy-tuyến-tính-linear-regression&quot;&gt;5.2. Hồi quy Tuyến tính (Linear Regression)&lt;/h3&gt;

&lt;p&gt;Xét mô hình \(\mathbf{y} = \mathbf{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}\). &lt;strong&gt;Nghiệm bình phương tối thiểu thông thường (OLS — Ordinary Least Squares)&lt;/strong&gt; là:&lt;/p&gt;

\[\hat{\boldsymbol{\beta}} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Tạo dữ liệu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;true_beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Thêm intercept
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_with_intercept&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;column_stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tính beta
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_with_intercept&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_with_intercept&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_with_intercept&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True beta:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Estimated beta:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Bỏ intercept
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Intercept:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Predictions
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_with_intercept&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Linear Regression: True vs Predicted&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# R-squared
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ss_res&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ss_tot&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;r_squared&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ss_res&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ss_tot&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;R² = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r_squared&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;6-tóm-tắt-công-thức-quan-trọng&quot;&gt;6. Tóm tắt Công thức Quan trọng&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Phép toán&lt;/th&gt;
      &lt;th&gt;Ký hiệu&lt;/th&gt;
      &lt;th&gt;Công thức&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Tích vô hướng (Dot product)&lt;/td&gt;
      &lt;td&gt;\(\mathbf{x} \cdot \mathbf{y}\)&lt;/td&gt;
      &lt;td&gt;\(\sum_{i=1}^{n} x_i y_i\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Chuẩn (Norm)&lt;/td&gt;
      &lt;td&gt;\(|\mathbf{x}|\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{\sum_{i=1}^{n} x_i^2}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Nhân ma trận&lt;/td&gt;
      &lt;td&gt;\(\mathbf{AB}\)&lt;/td&gt;
      &lt;td&gt;\(c_{ij} = \sum_{k} a_{ik}b_{kj}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Chuyển vị (Transpose)&lt;/td&gt;
      &lt;td&gt;\(\mathbf{A}^T\)&lt;/td&gt;
      &lt;td&gt;\((\mathbf{A}^T)_{ij} = a_{ji}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Nghịch đảo (Inverse)&lt;/td&gt;
      &lt;td&gt;\(\mathbf{A}^{-1}\)&lt;/td&gt;
      &lt;td&gt;\(\mathbf{AA}^{-1} = \mathbf{I}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Định thức (Determinant)&lt;/td&gt;
      &lt;td&gt;\(\det(\mathbf{A})\)&lt;/td&gt;
      &lt;td&gt;Giá trị vô hướng&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Trị riêng (Eigenvalue)&lt;/td&gt;
      &lt;td&gt;\(\lambda\)&lt;/td&gt;
      &lt;td&gt;\(\mathbf{Av} = \lambda\mathbf{v}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;giải-thích-hình-học-của-ma-trận-hiệp-phương-sai-và-hồi-quy-bayes-tính-tay-22&quot;&gt;Giải thích: Hình học của ma trận hiệp phương sai và Hồi quy Bayes tính tay 2×2&lt;/h2&gt;

&lt;p&gt;Tại sao trị riêng của \(\boldsymbol{\Sigma}\) lại quan trọng đến vậy trong thống kê Bayes? Hãy đi chậm qua 4 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Dạng toàn phương (Quadratic Form):&lt;/strong&gt; Trong mật độ Chuẩn đa biến \(\exp\bigl(-\frac{1}{2}(\mathbf{x}-\boldsymbol{\mu})^T\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu})\bigr)\), các đường đồng mức xác suất là những &lt;strong&gt;hình elip&lt;/strong&gt; (hoặc ellipsoid nhiều chiều).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hướng và bán trục của elip:&lt;/strong&gt; Các vector riêng của \(\boldsymbol{\Sigma}\) chỉ phương các trục chính của elip, còn căn bậc hai trị riêng \(\sqrt{\lambda_i}\) chính là độ dài bán trục (độ lệch chuẩn dọc theo phương đó).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Số điều kiện (Condition Number):&lt;/strong&gt; Tỷ số \(\lambda_{\max}/\lambda_{\min}\) càng lớn thì elip hậu nghiệm càng dẹt như điếu xì gà — khiến bộ lấy mẫu Metropolis–Hastings nhảy bước đều bị kẹt (hoặc bước quá lớn đụng tường, hoặc bước quá nhỏ đi mãi không tới).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cộng độ chính xác ở dạng ma trận:&lt;/strong&gt; Cập nhật Normal–Normal đa biến hoàn toàn tương tự 1 chiều, chỉ thay số vô hướng bằng ma trận: \(\boldsymbol{\Lambda}_{\text{post}} = \boldsymbol{\Lambda}_0 + \frac{1}{\sigma^2}\mathbf{X}^T\mathbf{X}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-giải-trị-riêng-ma-trận-hiệp-phương-sai-22-và-cập-nhật-ridgebayes&quot;&gt;Ví dụ tính toán làm từng bước: Giải trị riêng ma trận hiệp phương sai 2×2 và cập nhật Ridge–Bayes&lt;/h3&gt;

&lt;p&gt;Xét hai tham số \((\beta_1, \beta_2)\) có ma trận hiệp phương sai hậu nghiệm:
\(\boldsymbol{\Sigma} = \begin{pmatrix} 5 &amp;amp; 3 \ 3 &amp;amp; 5 \end{pmatrix}.\)&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Tìm trị riêng từ phương trình đặc trưng \(\det(\boldsymbol{\Sigma} - \lambda \mathbf{I}) = 0\):&lt;/strong&gt;
\((5 - \lambda)^2 - 9 = 0 \implies 5 - \lambda = \pm 3 \implies \lambda_1 = 8,\quad \lambda_2 = 2.\)
Vì cả hai trị riêng đều dương, \(\boldsymbol{\Sigma}\) là ma trận xác định dương hợp lệ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Tìm vector riêng đơn vị và ý nghĩa hình học:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Với \(\lambda_1 = 8\): \((-3)v_1 + 3v_2 = 0 \implies \mathbf{u}_1 = \frac{1}{\sqrt{2}}\begin{pmatrix}1 \ 1\end{pmatrix}\). Độ lệch chuẩn dọc trục chéo này là \(\sqrt{8} \approx 2.83\).&lt;/li&gt;
      &lt;li&gt;Với \(\lambda_2 = 2\): \(3v_1 + 3v_2 = 0 \implies \mathbf{u}_2 = \frac{1}{\sqrt{2}}\begin{pmatrix}1 \ -1\end{pmatrix}\). Độ lệch chuẩn dọc trục vuông góc chỉ là \(\sqrt{2} \approx 1.41\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Tính hệ số tương quan để đối chiếu:&lt;/strong&gt;
\(ho = \frac{\Sigma_{12}}{\sqrt{\Sigma_{11}\Sigma_{22}}} = \frac{3}{\sqrt{5 \times 5}} = \frac{3}{5} = 0.60.\)
Đám mây hậu nghiệm nghiêng \(45^\circ\), dài gấp \(\sqrt{8/2} = 2\) lần bề ngang.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Tính nghịch đảo tường minh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.linalg.inv(A) @ b&lt;/code&gt; trong mã thực tế; cách chuẩn về mặt số học là giải hệ tuyến tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.linalg.solve(A, b)&lt;/code&gt; hoặc phân rã Cholesky để tránh khuếch đại sai số làm tròn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Định thức \(\det(\boldsymbol{\Sigma}) = 5 \times 5 - 3 \times 3 = 16\), khớp hoàn toàn với tích hai trị riêng \(\lambda_1 \lambda_2 = 8 \times 2 = 16\); vết \(\text{tr}(\boldsymbol{\Sigma}) = 5 + 5 = 10\), khớp với tổng \(\lambda_1 + \lambda_2 = 8 + 2 = 10\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Vectors&lt;/td&gt;
          &lt;td&gt;Chapter 1, Essence of linear algebra](https://www.youtube.com/watch?v=fNk_zzaMoSs) — 3Blue1Brown, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giúp hình dung vector như đối tượng hình học trước khi dùng để biểu diễn dữ liệu và tham số.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Matrix multiplication as composition&lt;/td&gt;
          &lt;td&gt;Chapter 4, Essence of linear algebra](https://www.youtube.com/watch?v=XkY2DOUCWMU) — 3Blue1Brown, English. Giải thích phép nhân ma trận như phép hợp các biến đổi tuyến tính, gắn với cách viết mô hình hồi quy.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Eigenvectors and eigenvalues&lt;/td&gt;
          &lt;td&gt;Chapter 14, Essence of linear algebra](https://www.youtube.com/watch?v=PFDu9oVAE-g) — 3Blue1Brown, English. Trình bày trực quan về trị riêng và vector riêng để hiểu cấu trúc hình học của ma trận.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Vectors&lt;/strong&gt;: Cho \(\mathbf{v} = [2, 3, -1]\) và \(\mathbf{w} = [1, -2, 4]\). Tính:
    &lt;ul&gt;
      &lt;li&gt;
\[\mathbf{v} + \mathbf{w}\]
      &lt;/li&gt;
      &lt;li&gt;
\[\mathbf{v} \cdot \mathbf{w}\]
      &lt;/li&gt;
      &lt;li&gt;
\[\|\mathbf{v}\|\]
      &lt;/li&gt;
      &lt;li&gt;Góc giữa \(\mathbf{v}\) và \(\mathbf{w}\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ma trận&lt;/strong&gt;: Cho \(\mathbf{A} = \begin{bmatrix} 1 &amp;amp; 2 \\ 3 &amp;amp; 4 \end{bmatrix}\) và \(\mathbf{B} = \begin{bmatrix} 5 &amp;amp; 6 \\ 7 &amp;amp; 8 \end{bmatrix}\). Tính:
    &lt;ul&gt;
      &lt;li&gt;
\[\mathbf{A} + \mathbf{B}\]
      &lt;/li&gt;
      &lt;li&gt;
\[\mathbf{AB}\]
      &lt;/li&gt;
      &lt;li&gt;
\[\mathbf{A}^T\]
      &lt;/li&gt;
      &lt;li&gt;
\[\mathbf{A}^{-1}\]
      &lt;/li&gt;
      &lt;li&gt;
\[\det(\mathbf{A})\]
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hệ phương trình&lt;/strong&gt;: Giải hệ:
\(\begin{cases} 3x + 2y = 7 \\ x - y = 1 \end{cases}\)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Trị riêng và vector riêng&lt;/strong&gt;: Tìm trị riêng và vector riêng của \(\mathbf{A} = \begin{bmatrix} 3 &amp;amp; 1 \\ 1 &amp;amp; 3 \end{bmatrix}\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hồi quy tuyến tính&lt;/strong&gt;: Sinh 100 quan sát theo mô hình \(y = 3x_1 - 2x_2 + \epsilon\) rồi ước lượng \(\boldsymbol{\beta}\) bằng công thức OLS.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Strang, G. (2016).&lt;/strong&gt; &lt;em&gt;Introduction to Linear Algebra&lt;/em&gt;. Wellesley-Cambridge Press.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;3Blue1Brown - Essence of Linear Algebra&lt;/strong&gt; - https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;NumPy Linear Algebra&lt;/strong&gt; - https://numpy.org/doc/stable/reference/routines.linalg.html&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_06_calculus_basics/&quot;&gt;0.9 Giải tích Cơ bản&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.7: Python Cơ bản cho Data Science</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_04_python_basics/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_04_python_basics</id>
   <content type="html">&lt;p&gt;Trong suốt thế kỷ 19 và phần lớn thế kỷ 20, thống kê Bayes bị xem là “đẹp về triết lý nhưng bất khả thi về tính toán”, bởi chỉ cần mô hình có hơn vài tham số không liên hợp, tích phân ở mẫu số định lý Bayes trở nên không thể giải bằng giấy bút. Mọi thứ đảo chiều khi máy tính cá nhân và các thư viện tính toán khoa học như NumPy, SciPy và PyMC xuất hiện: phép tích phân 100 chiều nay có thể được xấp xỉ trong vài giây bằng mã Python.&lt;/p&gt;

&lt;p&gt;Bài này không chỉ ôn lại cú pháp Python, mà đặt nền móng cho tư duy &lt;strong&gt;lập trình xác suất (probabilistic programming)&lt;/strong&gt; — nơi mỗi hàm toán học như prior, likelihood và log-posterior trở thành các phép toán vector hóa sạch sẽ và tái lập được.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ nắm nền tảng Python cần thiết cho toàn bộ quy trình phân tích Bayesian trong khóa học: chuẩn bị dữ liệu, tính toán số học, trực quan hóa và viết các đoạn mã có thể tái lập. Trọng tâm của bài không phải học thuộc cú pháp rời rạc, mà là hiểu cách chuyển một mô hình sinh dữ liệu thành các phép tính kiểm chứng được bằng mã nguồn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-tính-toán-vector-hóa-mô-phỏng-monte-carlo-và-hệ-sinh-thái-bayes-trong-python&quot;&gt;Kiến thức cần nhớ: Tính toán vector hóa, Mô phỏng Monte Carlo và Hệ sinh thái Bayes trong Python&lt;/h2&gt;

&lt;p&gt;Để dùng Python hiệu quả cho thống kê Bayes ở trình độ đại học, hãy nắm rõ ba trụ cột kỹ thuật:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tính toán mảng vector hóa (NumPy &amp;amp; Broadcasting):&lt;/strong&gt; Thay vì viết vòng lặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt; chậm chạp trong Python thuần, ta biểu diễn lưới tham số \(\theta\) và tập dữ liệu \(y\) dưới dạng mảng đa chiều. Một phép tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log_lik = (y * np.log(p) + (1 - y) * np.log(1 - p)).sum(axis=-1)&lt;/code&gt; chạy nhanh gấp hàng trăm lần vì được thực thi bằng mã C biên dịch sẵn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lập trình khoa học &amp;amp; Trực quan hóa (SciPy, Pandas, Matplotlib):&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats&lt;/code&gt; cung cấp sẵn PDF, PMF, CDF, PPF và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;logpdf&lt;/code&gt; cho mọi phân phối xác suất chuẩn; Pandas quản lý dữ liệu bảng sạch sẽ; còn Matplotlib/ArviZ giúp kiểm tra trực quan đường cong posterior và dấu vết chuỗi MCMC (&lt;em&gt;trace plots&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Thuật toán Bayes (Grid, MCMC, VI):&lt;/strong&gt; Khi bạn nắm vững mảng NumPy, sinh số ngẫu nhiên có kiểm soát &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.random.default_rng(seed)&lt;/code&gt; và tính toán trên thang log, bạn đã có đủ 90% kỹ năng lập trình để tự viết bộ xấp xỉ lưới (&lt;em&gt;Grid Approximation&lt;/em&gt;), thuật toán &lt;em&gt;Metropolis–Hastings&lt;/em&gt;, hay chạy các mô hình thực tế bằng PyMC / Stan.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-python-như-ngôn-ngữ-thực-thi-mô-hình&quot;&gt;Giới thiệu: Python như ngôn ngữ thực thi mô hình&lt;/h2&gt;

&lt;p&gt;Trong phân tích Bayesian, mô hình không dừng ở công thức trên giấy. Mọi giả định về dữ liệu và tham số đều cần được hiện thực hóa thành các bước tính toán cụ thể: tạo biến, biến đổi dữ liệu, mô phỏng và kiểm tra kết quả. Nếu toán học cung cấp cấu trúc suy luận, thì Python là lớp thực thi giúp suy luận đó chạy được, lặp lại được và chia sẻ được.&lt;/p&gt;

&lt;p&gt;Bài học đi theo mạch từ cơ bản đến ứng dụng: bắt đầu bằng cấu trúc dữ liệu và điều khiển luồng trong Python, rồi chuyển sang NumPy, Pandas và Matplotlib — ba thư viện cốt lõi cho tiền xử lý và khám phá dữ liệu trước khi xây dựng mô hình xác suất. Hãy đọc bài theo hướng “mục đích phân tích -&amp;gt; công cụ lập trình” thay vì coi đây là danh sách câu lệnh đơn thuần.&lt;/p&gt;

&lt;h2 id=&quot;nguyên-tắc-thực-hành-trong-khóa-học-bayesian&quot;&gt;Nguyên tắc thực hành trong khóa học Bayesian&lt;/h2&gt;

&lt;p&gt;Ở các chương tiếp theo, phần lớn bài toán sẽ đi theo quy trình:&lt;/p&gt;

\[\text{data} \rightarrow \text{cleaning/transform} \rightarrow \text{modeling} \rightarrow \text{diagnostics} \rightarrow \text{interpretation}.\]

&lt;p&gt;Do đó, ngay từ Chương 0, ta ưu tiên ba nguyên tắc khi viết mã Python:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Khả năng tái lập (reproducibility)&lt;/strong&gt;: cố định seed khi mô phỏng ngẫu nhiên và ghi rõ nguồn dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính minh bạch (transparency)&lt;/strong&gt;: mỗi bước biến đổi dữ liệu phải rõ ràng, dễ đọc và dễ giải thích bằng lời.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khả năng diễn giải (interpretability)&lt;/strong&gt;: trực quan hóa nhằm kiểm tra giả định và phát hiện sai lệch của mô hình, không chỉ để trang trí.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;1-python-cơ-bản&quot;&gt;1. Python Cơ bản&lt;/h2&gt;

&lt;h3 id=&quot;11-biến-và-kiểu-dữ-liệu&quot;&gt;1.1. Biến và Kiểu dữ liệu&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Số
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# int
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;3.14&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# float
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;3j&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# complex
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Chuỗi
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bayesian&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;message&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Statistics&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Boolean
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;is_false&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra kiểu
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# &amp;lt;class &apos;int&apos;&amp;gt;
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# &amp;lt;class &apos;str&apos;&amp;gt;
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Chuyển đổi kiểu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 5.0
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_int&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;12-lists-tuples-dictionaries&quot;&gt;1.2. Lists, Tuples, Dictionaries&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# List (có thể thay đổi)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;mixed&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;two&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Truy cập
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1 (index bắt đầu từ 0)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 5 (index âm: từ cuối)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [2, 3, 4] (slicing)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Thêm/xóa
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Thêm vào cuối
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;insert&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Thêm vào vị trí
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;remove&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Xóa giá trị 3
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;popped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Xóa và trả về phần tử cuối
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Tuple (không thể thay đổi)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coordinates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# coordinates[0] = 15  # Lỗi!
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Dictionary (key-value pairs)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;person&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;city&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Hanoi&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# &apos;Alice&apos;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;26&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cập nhật
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;email&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alice@email.com&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Thêm mới
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Lặp qua dictionary
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;13-vòng-lặp-và-điều-kiện&quot;&gt;1.3. Vòng lặp và Điều kiện&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# If-else
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Positive&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Negative&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Zero&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# For loop
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 0, 1, 2, 3, 4
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# While loop
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# List comprehension (quan trọng!)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;squares&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;evens&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;14-functions&quot;&gt;1.4. Functions&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Định nghĩa function
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Hello, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Function với default arguments
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;power&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;power&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 9 (n=2 mặc định)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;power&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 27
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Multiple return values
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Lambda functions (anonymous)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;square&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;square&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 25
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Map, filter
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;squared&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;evens&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;filter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;2-numpy---tính-toán-số-học&quot;&gt;2. NumPy - Tính toán Số học&lt;/h2&gt;

&lt;h3 id=&quot;21-arrays&quot;&gt;2.1. Arrays&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo arrays
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (5,)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 3)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# int64
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Tạo arrays đặc biệt
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;zeros&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Ma trận 3x4 toàn 0
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ones&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Ma trận 2x3 toàn 1
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Ma trận đơn vị 4x4
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Random [0, 1)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;22-indexing-và-slicing&quot;&gt;2.2. Indexing và Slicing&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Indexing
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 0
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 9
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Slicing
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [2, 3, 4]
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [0, 1, 2]
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [5, 6, 7, 8, 9]
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[::&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [0, 2, 4, 6, 8] (bước nhảy 2)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 2D arrays
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [4, 5, 6] (hàng 1)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [2, 5, 8] (cột 1)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Boolean indexing
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [6, 7, 8, 9]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;23-phép-toán&quot;&gt;2.3. Phép toán&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;40&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Element-wise operations
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [11, 22, 33, 44]
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [10, 40, 90, 160]
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [1, 4, 9, 16]
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Broadcasting
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cộng 10 vào mọi phần tử
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Aggregations
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 10
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2.5
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1.118...
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1, 4
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Axis operations
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [5, 7, 9] (sum theo cột)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [6, 15] (sum theo hàng)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;24-các-hàm-quan-trọng&quot;&gt;2.4. Các hàm quan trọng&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Random
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Reproducibility
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random_normal&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Normal(0, 1)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random_uniform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Uniform[0, 10]
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Linear algebra
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Nhân ma trận
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cách khác
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Ma trận nghịch đảo
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;det&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Định thức
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Reshape
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [0, 1, ..., 11]
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Ma trận 3x4
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Về 1D
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Stack
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;vstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Vertical stack
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Horizontal stack
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;video-ngắn-python--vector-hóa-numpy-cho-suy-diễn-bayes&quot;&gt;Video ngắn: Python &amp;amp; Vector hóa NumPy cho Suy diễn Bayes&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-07a-numpy-vectorization.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 8 giây: so sánh vòng lặp Python với vector hóa NumPy, giải Grid Approximation Bayes trong 4 dòng code, cơ chế Broadcasting, Random Seed và hệ sinh thái PyMC/ArviZ.&lt;/p&gt;

&lt;h2 id=&quot;3-pandas---xử-lý-dữ-liệu&quot;&gt;3. Pandas - Xử lý Dữ liệu&lt;/h2&gt;

&lt;h3 id=&quot;31-series-và-dataframe&quot;&gt;3.1. Series và DataFrame&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pandas&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Series (1D)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Series&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;s_named&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Series&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;index&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s_named&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 10
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# DataFrame (2D)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bob&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Charlie&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;35&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;City&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Hanoi&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;HCMC&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Danang&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;32-đọcghi-dữ-liệu&quot;&gt;3.2. Đọc/Ghi Dữ liệu&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Đọc CSV
# df = pd.read_csv(&apos;data.csv&apos;)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Ghi CSV
# df.to_csv(&apos;output.csv&apos;, index=False)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Đọc Excel
# df = pd.read_excel(&apos;data.xlsx&apos;)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Từ dictionary
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;33-truy-cập-dữ-liệu&quot;&gt;3.3. Truy cập Dữ liệu&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bob&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Charlie&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;David&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;35&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;85&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;90&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;78&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;92&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Truy cập cột
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cách khác
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Truy cập nhiều cột
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Truy cập hàng bằng index
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iloc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Hàng đầu tiên
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iloc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Hàng 1-2
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Truy cập bằng label
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_indexed&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_index&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_indexed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Boolean indexing
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;80&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;34-xử-lý-dữ-liệu&quot;&gt;3.4. Xử lý Dữ liệu&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Thêm cột
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Grade&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age_squared&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Xóa cột
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_dropped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;drop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age_squared&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sắp xếp
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_sorted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sort_values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ascending&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Group by
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grouped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;groupby&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Grade&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grouped&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Apply function
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age_category&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;apply&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Young&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Old&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Missing values
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_with_nan&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df_with_nan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nan&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_with_nan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;isnull&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Đếm NaN
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_filled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df_with_nan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fillna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Fill NaN
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_dropped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df_with_nan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Drop NaN
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;35-merge-và-join&quot;&gt;3.5. Merge và Join&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Merge
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ID&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bob&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Charlie&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;df2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ID&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;85&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;90&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;78&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;merged&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;on&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ID&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;how&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;inner&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# inner, left, right, outer
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;merged&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Concat
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_concat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;concat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Vertical
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;4-matplotlib---trực-quan-hóa&quot;&gt;4. Matplotlib - Trực quan hóa&lt;/h2&gt;

&lt;h3 id=&quot;41-plots-cơ-bản&quot;&gt;4.1. Plots Cơ bản&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Line plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sin(x)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;cos(x)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trigonometric Functions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Scatter plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Scatter Plot&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Histogram
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Value&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Frequency&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Histogram&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;42-subplots&quot;&gt;4.2. Subplots&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot 1
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Line Plot&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot 2
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Scatter Plot&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot 3
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Histogram&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot 4
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;boxplot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Box Plot&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;43-tùy-chỉnh&quot;&gt;4.3. Tùy chỉnh&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Nhiều styles
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Red solid&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Blue dashed&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;go&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;markersize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Green dots&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Colors: &apos;r&apos;, &apos;g&apos;, &apos;b&apos;, &apos;c&apos;, &apos;m&apos;, &apos;y&apos;, &apos;k&apos;, &apos;w&apos;
# Linestyles: &apos;-&apos;, &apos;--&apos;, &apos;-.&apos;, &apos;:&apos;
# Markers: &apos;o&apos;, &apos;s&apos;, &apos;^&apos;, &apos;*&apos;, &apos;+&apos;, &apos;x&apos;
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;X axis&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Y axis&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Customized Plot&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;best&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-ví-dụ-tổng-hợp&quot;&gt;5. Ví dụ Tổng hợp&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Tạo và phân tích dữ liệu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sinh dữ liệu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;170&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;M&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Thêm BMI
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Thống kê mô tả
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=== Thống kê Mô tả ===&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;describe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=== Theo Gender ===&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;groupby&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Trực quan hóa
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Histogram
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height (cm)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Frequency&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Distribution of Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Scatter
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gender&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;M&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gender&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; 
                      &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                      &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gender&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height (cm)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight (kg)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height vs Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Box plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;boxplot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;column&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;by&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI by Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Correlation heatmap
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seaborn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;corr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;corr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;heatmap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;annot&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;coolwarm&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Correlation Matrix&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;video-ngắn-mô-phỏng-monte-carlo-trong-python-đổi-tích-phân-thành-lấy-mẫu&quot;&gt;Video ngắn: Mô phỏng Monte Carlo trong Python: Đổi Tích phân thành Lấy mẫu&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-07b-python-monte-carlo.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 3 giây: ném điểm ước lượng π, biểu đồ hội tụ theo 1/√N, tính kỳ vọng hậu nghiệm và dự báo hậu nghiệm, vượt qua lời nguyền số chiều và kiểm soát MCSE.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-từ-công-thức-bayes-trên-giấy-sang-5-dòng-vector-hóa-numpy&quot;&gt;Giải thích: Từ công thức Bayes trên giấy sang 5 dòng vector hóa NumPy&lt;/h2&gt;

&lt;p&gt;Nhiều người học biết công thức Bayes nhưng khi viết mã lại vướng ở hai chỗ: lỗi tràn số (&lt;em&gt;underflow&lt;/em&gt;) và vòng lặp lồng nhau. Hãy đọc chậm luồng chuyển đổi chuẩn mực sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Rời rạc hóa hoặc lấy mẫu tham số:&lt;/strong&gt; Tạo một mảng 1D &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;theta&lt;/code&gt; gồm \(M\) giá trị ứng viên trên miền tham số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Làm việc trên thang logarit:&lt;/strong&gt; Thay vì nhân trực tiếp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prior * likelihood&lt;/code&gt; (dễ về &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt; khi \(n\) lớn), ta cộng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log_unnorm = log_prior + log_lik&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ổn định số bằng phép trừ cực đại (Log-Sum-Exp trick):&lt;/strong&gt; Trừ đi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.max(log_unnorm)&lt;/code&gt; trước khi lấy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.exp(...)&lt;/code&gt; để giá trị lớn nhất luôn là \(e^0 = 1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa thành phân phối hậu nghiệm:&lt;/strong&gt; Chia cho tổng diện tích (hoặc tổng trọng số trên lưới) để thu được &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;posterior&lt;/code&gt; có tổng bằng 1.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-mô-phỏng-5-điểm-lưới-của-bài-toán-tung-xu-tự-kiểm-tra-được-từng-số&quot;&gt;Ví dụ tính toán làm từng bước: Mô phỏng 5 điểm lưới của bài toán tung xu (tự kiểm tra được từng số)&lt;/h3&gt;

&lt;p&gt;Giả sử bạn tung đồng xu \(n = 2\) lần và được \(k = 2\) mặt ngửa. Ta dùng prior đều trên lưới thô 5 điểm \(\theta \in \{0.0, 0.25, 0.50, 0.75, 1.0\}\) (mỗi điểm có prior \(1/5 = 0.2\)). Hãy tự tính tay bảng sau trước khi chạy trong NumPy:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Điểm lưới \(\theta\)&lt;/th&gt;
      &lt;th&gt;Prior \(p(\theta)\)&lt;/th&gt;
      &lt;th&gt;Likelihood \(\theta^2\)&lt;/th&gt;
      &lt;th&gt;Tích chưa chuẩn hóa \(u(\theta)\)&lt;/th&gt;
      &lt;th&gt;Hậu nghiệm \(p(\theta \mid k=2)\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(0.00\)&lt;/td&gt;
      &lt;td&gt;\(0.20\)&lt;/td&gt;
      &lt;td&gt;\(0.0000\)&lt;/td&gt;
      &lt;td&gt;\(0.0000\)&lt;/td&gt;
      &lt;td&gt;\(0.0000 / 0.3750 = 0.000\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(0.25\)&lt;/td&gt;
      &lt;td&gt;\(0.20\)&lt;/td&gt;
      &lt;td&gt;\(0.0625\)&lt;/td&gt;
      &lt;td&gt;\(0.0125\)&lt;/td&gt;
      &lt;td&gt;\(0.0125 / 0.3750 = 0.033\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(0.50\)&lt;/td&gt;
      &lt;td&gt;\(0.20\)&lt;/td&gt;
      &lt;td&gt;\(0.2500\)&lt;/td&gt;
      &lt;td&gt;\(0.0500\)&lt;/td&gt;
      &lt;td&gt;\(0.0500 / 0.3750 = 0.133\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(0.75\)&lt;/td&gt;
      &lt;td&gt;\(0.20\)&lt;/td&gt;
      &lt;td&gt;\(0.5625\)&lt;/td&gt;
      &lt;td&gt;\(0.1125\)&lt;/td&gt;
      &lt;td&gt;\(0.1125 / 0.3750 = 0.300\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(1.00\)&lt;/td&gt;
      &lt;td&gt;\(0.20\)&lt;/td&gt;
      &lt;td&gt;\(1.0000\)&lt;/td&gt;
      &lt;td&gt;\(0.2000\)&lt;/td&gt;
      &lt;td&gt;\(0.2000 / 0.3750 = 0.533\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Tổng cột chưa chuẩn hóa: \(0 + 0.0125 + 0.05 + 0.1125 + 0.20 = 0.3750\).
Kỳ vọng hậu nghiệm tính bằng tích vô hướng (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.sum(theta * posterior)&lt;/code&gt;):
\(0(0) + 0.25(0.0333) + 0.50(0.1333) + 0.75(0.3000) + 1.00(0.5333) = 0.0083 + 0.0667 + 0.2250 + 0.5333 \approx 0.8333.\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Quên đặt hạt giống ngẫu nhiên (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seed&lt;/code&gt;) khi mô phỏng Monte Carlo khiến mỗi lần chạy ra kết quả khác nhau và không thể gỡ lỗi.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu tăng lưới lên 1.000 điểm trên \([0, 1]\), trung bình hậu nghiệm sẽ hội tụ về đúng giá trị giải tích của \(\text{Beta}(1+2, 1+0) = \text{Beta}(3, 1)\), tức là \(\frac{3}{3+1} = 0.75\) (lưới 5 điểm bị lệch lên \(0.833\) do hai đầu mút thô).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jZ952vChhuI&quot;&gt;Quick introduction to Jupyter Notebook&lt;/a&gt; — Michael Fudge, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giới thiệu cách Jupyter Notebook kết hợp mã nguồn, kết quả chạy và ghi chú trong cùng một tệp dễ tái lập.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=lLRBYKwP8GQ&quot;&gt;Ultimate Guide to NumPy Arrays - VERY DETAILED TUTORIAL for beginners!&lt;/a&gt; — Python Simplified, English. Trình bày mảng NumPy và các phép tính vector hóa phục vụ mô phỏng và biến đổi dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2uvysYbKdjM&quot;&gt;Complete Python Pandas Data Science Tutorial! (2025 Updated Edition)&lt;/a&gt; — Keith Galli, English. Hướng dẫn nạp, lọc và chuẩn bị dữ liệu dạng bảng bằng Pandas trước khi đưa vào mô hình.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lists và vòng lặp&lt;/strong&gt;: Tạo danh sách các số nguyên từ 1 đến 100, rồi tính riêng tổng các số chẵn và tổng các số lẻ.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hàm (Functions)&lt;/strong&gt;: Viết hàm tính trung bình (mean), trung vị (median) và độ lệch chuẩn (std) cho một danh sách số.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;NumPy&lt;/strong&gt;: Tạo một ma trận ngẫu nhiên kích thước 5×5, sau đó tính giá trị trung bình theo từng hàng và theo từng cột.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pandas&lt;/strong&gt;: Tạo DataFrame gồm 100 người với các cột &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;name&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;age&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;score&lt;/code&gt; và thực hiện:
    &lt;ul&gt;
      &lt;li&gt;Lọc những người có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;age &amp;gt; 25&lt;/code&gt;.&lt;/li&gt;
      &lt;li&gt;Tính điểm trung bình theo từng nhóm tuổi (18–30, 31–40, 41+).&lt;/li&gt;
      &lt;li&gt;Sắp xếp bảng theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;score&lt;/code&gt; giảm dần.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trực quan hóa&lt;/strong&gt;: Sinh dữ liệu gồm 2 biến có tương quan và vẽ:
    &lt;ul&gt;
      &lt;li&gt;Biểu đồ phân tán (scatter plot) kèm đường hồi quy.&lt;/li&gt;
      &lt;li&gt;Biểu đồ tần suất (histogram) của từng biến.&lt;/li&gt;
      &lt;li&gt;Biểu đồ hộp (box plot) so sánh hai biến.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Python Documentation&lt;/strong&gt; - https://docs.python.org/3/&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;NumPy Documentation&lt;/strong&gt; - https://numpy.org/doc/&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pandas Documentation&lt;/strong&gt; - https://pandas.pydata.org/docs/&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Matplotlib Documentation&lt;/strong&gt; - https://matplotlib.org/stable/contents.html&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Real Python Tutorials&lt;/strong&gt; - https://realpython.com/&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_05_linear_algebra/&quot;&gt;0.8 Đại số Tuyến tính Cơ bản&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.6: Thống kê Mô tả - Ngôn ngữ Đầu tiên của Dữ liệu</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_03_descriptive_statistics/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_03_descriptive_statistics</id>
   <content type="html">&lt;p&gt;Năm 1973, nhà thống kê Francis Anscombe công bố bốn bộ dữ liệu kỳ lạ mà sau này được gọi là &lt;em&gt;Bộ tứ Anscombe&lt;/em&gt;: cả bốn bộ đều có trung bình \(x\) bằng 9, trung bình \(y\) bằng 7.50, phương sai giống hệt nhau và hệ số tương quan cùng bằng \(0.816\) — nhưng khi vẽ lên đồ thị, một bộ là đường thẳng, một bộ là parabol, một bộ có ngoại lai phá hỏng đường hồi quy! Câu chuyện ấy dạy ta bài học đầu tiên của khoa học dữ liệu: &lt;strong&gt;con số tóm tắt chỉ có giá trị khi ta hiểu nó đang giữ lại điều gì và che khuất điều gì&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Trong thống kê Bayes, thống kê mô tả không chỉ dùng để khám phá dữ liệu thô ban đầu, mà còn là công cụ hằng ngày để &lt;strong&gt;tóm tắt phân phối hậu nghiệm&lt;/strong&gt; rút ra từ hàng nghìn mẫu MCMC (posterior mean, median, SD, quantiles và tương quan giữa các tham số).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu Học tập&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành bài học này, bạn sẽ hiểu rằng thống kê mô tả không chỉ là việc tính các con số tóm tắt, mà là cách nắm bắt cấu trúc, xu hướng và mức độ biến thiên của dữ liệu. Bạn sẽ biết cách diễn giải trung bình, trung vị và độ lệch chuẩn theo bản chất dữ liệu thay vì áp dụng máy móc, đồng thời hình thành trực giác chọn thống kê phù hợp trong phân tích Bayesian — nơi việc khám phá phân phối dữ liệu luôn là bước khởi đầu trước khi xây dựng mô hình.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-thống-kê-mô-tả-thống-kê-bền-vững-và-tóm-tắt-hậu-nghiệm-bayes&quot;&gt;Kiến thức cần nhớ: Thống kê mô tả, Thống kê bền vững và Tóm tắt Hậu nghiệm Bayes&lt;/h2&gt;

&lt;p&gt;Ba trụ cột gắn kết bài học này với suy diễn Bayes hiện đại:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tâm và Độ phân tán (Location &amp;amp; Scale):&lt;/strong&gt; Trung bình (&lt;em&gt;mean&lt;/em&gt;), trung vị (&lt;em&gt;median&lt;/em&gt;) và yếu vị (&lt;em&gt;mode&lt;/em&gt;) đo vị trí trung tâm; phương sai (&lt;em&gt;variance&lt;/em&gt;), độ lệch chuẩn (&lt;em&gt;SD&lt;/em&gt;) và khoảng tứ phân vị (&lt;em&gt;IQR&lt;/em&gt;) đo mức độ trải rộng. Trong lý thuyết quyết định Bayes, chọn &lt;strong&gt;posterior mean&lt;/strong&gt; tối thiểu hóa sai số bình phương kỳ vọng (\(L_2\) loss), còn chọn &lt;strong&gt;posterior median&lt;/strong&gt; tối thiểu hóa sai số tuyệt đối kỳ vọng (\(L_1\) loss)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thống kê bền vững (Robust Statistics):&lt;/strong&gt; Trung bình và độ lệch chuẩn rất nhạy với ngoại lai (&lt;em&gt;outliers&lt;/em&gt;), trong khi trung vị và IQR bền vững hơn nhiều. Tương tự, khi hậu nghiệm bị lệch (như phân phối của phương sai \(\sigma^2\) hoặc tỷ lệ gần 0), median và khoảng tin cậy (credible interval) cho bức tranh trung thực hơn mean ± SD.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tương quan và Hình học Hậu nghiệm:&lt;/strong&gt; Hệ số tương quan Pearson đo mối quan hệ tuyến tính. Trong MCMC, tương quan mạnh giữa hai tham số hậu nghiệm (ví dụ hệ số chặn và độ dốc trong hồi quy) tạo ra “hẻm núi hẹp” khiến bộ lấy mẫu chậm hội tụ — lúc đó ta cần chuẩn hóa dữ liệu (centering/scaling) trước khi chạy mô hình.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-tại-sao-chúng-ta-cần-thống-kê-mô-tả&quot;&gt;Giới thiệu: Tại sao chúng ta cần Thống kê Mô tả?&lt;/h2&gt;

&lt;p&gt;Giả sử bạn nhận được tập dữ liệu chiều cao của 10,000 người trưởng thành. Việc nhìn từng giá trị riêng lẻ không thể cho bạn kết luận rõ ràng; bạn cần những đại lượng tóm tắt và biểu đồ để nắm được đặc điểm chính của tập dữ liệu.&lt;/p&gt;

&lt;p&gt;Đó là vai trò của thống kê mô tả. Nó giúp thu gọn hàng nghìn hay hàng triệu quan sát thành một số đặc trưng dễ theo dõi, trả lời các câu hỏi nền tảng: giá trị “điển hình” nằm ở đâu, dữ liệu phân tán mạnh hay yếu, có giá trị bất thường nào không, và phân phối đối xứng hay bị lệch?&lt;/p&gt;

&lt;p&gt;Trong phân tích Bayesian, bước này càng quan trọng. Trước khi thiết lập một mô hình xác suất, ta cần hiểu dữ liệu để chọn họ phân phối phù hợp, xác định tham số cần ước lượng và nhận diện sớm các giả định có nguy cơ bị vi phạm.&lt;/p&gt;

&lt;h2 id=&quot;thống-kê-vị-trí-trung-tâm-tìm-kiếm-giá-trị-điển-hình&quot;&gt;Thống kê Vị trí Trung tâm: Tìm kiếm Giá trị “Điển hình”&lt;/h2&gt;

&lt;p&gt;Câu hỏi đầu tiên khi tiếp cận dữ liệu thường là “giá trị điển hình là gì?”. Tuy nhiên, khái niệm “điển hình” có nhiều cách hiểu khác nhau, nên ta có nhiều thước đo vị trí trung tâm tương ứng.&lt;/p&gt;

&lt;h3 id=&quot;trung-bình-điểm-cân-bằng&quot;&gt;Trung bình: Điểm Cân bằng&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Trung bình số học&lt;/strong&gt; (arithmetic mean) là thước đo vị trí trung tâm quen thuộc nhất. Với tập dữ liệu \(x_1, x_2, \ldots, x_n\), trung bình được định nghĩa là:&lt;/p&gt;

\[\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i\]

&lt;p&gt;Về mặt hình học, trung bình đóng vai trò như điểm cân bằng của dữ liệu: nếu coi mỗi điểm dữ liệu là một vật nặng đặt trên một thanh thẳng, thanh sẽ cân bằng tại \(\bar{x}\). Một cách hình thức, trung bình là giá trị làm tổng các độ lệch so với nó bằng không: \(\sum_{i=1}^{n} (x_i - \bar{x}) = 0\).&lt;/p&gt;

&lt;p&gt;Điểm yếu lớn của trung bình là rất nhạy cảm với giá trị ngoại lai (outlier): chỉ một giá trị cực lớn cũng có thể kéo trung bình ra xa phần lớn dữ liệu. Chẳng hạn, xét thu nhập của 10 người, trong đó 9 người kiếm từ 30,000 đến 50,000 đô la mỗi năm và một người kiếm 1,000,000 đô la. Khi đó trung bình khoảng 130,000 đô la — con số không phản ánh mức thu nhập điển hình của nhóm.&lt;/p&gt;

&lt;p&gt;Trong phân tích Bayesian, trung bình thường gắn với tham số vị trí của phân phối chuẩn. Khi mô hình hóa dữ liệu dưới dạng \(y_i \sim \mathcal{N}(\mu, \sigma^2)\), \(\mu\) là trung bình của phân phối và trung bình mẫu \(\bar{x}\) là ước lượng tự nhiên từ dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;trung-vị-giá-trị-giữa&quot;&gt;Trung vị: Giá trị Giữa&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Trung vị&lt;/strong&gt; (median) là giá trị nằm chính giữa khi sắp xếp dữ liệu theo thứ tự tăng dần. Nếu số quan sát \(n\) là lẻ, trung vị là giá trị thứ \((n+1)/2\); nếu \(n\) là chẵn, trung vị là trung bình của hai giá trị ở giữa.&lt;/p&gt;

&lt;p&gt;Ưu điểm nổi bật của trung vị là tính &lt;strong&gt;bền vững (robust)&lt;/strong&gt; trước các giá trị ngoại lai. Việc thay đổi các giá trị cực đoan không làm thay đổi trung vị, miễn là thứ tự quanh điểm giữa giữ nguyên. Trong ví dụ thu nhập ở trên, trung vị vẫn nằm trong khoảng 30,000–50,000 đô la, phản ánh sát hơn thu nhập điển hình của nhóm.&lt;/p&gt;

&lt;p&gt;Trung vị cũng có diễn giải xác suất rõ ràng: xác suất quan sát một giá trị nhỏ hơn trung vị là 50%, và lớn hơn trung vị cũng là 50% (tức phân vị thứ 50). Trong phân tích Bayesian, khi phân phối hậu nghiệm (posterior) bị lệch hoặc có đuôi dài, người ta thường dùng trung vị hậu nghiệm kèm khoảng tin cậy thay vì chỉ báo cáo trung bình hậu nghiệm.&lt;/p&gt;

&lt;h3 id=&quot;so-sánh-trung-bình-và-trung-vị-phát-hiện-độ-lệch&quot;&gt;So sánh Trung bình và Trung vị: Phát hiện Độ lệch&lt;/h3&gt;

&lt;p&gt;So sánh trung bình và trung vị giúp nhận diện hình dạng phân phối. Nếu phân phối đối xứng, trung bình và trung vị gần bằng nhau. Nếu phân phối lệch phải (đuôi dài về phía giá trị lớn), trung bình lớn hơn trung vị; nếu lệch trái, trung bình nhỏ hơn trung vị.&lt;/p&gt;

&lt;p&gt;Thông tin này có ý nghĩa trực tiếp khi chọn mô hình: nếu trung bình và trung vị chênh lệch rõ rệt, phân phối chuẩn có thể không phù hợp và ta nên cân nhắc các phân phối lệch như log-normal, Gamma hoặc Beta tùy theo bản chất dữ liệu.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Hai hình dưới đây tách riêng hai trường hợp để bạn nhìn rõ vị trí tương đối giữa trung bình và trung vị trong từng dạng phân phối.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_mean_median_symmetric.png&quot; alt=&quot;Phân phối đối xứng với trung bình gần trung vị&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1a: Ở phân phối gần đối xứng, trung bình và trung vị gần như trùng nhau.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_mean_median_right_skewed.png&quot; alt=&quot;Phân phối lệch phải với trung bình bị kéo về phía đuôi&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 1b: Khi dữ liệu lệch phải, đuôi dài kéo trung bình sang phải mạnh hơn trung vị — một dấu hiệu trực quan quan trọng trước khi chọn mô hình.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;một-ví-dụ-ngắn-trung-bình-và-trung-vị-kể-hai-câu-chuyện-khác-nhau&quot;&gt;Một ví dụ ngắn: trung bình và trung vị kể hai câu chuyện khác nhau&lt;/h3&gt;

&lt;p&gt;Giả sử thu nhập tháng (triệu đồng) của 10 người là:&lt;/p&gt;

\[30,\ 31,\ 32,\ 33,\ 34,\ 35,\ 36,\ 37,\ 38,\ 120\]

&lt;p&gt;Khi đó:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Trung bình là \(42.6\).&lt;/li&gt;
  &lt;li&gt;Trung vị là \(34.5\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nếu chỉ báo cáo trung bình, người đọc dễ lầm tưởng mức thu nhập điển hình vượt quá 40 triệu, trong khi thực tế 9/10 người nằm trong khoảng 30–38 triệu và chỉ một giá trị cực lớn đã kéo trung bình lên cao. Ví dụ này cho thấy các chỉ số thống kê mô tả cần được đọc song song thay vì dựa vào một con số đơn lẻ.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-mean-vs-median--độ-lệch-chuẩn-trước-ngoại-lai&quot;&gt;Video ngắn: Mean vs Median &amp;amp; Độ lệch chuẩn trước Ngoại lai&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-06a-mean-median-outlier.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 2 giây: kéo một ngoại lai trên trục số để thấy Mean &amp;amp; SD nhảy vọt trong khi Median &amp;amp; IQR đứng yên, phân phối lệch phải, chuẩn hóa Z-score và tóm tắt mẫu MCMC.&lt;/p&gt;

&lt;h2 id=&quot;thống-kê-phân-tán-đo-lường-sự-không-chắc-chắn&quot;&gt;Thống kê Phân tán: Đo lường Sự Không chắc chắn&lt;/h2&gt;

&lt;p&gt;Chỉ biết vị trí trung tâm là chưa đủ. Hai tập dữ liệu có thể có cùng trung bình nhưng mức độ biến thiên rất khác nhau: một tập tập trung chặt quanh trung bình, tập kia phân tán rộng. Các thống kê phân tán giúp định lượng sự biến thiên đó.&lt;/p&gt;

&lt;h3 id=&quot;phương-sai-và-độ-lệch-chuẩn-độ-lệch-bình-phương-trung-bình&quot;&gt;Phương sai và Độ lệch Chuẩn: Độ lệch Bình phương Trung bình&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phương sai mẫu&lt;/strong&gt; (sample variance) đo mức độ phân tán trung bình của dữ liệu quanh trung bình mẫu:&lt;/p&gt;

\[s^2 = \frac{1}{n-1} \sum_{i=1}^{n} (x_i - \bar{x})^2\]

&lt;p&gt;Lưu ý mẫu số là \(n-1\) thay vì \(n\). Đây là &lt;strong&gt;hiệu chỉnh Bessel&lt;/strong&gt; (Bessel’s correction), giúp phương sai mẫu trở thành ước lượng không chệch (unbiased estimator) của phương sai tổng thể, do ta đã dùng dữ liệu để ước lượng \(\bar{x}\) làm mất đi một bậc tự do (degree of freedom).&lt;/p&gt;

&lt;p&gt;Hạn chế của phương sai là đơn vị đo bị bình phương so với dữ liệu gốc (ví dụ chiều cao đo bằng cm thì phương sai có đơn vị cm²), khiến việc diễn giải trực tiếp kém tự nhiên. Vì vậy, ta thường dùng &lt;strong&gt;độ lệch chuẩn&lt;/strong&gt; (standard deviation):&lt;/p&gt;

\[s = \sqrt{s^2}\]

&lt;p&gt;Độ lệch chuẩn có cùng đơn vị với dữ liệu gốc và có thể hiểu như độ lệch điển hình của các quan sát so với trung bình. Trong phân tích Bayesian, phương sai (hoặc độ chính xác — nghịch đảo của phương sai) là tham số then chốt cần ước lượng; chẳng hạn với mô hình \(y_i \sim \mathcal{N}(\mu, \sigma^2)\), \(\sigma^2\) là phương sai và \(s^2\) là ước lượng tự nhiên từ mẫu.&lt;/p&gt;

&lt;h3 id=&quot;phân-vị-và-khoảng-tứ-phân-vị-thống-kê-bền-vững&quot;&gt;Phân vị và Khoảng Tứ phân vị: Thống kê Bền vững&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phân vị&lt;/strong&gt; (quantile hoặc percentile) chia phân phối theo tỷ lệ phần trăm. Phân vị thứ \(p\) (\(0 &amp;lt; p &amp;lt; 1\)) là giá trị mà \(100p\%\) dữ liệu nhỏ hơn hoặc bằng nó; ví dụ phân vị 0.25 (tứ phân vị thứ nhất, Q1) là mốc có 25% dữ liệu nhỏ hơn hoặc bằng nó.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Khoảng tứ phân vị&lt;/strong&gt; (interquartile range, IQR) là hiệu giữa tứ phân vị thứ ba (Q3) và tứ phân vị thứ nhất (Q1):&lt;/p&gt;

\[\text{IQR} = Q3 - Q1\]

&lt;p&gt;IQR bao phủ 50% dữ liệu ở giữa và bền vững trước giá trị ngoại lai. Quy tắc phổ biến để nhận diện giá trị ngoại lai tiềm năng là kiểm tra các điểm nằm ngoài đoạn \([Q1 - 1.5 \times \text{IQR}, Q3 + 1.5 \times \text{IQR}]\).&lt;/p&gt;

&lt;p&gt;Trong phân tích Bayesian, phân vị được dùng rộng rãi để tóm tắt phân phối hậu nghiệm. Bên cạnh trung bình hoặc trung vị, ta thường báo cáo &lt;strong&gt;khoảng tin cậy&lt;/strong&gt; (credible interval), chẳng hạn khoảng 95% được xác định từ phân vị 0.025 đến phân vị 0.975, chứa 95% khối lượng xác suất hậu nghiệm.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Hai hình dưới đây tách riêng câu chuyện về độ phân tán theo độ lệch chuẩn và cách biểu diễn IQR trên biểu đồ hộp (box plot).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_spread_same_mean_diff_sd.png&quot; alt=&quot;Hai phân phối có cùng trung bình nhưng độ phân tán khác nhau&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 2a: Hai tập dữ liệu có trung bình gần như bằng nhau nhưng độ phân tán khác nhau rõ rệt.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_boxplot_iqr_outliers.png&quot; alt=&quot;Box plot thể hiện IQR và outlier&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 2b: Biểu đồ hộp hiển thị phần hộp chứa 50% dữ liệu ở giữa, đường trung vị bên trong hộp, và các điểm đỏ đánh dấu giá trị ngoại lai tiềm năng theo quy tắc \(1.5 \times \text{IQR}\).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;trực-quan-hóa-nhìn-thấy-câu-chuyện-trong-dữ-liệu&quot;&gt;Trực quan hóa: Nhìn thấy Câu chuyện trong Dữ liệu&lt;/h2&gt;

&lt;p&gt;Các chỉ số tóm tắt rất hữu ích nhưng không thể thay thế việc quan sát trực tiếp dữ liệu. Trực quan hóa giúp phát hiện cấu trúc, xu hướng và điểm bất thường mà các con số tóm tắt dễ bỏ sót. Trong phân tích Bayesian, biểu đồ vừa phục vụ bước khám phá ban đầu, vừa hỗ trợ kiểm tra mô hình và trình bày kết quả.&lt;/p&gt;

&lt;h3 id=&quot;histogram-ước-lượng-phân-phối&quot;&gt;Histogram: Ước lượng Phân phối&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Histogram&lt;/strong&gt; chia miền dữ liệu thành các khoảng (bin) và đếm số quan sát rơi vào từng khoảng, với chiều cao mỗi cột tỷ lệ với tần số hoặc mật độ trong khoảng đó.&lt;/p&gt;

&lt;p&gt;Có thể xem histogram như một ước lượng thô của hàm mật độ xác suất (PDF). Khi cỡ mẫu tăng và độ rộng khoảng giảm, histogram tiến gần tới PDF thực của phân phối — đây cũng là nền tảng của &lt;strong&gt;ước lượng mật độ hạt nhân&lt;/strong&gt; (kernel density estimation, KDE). Khi vẽ histogram, việc chọn số lượng bin rất quan trọng: quá ít bin làm mất chi tiết hình dạng, còn quá nhiều bin dễ gây nhiễu. Các quy tắc kinh nghiệm như quy tắc Sturges (\(k = \lceil \log_2 n \rceil + 1\)) hoặc quy tắc Scott thường là điểm khởi đầu hợp lý.&lt;/p&gt;

&lt;h3 id=&quot;box-plot-tóm-tắt-năm-số&quot;&gt;Box Plot: Tóm tắt Năm Số&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Box plot&lt;/strong&gt; (biểu đồ hộp) trực quan hóa năm mốc tóm tắt: giá trị nhỏ nhất, Q1, trung vị, Q3 và giá trị lớn nhất. Phần hộp bao phủ 50% dữ liệu ở giữa (từ Q1 đến Q3), vạch ngang trong hộp là trung vị, còn hai râu (whiskers) kéo dài tới các quan sát cực trị trong ngưỡng (thường tối đa \(1.5 \times \text{IQR}\) tính từ hai cạnh hộp); những điểm vượt ngoài ngưỡng được vẽ riêng như giá trị ngoại lai tiềm năng.&lt;/p&gt;

&lt;p&gt;Biểu đồ hộp đặc biệt tiện lợi khi so sánh nhiều nhóm song song, giúp nhận ra nhanh sự khác biệt về vị trí trung tâm, độ phân tán và độ lệch giữa các nhóm.&lt;/p&gt;

&lt;h3 id=&quot;scatter-plot-khám-phá-mối-quan-hệ&quot;&gt;Scatter Plot: Khám phá Mối quan hệ&lt;/h3&gt;

&lt;p&gt;Với hai biến số, &lt;strong&gt;scatter plot&lt;/strong&gt; (biểu đồ phân tán) biểu diễn mỗi quan sát bằng một điểm có tọa độ \((x, y)\). Biểu đồ này giúp kiểm tra hai biến có tương quan hay không, quan hệ có dạng tuyến tính hay phi tuyến, và dữ liệu có giá trị ngoại lai hay tách thành nhiều cụm riêng biệt hay không — những thông tin trực tiếp định hướng việc chọn mô hình Bayesian.&lt;/p&gt;

&lt;h2 id=&quot;tương-quan-đo-lường-mối-quan-hệ-tuyến-tính&quot;&gt;Tương quan: Đo lường Mối quan hệ Tuyến tính&lt;/h2&gt;

&lt;p&gt;Để định lượng độ mạnh của mối quan hệ tuyến tính thấy trên biểu đồ phân tán, ta dùng &lt;strong&gt;hệ số tương quan Pearson&lt;/strong&gt;:&lt;/p&gt;

\[r = \frac{\sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_{i=1}^{n} (x_i - \bar{x})^2} \sqrt{\sum_{i=1}^{n} (y_i - \bar{y})^2}}\]

&lt;p&gt;Hệ số \(r\) luôn nằm trong đoạn \([-1, 1]\): \(r = 1\) ứng với quan hệ tuyến tính dương hoàn hảo, \(r = -1\) ứng với quan hệ tuyến tính âm hoàn hảo, và \(r = 0\) cho thấy không có quan hệ tuyến tính.&lt;/p&gt;

&lt;p&gt;Cần lưu ý hai điểm quan trọng khi diễn giải tương quan. Thứ nhất, hệ số Pearson chỉ đo lường quan hệ &lt;strong&gt;tuyến tính&lt;/strong&gt;: hai biến có thể liên hệ phi tuyến rất chặt nhưng vẫn có \(r \approx 0\). Thứ hai, &lt;strong&gt;tương quan không đồng nghĩa với nhân quả&lt;/strong&gt;: hai biến tương quan có thể cùng chịu ảnh hưởng từ một biến ẩn thứ ba hoặc chỉ trùng hợp ngẫu nhiên.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Ba hình dưới đây tách riêng từng dạng quan hệ để cho thấy vì sao một hệ số tương quan duy nhất có thể che khuất cấu trúc thật của dữ liệu.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_correlation_linear.png&quot; alt=&quot;Quan hệ tuyến tính dương trong scatter plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 3a: Với quan hệ tuyến tính dương, hệ số Pearson \(r\) phản ánh khá sát xu hướng dữ liệu.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_correlation_nonlinear.png&quot; alt=&quot;Quan hệ phi tuyến trong scatter plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 3b: Quan hệ phi tuyến rất rõ trên biểu đồ nhưng lại bị hệ số Pearson \(r\) đánh giá thấp.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_correlation_hidden_groups.png&quot; alt=&quot;Tương quan do nhóm ẩn trong scatter plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hình 3c: Tương quan tổng thể có thể phát sinh do cấu trúc nhóm ẩn, nên luôn cần quan sát biểu đồ trước khi tin vào một con số tóm tắt.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Trong phân tích Bayesian, mối quan hệ giữa các biến thường được mô hình hóa tường minh qua tham số mô hình. Chẳng hạn, trong hồi quy tuyến tính Bayesian, hệ số hồi quy \(\beta\) biểu diễn mối liên hệ giữa biến giải thích và biến phản hồi, còn phân phối hậu nghiệm của \(\beta\) định lượng độ bất định quanh ước lượng đó.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-bộ-tứ-anscombe-đừng-bao-giờ-tin-mỗi-con-số-tóm-tắt&quot;&gt;Video ngắn: Bộ tứ Anscombe: Đừng bao giờ tin mỗi con số tóm tắt!&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-06b-anscombe-correlation.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 2 giây: so sánh cả 4 bộ dữ liệu Anscombe có cùng Mean, SD và r = 0.816 nhưng hình dáng hoàn toàn khác nhau, tầm quan trọng của EDA và giải pháp Spearman/Student-t.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-vì-sao-mean-median-và-mode-tách-nhau--và-ý-nghĩa-khi-đọc-mẫu-mcmc&quot;&gt;Giải thích: Vì sao Mean, Median và Mode tách nhau — và ý nghĩa khi đọc mẫu MCMC&lt;/h2&gt;

&lt;p&gt;Khi nhìn vào một tập dữ liệu hay một chuỗi mẫu hậu nghiệm từ MCMC, đừng bao giờ chỉ đọc mỗi số trung bình. Hãy đi chậm qua 4 bước đọc tóm tắt:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;So sánh Mean và Median để phát hiện độ lệch:&lt;/strong&gt; Nếu Mean \(&amp;gt;\) Median đáng kể, phân phối lệch phải (có đuôi dài bên phải hoặc ngoại lai lớn).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dùng SD kết hợp với IQR:&lt;/strong&gt; Với phân phối Chuẩn, \(\text{IQR} \approx 1.35 \times \text{SD}\). Nếu SD lớn bất thường so với IQR, gần như chắc chắn có ngoại lai hoặc đuôi nặng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Liên hệ với hàm mất mát Bayes:&lt;/strong&gt; Nếu bạn phải chốt một con số duy nhất từ hậu nghiệm, Mean tối ưu cho phạt sai số bậc hai, Median tối ưu cho phạt sai số bậc một, còn Mode (MAP) tối ưu cho sai số 0–1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra tương quan giữa các chiều:&lt;/strong&gt; Tương quan \(r \approx 0\) chỉ loại trừ quan hệ &lt;em&gt;tuyến tính&lt;/em&gt;, không loại trừ quan hệ phi tuyến (như parabol \(y = x^2\)).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-tóm-tắt-mẫu-dữ-liệu-hoặc-mẫu-hậu-nghiệm-bị-lệch&quot;&gt;Ví dụ tính toán làm từng bước: Tóm tắt mẫu dữ liệu (hoặc mẫu hậu nghiệm) bị lệch&lt;/h3&gt;

&lt;p&gt;Giả sử bạn thu thập 5 quan sát về thời gian phản hồi API (tính bằng mili-giây): \(x = \{10, 12, 14, 14, 50\}\).&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Vị trí trung tâm:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Mean: \(\bar{x} = \frac{10 + 12 + 14 + 14 + 50}{5} = \frac{100}{5} = 20\text{ ms}\).&lt;/li&gt;
      &lt;li&gt;Median (giá trị đứng thứ 3 sau khi sắp xếp): \(14\text{ ms}\).&lt;/li&gt;
      &lt;li&gt;Mode (xuất hiện nhiều nhất): \(14\text{ ms}\).
Nhận xét: Chỉ một ngoại lai \(50\) đã kéo Mean lên \(20\) — cao hơn cả 4/5 giá trị thực tế!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Độ phân tán (tính tay phương sai mẫu hiệu chỉnh \(n-1\)):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Các độ lệch \((x_i - 20)\): \(-10, -8, -6, -6, +30\).&lt;/li&gt;
      &lt;li&gt;Tổng bình phương độ lệch: \(100 + 64 + 36 + 36 + 900 = 1136\).&lt;/li&gt;
      &lt;li&gt;Phương sai mẫu: \(s^2 = \frac{1136}{5 - 1} = 284 \implies s = \sqrt{284} \approx 16.85\text{ ms}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Tương phản khi bỏ ngoại lai \(50\) (chỉ xét 4 giá trị đầu):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Mean mới: \(\frac{10+12+14+14}{4} = 12.5\text{ ms}\); độ lệch chuẩn mới chỉ còn \(\sqrt{\frac{6.25+0.25+2.25+2.25}{3}} \approx 1.91\text{ ms}\) — giảm gần 9 lần!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Dùng công thức \(\bar{x} \pm 2s\) để báo cáo khoảng bất định cho phân phối lệch: trong ví dụ trên, \(20 - 2(16.85) = -13.7\text{ ms}\) — một thời gian phản hồi âm vô nghĩa! Trong Bayes, luôn dùng phân vị hậu nghiệm (ví dụ phân vị 2.5% và 97.5%) hoặc HDI.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu ta nhân toàn bộ dữ liệu với 2 (đổi đơn vị), Mean và SD tăng gấp 2 lần, còn phương sai tăng gấp \(2^2 = 4\) lần.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qBigTkBLU6g&quot;&gt;StatQuest: Histograms, Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giải thích cách dùng histogram để quan sát hình dạng phân phối trước khi tóm tắt bằng số liệu.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Finding mean, median, and mode&lt;/td&gt;
          &lt;td&gt;Descriptive statistics&lt;/td&gt;
          &lt;td&gt;Probability and Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=k3aKKasOmIw) — Khan Academy, English. Phân biệt vai trò của trung bình, trung vị và yếu vị (mode) trong thống kê vị trí.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=xZ_z8KWkhXE&quot;&gt;Pearson’s Correlation, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Trình bày ý nghĩa và giới hạn của hệ số tương quan Pearson.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 1: Tính toán Thống kê Mô tả.&lt;/strong&gt; Cho dữ liệu điểm thi của 20 sinh viên: [45, 67, 78, 82, 55, 90, 88, 76, 95, 20, 85, 72, 68, 91, 77, 83, 65, 89, 74, 80]. (a) Tính trung bình, trung vị và yếu vị (mode). (b) Tính phương sai, độ lệch chuẩn và IQR. (c) Xác định giá trị ngoại lai theo quy tắc \(1.5 \times \text{IQR}\). (d) Giải thích vì sao trung bình và trung vị khác nhau, và điều này phản ánh gì về hình dạng phân phối dữ liệu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 2: Trực quan hóa và Diễn giải.&lt;/strong&gt; Dùng Python sinh 1000 quan sát từ: (a) phân phối chuẩn \(\mathcal{N}(50, 10^2)\), và (b) phân phối log-normal với tham số \(\mu = 3.5, \sigma = 0.5\). Với mỗi phân phối, vẽ histogram và box plot, tính trung bình và trung vị, rồi giải thích sự khác biệt giữa hai phân phối dựa trên thống kê và biểu đồ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 3: Tương quan và Nhân quả.&lt;/strong&gt; Xét hai cặp biến: (a) doanh số bán kem và số vụ đuối nước (cả hai cùng tăng vào mùa hè), và (b) số giờ học và điểm thi. Với mỗi cặp, hãy phân tích: hai biến có tương quan không, có quan hệ nhân quả không, và nếu có tương quan mà không có nhân quả thì nguyên nhân là gì? Điều này rút ra lưu ý gì khi diễn giải tương quan?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 4: Nhận diện Phân phối.&lt;/strong&gt; Xét ba tập dữ liệu (có thể tự mô phỏng hoặc lấy dữ liệu thực): (a) chiều cao người trưởng thành, (b) số email nhận được mỗi ngày, và (c) thời gian chờ giữa hai cuộc gọi đến tổng đài. Với mỗi tập dữ liệu, vẽ histogram, tính thống kê mô tả và đề xuất một phân phối xác suất phù hợp (chuẩn, Poisson, mũ, v.v.), kèm giải thích.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 5: Khám phá Dữ liệu Thực tế.&lt;/strong&gt; Chọn một tập dữ liệu thực tế (ví dụ Iris, Boston Housing hoặc tập dữ liệu bạn quan tâm) và thực hiện phân tích khám phá: (a) tính thống kê mô tả cho các biến số, (b) vẽ histogram và box plot cho các biến liên tục, (c) vẽ scatter plot và tính tương quan theo cặp biến, (d) phát hiện và bàn luận về giá trị ngoại lai, (e) viết một đoạn tóm tắt ngắn về đặc điểm dữ liệu cùng đề xuất phân phối và mô hình phù hợp cho phân tích Bayesian.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu Tham khảo&lt;/h2&gt;

&lt;h3 id=&quot;primary-references&quot;&gt;Primary References:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., &amp;amp; Rubin, D. B. (2013).&lt;/strong&gt; &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 6: Model checking and improvement (posterior predictive checks)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kruschke, J. K. (2015).&lt;/strong&gt; &lt;em&gt;Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan&lt;/em&gt; (2nd Edition). Academic Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 3: The R Programming Language (data exploration)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;supplementary-reading&quot;&gt;Supplementary Reading:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Tukey, J. W. (1977).&lt;/strong&gt; &lt;em&gt;Exploratory Data Analysis&lt;/em&gt;. Addison-Wesley.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Classic text on EDA philosophy and techniques&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Wickham, H., &amp;amp; Grolemund, G. (2017).&lt;/strong&gt; &lt;em&gt;R for Data Science&lt;/em&gt;. O’Reilly Media.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 7: Exploratory Data Analysis&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_04_python_basics/&quot;&gt;0.7 Python Cơ bản cho Data Science&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.5: Beta và Gamma - Phân phối cho Xác suất và Tham số Dương</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_02_04_beta_gamma_bayesian/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_02_04_beta_gamma_bayesian</id>
   <content type="html">&lt;p&gt;Nếu Bernoulli, Binomial và Poisson là những phân phối mô tả &lt;em&gt;dữ liệu quan sát&lt;/em&gt;, thì &lt;strong&gt;Beta&lt;/strong&gt; và &lt;strong&gt;Gamma&lt;/strong&gt; là những phân phối sống ở tầng trên: chúng mô tả &lt;strong&gt;sự không chắc chắn về chính các tham số chưa biết&lt;/strong&gt;. Khi bạn nói “tôi nghĩ tỷ lệ click nằm đâu đó quanh 20%, nhưng chưa chắc lắm”, bạn đang cần một phân phối trên đoạn \([0, 1]\) — đó là Beta. Khi bạn cần đặt niềm tin lên một tốc độ \(\lambda &amp;gt; 0\) hay độ chính xác \(\tau &amp;gt; 0\), bạn cần một phân phối trên \((0, \infty)\) — đó là Gamma.&lt;/p&gt;

&lt;p&gt;Hiểu thấu đáo Beta và Gamma không chỉ giúp bạn giải tay các bài toán liên hợp đầu khóa, mà còn mở khóa tư duy &lt;strong&gt;phân cấp (hierarchical modeling)&lt;/strong&gt;: tham số cũng là biến ngẫu nhiên có phân phối của riêng nó.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu phân phối Beta dùng để mô tả các đại lượng nằm trong đoạn \([0,1]\), nắm được ý nghĩa của các tham số \(\alpha,\beta\), hiểu vai trò của phân phối Gamma cho tham số dương, và thấy rõ chức năng của hằng số chuẩn hóa trong việc tạo ra một hàm mật độ hợp lệ.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hàm-đặc-biệt-gammabeta-họ-mũ-và-prior-liên-hợp&quot;&gt;Kiến thức cần nhớ: Hàm đặc biệt (Gamma/Beta), Họ mũ và Prior liên hợp&lt;/h2&gt;

&lt;p&gt;Ba trụ cột toán học nâng đỡ bài học này:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Giải tích hàm đặc biệt (Special Functions):&lt;/strong&gt; Hàm Gamma \(\Gamma(\alpha) = \int_0^\infty t^{\alpha-1} e^{-t}\,dt\) mở rộng giai thừa sang số thực dương (\(\Gamma(n) = (n-1)!\)), còn hàm Beta \(B(\alpha, \beta) = \frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\) là hằng số chuẩn hóa đảm bảo tích phân mật độ trên \([0,1]\) bằng đúng 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không gian tham số và Miền giá trị (Support Matching):&lt;/strong&gt; Một nguyên tắc vàng khi xây mô hình Bayes là miền giá trị của prior phải khớp với miền hợp lệ của tham số: \(\theta \in (0,1) \Rightarrow \text{Beta}\); \(\lambda &amp;gt; 0 \Rightarrow \text{Gamma}\) (hoặc Half-Normal, Log-Normal).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Tính liên hợp &amp;amp; Mô hình tổng quát:&lt;/strong&gt; Beta và Gamma là hai đại diện kinh điển của &lt;strong&gt;họ mũ (exponential family)&lt;/strong&gt; có prior liên hợp dạng đóng. Khi bước sang các mô hình không liên hợp (như hồi quy logistic hay mạng Bayes), ta vẫn giữ tư duy tương tự về hình dạng prior nhưng thay giải tích dạng đóng bằng &lt;strong&gt;MCMC&lt;/strong&gt; hoặc &lt;strong&gt;Variational Inference&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-bắt-đầu-từ-vấn-đề-thực-tế-mô-tả-một-tỷ-lệ-chưa-biết&quot;&gt;1) Bắt đầu từ vấn đề thực tế: mô tả một tỷ lệ chưa biết&lt;/h2&gt;

&lt;p&gt;Trong thực tế, ta thường gặp các đại lượng dạng tỷ lệ như tỷ lệ khách hàng nhấp chuột, tỷ lệ sản phẩm lỗi, hay tỷ lệ học viên hoàn thành khóa học. Các đại lượng này có chung một đặc điểm: giá trị luôn nằm giữa 0 và 1.&lt;/p&gt;

&lt;p&gt;Để mô hình hóa chúng, ta cần một phân phối đủ linh hoạt trên đoạn \([0,1]\) — có thể lệch trái, lệch phải, hoặc tập trung quanh một vùng trung tâm. Đó là vai trò của phân phối Beta.&lt;/p&gt;

&lt;h2 id=&quot;2-phân-phối-beta-cho-xác-suất&quot;&gt;2) Phân phối Beta cho xác suất&lt;/h2&gt;

&lt;p&gt;Phân phối Beta được viết là:&lt;/p&gt;

\[p\sim\text{Beta}(\alpha,\beta), \quad 0&amp;lt;p&amp;lt;1.\]

&lt;p&gt;Có thể hiểu nhanh rằng \(\alpha-1\) gắn với phần nghiêng về “thành công”, còn \(\beta-1\) gắn với phần nghiêng về “thất bại”. Kỳ vọng của phân phối là:&lt;/p&gt;

\[\mathbb{E}[p]=\frac{\alpha}{\alpha+\beta}.\]

&lt;p&gt;Khi tổng \(\alpha+\beta\) lớn, phân phối tập trung hẹp quanh trung bình; khi \(\alpha+\beta\) nhỏ, phân phối dàn rộng hơn.&lt;/p&gt;

&lt;p&gt;Hằng số chuẩn hóa của phân phối Beta là hàm Beta:&lt;/p&gt;

\[B(\alpha,\beta)=\int_0^1 p^{\alpha-1}(1-p)^{\beta-1}\,dp
=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}.\]

&lt;p&gt;Do đó, hàm mật độ đầy đủ có dạng:&lt;/p&gt;

\[f(p)=\frac{1}{B(\alpha,\beta)}p^{\alpha-1}(1-p)^{\beta-1},\quad 0&amp;lt;p&amp;lt;1.\]

&lt;h3 id=&quot;video-ngắn-betaα-β-phân-phối-trên-0-1--dữ-liệu-ảo&quot;&gt;Video ngắn: Beta(α, β): Phân phối trên [0, 1] &amp;amp; Dữ liệu ảo&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-05a-beta-pseudocounts.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 2 giây: các hình dáng Beta(1,1), chữ U Beta(0.5,0.5), lệch Beta(2,8), so sánh Beta(7,3) với Beta(70,30) và tính ổn định số log-beta.&lt;/p&gt;

&lt;h2 id=&quot;3-hàm-gamma-và-cầu-nối-tới-hàm-beta&quot;&gt;3) Hàm Gamma và cầu nối tới hàm Beta&lt;/h2&gt;

&lt;p&gt;Để biểu diễn hằng số chuẩn hóa của Beta, ta sử dụng hàm Gamma:&lt;/p&gt;

\[\Gamma(z)=\int_0^{\infty} t^{z-1}e^{-t}\,dt,\quad z&amp;gt;0.\]

&lt;p&gt;Hàm Gamma mở rộng khái niệm giai thừa sang các số thực dương với tính chất đệ quy:&lt;/p&gt;

\[\Gamma(z+1)=z\,\Gamma(z),\qquad \Gamma(n+1)=n!\;(n\in\mathbb{N}).\]

&lt;p&gt;Nhờ đó, hằng số chuẩn hóa của Beta được viết gọn thành tỷ số các hàm Gamma:&lt;/p&gt;

\[B(\alpha,\beta)=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}.\]

&lt;p&gt;Về mặt thực hành, công thức này chuyển một tích phân chuẩn hóa khó tính trực tiếp thành tỷ số của các hàm Gamma, giúp việc tính toán ổn định và rõ cấu trúc hơn.&lt;/p&gt;

&lt;h2 id=&quot;4-phân-phối-beta-giải-quyết-vấn-đề-gì&quot;&gt;4) Phân phối Beta giải quyết vấn đề gì?&lt;/h2&gt;

&lt;p&gt;Phân phối Beta cung cấp một khuôn khổ có hệ thống để trả lời câu hỏi: “tỷ lệ thật nhiều khả năng nằm ở vùng nào trong đoạn \([0,1]\), và mức độ tập trung mạnh hay yếu ra sao?” Nói gọn lại:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\alpha\) và \(\beta\) quyết định hình dạng phân phối,&lt;/li&gt;
  &lt;li&gt;\(\frac{\alpha}{\alpha+\beta}\) xác định vị trí trung tâm,&lt;/li&gt;
  &lt;li&gt;\(\alpha+\beta\) phản ánh mức độ tập trung quanh trung tâm.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nhờ vậy, Beta không chỉ biểu diễn một con số tỷ lệ đơn lẻ mà còn thể hiện trọn vẹn độ bất định xung quanh tỷ lệ đó.&lt;/p&gt;

&lt;h2 id=&quot;5-ví-dụ-đọc-hình-dạng-beta&quot;&gt;5) Ví dụ đọc hình dạng Beta&lt;/h2&gt;

&lt;p&gt;Nếu \(\alpha=2,\beta=5\), mật độ nghiêng về phía gần 0; ngược lại, nếu \(\alpha=8,\beta=3\), mật độ nghiêng về phía gần 1. Nói cách khác, cặp tham số \(\alpha,\beta\) đồng thời kiểm soát cả vị trí lẫn độ tập trung của phân phối trên đoạn \([0,1]\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/beta_binomial_update_vi.png&quot; alt=&quot;So sánh hình dạng Beta với các bộ tham số khác nhau&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Biểu đồ cho thấy sự thay đổi của các tham số làm dịch chuyển vị trí đỉnh và co giãn độ rộng của phân phối Beta trên đoạn \([0,1]\).&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-phân-phối-betaα-β-5-dáng-hình-kinh-điển--cập-nhật-từng-lượt-click&quot;&gt;Video ngắn: Phân phối Beta(α, β): 5 dáng hình kinh điển &amp;amp; Cập nhật từng lượt click&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-05c-beta-shape-explorer.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 41 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): biến hình mượt Beta(α, β) qua 5 dáng (đều, chữ U, chữ J, lệch phải, chuông hẹp) rồi mô phỏng 20 khách truy cập cập nhật trực tiếp Beta(2, 2) → Beta(9, 15).&lt;/p&gt;

&lt;h2 id=&quot;6-phân-phối-gamma-cho-tham-số-dương&quot;&gt;6) Phân phối Gamma cho tham số dương&lt;/h2&gt;

&lt;p&gt;Một cách tham số hóa phổ biến của phân phối Gamma là dạng shape–rate (hình dạng–tốc độ):&lt;/p&gt;

\[\lambda\sim\text{Gamma}(\alpha,\beta), \quad
f(\lambda)=\frac{\beta^\alpha}{\Gamma(\alpha)}\lambda^{\alpha-1}e^{-\beta\lambda},\; \lambda&amp;gt;0.\]

&lt;p&gt;Kỳ vọng của phân phối là:&lt;/p&gt;

\[\mathbb{E}[\lambda]=\frac{\alpha}{\beta}.\]

&lt;p&gt;Trong công thức trên, \(\frac{\beta^\alpha}{\Gamma(\alpha)}\) là hằng số chuẩn hóa bảo đảm tổng xác suất bằng 1:&lt;/p&gt;

\[\int_0^{\infty} f(\lambda)\,d\lambda=1.\]

&lt;p&gt;Nếu bỏ hệ số này, biểu thức \(\lambda^{\alpha-1}e^{-\beta\lambda}\) mới chỉ mô tả hình dạng chứ chưa phải một hàm mật độ hợp lệ.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-phân-phối-gamma-miền-dương-0---cặp-liên-hợp&quot;&gt;Video ngắn: Phân phối Gamma: Miền dương (0, ∞) &amp;amp; Cặp liên hợp&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-05b-gamma-positive-rate.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 2 giây: phân phối Gamma trên miền dương, vai trò shape α và rate β, hàm Gamma mở rộng giai thừa và cập nhật Gamma–Poisson.&lt;/p&gt;

&lt;h2 id=&quot;7-ví-dụ-trực-giác-với-gamma&quot;&gt;7) Ví dụ trực giác với Gamma&lt;/h2&gt;

&lt;p&gt;Với tham số hóa shape–rate:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Khi giữ nguyên \(\alpha\) và tăng \(\beta\), phân phối dịch về gần 0 hơn.&lt;/li&gt;
  &lt;li&gt;Khi tăng \(\alpha\), phân phối có đỉnh rõ hơn và bớt lệch phải hơn.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Phân phối Gamma phù hợp để mô tả các đại lượng dương như thời gian chờ, cường độ xảy ra sự kiện, hoặc các biến có đuôi phải dài.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-phân-phối-gammak-λ-chờ-đủ-k-đơn-hàng--vì-sao-bắt-đầu-từ-0&quot;&gt;Video ngắn: Phân phối Gamma(k, λ): Chờ đủ k đơn hàng &amp;amp; Vì sao bắt đầu từ 0?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-05d-gamma-waiting-k-events.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 39 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): ghép nối tiếp 3 khoảng chờ Exponential trên dòng thời gian qua 48 lượt thử để dựng Gamma(3, 1), giải thích mật độ bằng 0 tại t = 0 và trượt mượt k từ 1 (Exponential) → 5.5 (gần Chuông).&lt;/p&gt;

&lt;h2 id=&quot;8-dạng-chưa-chuẩn-hóa-và-dạng-chuẩn-hóa&quot;&gt;8) Dạng chưa chuẩn hóa và dạng chuẩn hóa&lt;/h2&gt;

&lt;p&gt;Trong thực hành, ta thường gặp phần lõi (kernel) của mật độ trước, chẳng hạn:&lt;/p&gt;

\[g(p)=p^{\alpha-1}(1-p)^{\beta-1}.\]

&lt;p&gt;Biểu thức này chưa phải mật độ hợp lệ vì tích phân của nó trên \([0,1]\) không nhất thiết bằng 1. Để chuẩn hóa thành mật độ, ta chia cho hằng số chuẩn hóa tương ứng:&lt;/p&gt;

\[f(p)=\frac{1}{B(\alpha,\beta)}g(p).\]

&lt;p&gt;Nguyên tắc tương tự áp dụng cho Gamma: phần lũy thừa và hàm mũ quy định hình dạng đường cong, còn hệ số phía trước bảo đảm tổng diện tích dưới đường cong bằng 1.&lt;/p&gt;

&lt;h2 id=&quot;9-mẹo-thực-hành&quot;&gt;9) Mẹo thực hành&lt;/h2&gt;

&lt;p&gt;Khi sử dụng phân phối Gamma, luôn ghi rõ mình đang dùng tham số hóa shape–rate hay shape–scale. Khi đọc tài liệu khác, cần kiểm tra kỹ ký hiệu để tránh nhầm giữa tham số tốc độ (rate) \(\beta\) và tham số tỷ lệ (scale) \(\theta=1/\beta\).&lt;/p&gt;

&lt;h2 id=&quot;10-mở-rộng-từ-giai-thừa-sang-gamma&quot;&gt;10) Mở rộng từ giai thừa sang Gamma&lt;/h2&gt;

&lt;p&gt;Với số nguyên dương \(n\), giai thừa được định nghĩa là:&lt;/p&gt;

\[n!=1\cdot 2\cdot 3\cdots n.\]

&lt;p&gt;Hàm Gamma mở rộng khái niệm này sang tập số thực dương, nên ta có thể liên hệ nhanh với ký hiệu giai thừa mở rộng:&lt;/p&gt;

\[x!=\Gamma(x+1),\quad x&amp;gt;0.\]

&lt;p&gt;Ví dụ với một số giá trị nguyên nhỏ:&lt;/p&gt;

\[\Gamma(1)=1,\quad \Gamma(2)=1!,\quad \Gamma(3)=2!,\quad \Gamma(6)=5!.\]

&lt;h2 id=&quot;11-giá-trị-đặc-biệt-thường-gặp&quot;&gt;11) Giá trị đặc biệt thường gặp&lt;/h2&gt;

&lt;p&gt;Một giá trị đặc biệt rất hay gặp của hàm Gamma là:&lt;/p&gt;

\[\Gamma\!\left(\frac{1}{2}\right)=\sqrt{\pi}.\]

&lt;p&gt;Áp dụng công thức đệ quy \(\Gamma(z+1)=z\,\Gamma(z)\), ta suy ra:&lt;/p&gt;

\[\Gamma\!\left(\frac{3}{2}\right)=\frac{\sqrt{\pi}}{2},
\qquad
\Gamma\!\left(\frac{5}{2}\right)=\frac{3\sqrt{\pi}}{4}.\]

&lt;p&gt;Đây cũng là lý do hằng số \(\pi\) xuất hiện trong nhiều công thức phân phối liên tục.&lt;/p&gt;

&lt;h2 id=&quot;12-ví-dụ-tính-hàm-beta&quot;&gt;12) Ví dụ tính hàm Beta&lt;/h2&gt;

&lt;p&gt;Với \(a,b&amp;gt;0\):&lt;/p&gt;

\[B(a,b)=\int_0^1 t^{a-1}(1-t)^{b-1}\,dt
=\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}.\]

&lt;p&gt;Chẳng hạn, với \(a=2, b=3\):&lt;/p&gt;

\[B(2,3)=\frac{\Gamma(2)\Gamma(3)}{\Gamma(5)}=\frac{1!\,2!}{4!}=\frac{1}{12}.\]

&lt;p&gt;Ví dụ này minh họa trực tiếp vai trò của hàm Gamma trong việc tính hằng số chuẩn hóa cho phân phối Beta.&lt;/p&gt;

&lt;h2 id=&quot;13-ví-dụ-số-cho-hình-dạng-beta-710&quot;&gt;13) Ví dụ số cho hình dạng Beta (7/10)&lt;/h2&gt;

&lt;p&gt;Xét biểu thức theo \(\theta\) trên đoạn \([0,1]\):&lt;/p&gt;

\[g(\theta)=\theta^8(1-\theta)^4.\]

&lt;p&gt;Đây mới là dạng chưa chuẩn hóa. Khi chuẩn hóa, ta thu được mật độ của \(\text{Beta}(9,5)\):&lt;/p&gt;

\[f(\theta)=\frac{1}{B(9,5)}\theta^8(1-\theta)^4.\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/beta_binomial_update_7of10.png&quot; alt=&quot;Beta-Binomial update 7 over 10&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Hai đường cong có cùng hình dạng tương đối; nhân thêm hệ số \(1/B(9,5)\) chỉ điều chỉnh tỷ lệ trục tung để diện tích dưới đường cong bằng 1.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;14-gợi-ý-tính-toán-số-ổn-định&quot;&gt;14) Gợi ý tính toán số ổn định&lt;/h2&gt;

&lt;p&gt;Khi các tham số lớn, giá trị của hàm Gamma có thể vượt quá giới hạn biểu diễn số thực dấu phẩy động. Khi đó, nên tính trên thang log thay vì tính trực tiếp:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln(z)&lt;/code&gt; thay cho &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(gamma(z))&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;betaln(a,b)&lt;/code&gt; thay cho &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(beta(a,b))&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trong SciPy, các hàm này nằm trong mô-đun &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.special&lt;/code&gt; và cho độ ổn định số học cao hơn.&lt;/p&gt;

&lt;p&gt;Ví dụ Python:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy.special&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gammaln&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;betaln&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# 120.0
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# ~1.7724538509 = sqrt(pi)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gammaln&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# log(Gamma(100))
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# 1/12 = 0.08333...
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;betaln&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# log(Beta(2,3))
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;15-tóm-tắt-nhanh&quot;&gt;15) Tóm tắt nhanh&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Phân phối Beta mô tả linh hoạt các đại lượng nằm trong \([0,1]\).&lt;/li&gt;
  &lt;li&gt;Phân phối Gamma mô tả các đại lượng nhận giá trị dương.&lt;/li&gt;
  &lt;li&gt;Hàm Gamma mở rộng khái niệm giai thừa: \(\Gamma(n+1)=n!\).&lt;/li&gt;
  &lt;li&gt;Hàm Beta liên hệ trực tiếp với hàm Gamma qua tỷ số \(\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}\).&lt;/li&gt;
  &lt;li&gt;Hằng số chuẩn hóa biến một biểu thức “đúng hình dạng” thành hàm mật độ xác suất hợp lệ.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;giải-thích-giải-mã-siêu-tham-số-như-dữ-liệu-ảo-pseudo-counts&quot;&gt;Giải thích: Giải mã siêu tham số như “dữ liệu ảo” (Pseudo-counts)&lt;/h2&gt;

&lt;p&gt;Sinh viên mới học Bayes thường lúng túng: &lt;em&gt;làm sao chọn \(\alpha, \beta\) cho Beta hay Gamma mà không phải đoán mò?&lt;/em&gt; Câu trả lời nằm ở cách diễn giải &lt;strong&gt;dữ liệu ảo&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Beta(\(\alpha, \beta\)) là tổng của hai số đếm ảo:&lt;/strong&gt; Có thể xem \(\alpha - 1\) là số thành công ảo và \(\beta - 1\) là số thất bại ảo (hoặc trực quan hơn: \(\alpha + \beta\) là “cỡ mẫu ảo” quyết định độ mạnh của prior).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra độ tập trung:&lt;/strong&gt; Cùng trung bình \(0.5\), nhưng \(\text{Beta}(1, 1)\) là phân phối đều (cỡ mẫu ảo 2, gần như không biết gì), còn \(\text{Beta}(50, 50)\) tương đương đã tung đồng xu 100 lần (rất khó bị lay chuyển bởi 5–10 quan sát mới).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gamma(\(\alpha, \beta\)) (tham số hóa shape–rate):&lt;/strong&gt; \(\alpha\) đóng vai trò tổng số sự kiện ảo đã thấy trong \(\beta\) đơn vị thời gian ảo, nên trung bình là \(\alpha/\beta\) và phương sai là \(\alpha/\beta^2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật trở thành phép cộng kế toán:&lt;/strong&gt; Dữ liệu thực chỉ đơn giản cộng thêm vào các số đếm ảo đó.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-chuyển-đổi-niềm-tin-thành-beta-và-kiểm-chứng-hằng-số-chuẩn-hóa&quot;&gt;Ví dụ tính toán làm từng bước: Chuyển đổi niềm tin thành Beta và kiểm chứng hằng số chuẩn hóa&lt;/h3&gt;

&lt;p&gt;Giả sử bạn tin một loại thuốc mới có tỷ lệ hiệu quả quanh \(0.6\) với độ tin cậy tương đương đã thử trên 10 bệnh nhân. Ta chọn \(\alpha = 6, \beta = 4\) (tổng \(\alpha + \beta = 10\), trung bình \(6/10 = 0.6\)).&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Kiểm tra hằng số chuẩn hóa \(B(6, 4)\) bằng tay:&lt;/strong&gt;
\(B(6, 4) = \frac{\Gamma(6)\Gamma(4)}{\Gamma(10)} = \frac{5!\,3!}{9!} = \frac{120 \times 6}{362\,880} = \frac{720}{362\,880} = \frac{1}{504}.\)
Vậy mật độ tiên nghiệm là \(p(\theta) = 504\,\theta^5(1-\theta)^3\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Tính mật độ tại \(\theta = 0.6\) và \(\theta = 0.2\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Tại \(\theta = 0.6\): \(504 \times (0.6)^5 \times (0.4)^3 = 504 \times 0.07776 \times 0.064 \approx 2.508\).&lt;/li&gt;
      &lt;li&gt;Tại \(\theta = 0.2\): \(504 \times (0.2)^5 \times (0.8)^3 = 504 \times 0.00032 \times 0.512 \approx 0.083\).
(Chú ý: mật độ \(2.508 &amp;gt; 1\) hoàn toàn hợp lệ vì đây là PDF trên đoạn ngắn \([0,1]\), miễn tổng diện tích bằng 1).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Cập nhật với thử nghiệm lâm sàng gồm \(n = 15\) bệnh nhân, \(k = 12\) người khỏi bệnh:&lt;/strong&gt;
\(\theta \mid \text{data} \sim \text{Beta}(6 + 12, 4 + 3) = \text{Beta}(18, 7).\)
    &lt;ul&gt;
      &lt;li&gt;Trung bình hậu nghiệm: \(\frac{18}{25} = 0.72\) (dịch chuyển từ prior \(0.60\) hướng về tỷ lệ mẫu \(12/15 = 0.80\)).&lt;/li&gt;
      &lt;li&gt;Độ lệch chuẩn giảm từ \(\sqrt{\frac{6\times 4}{10^2 \times 11}} \approx 0.148\) xuống \(\sqrt{\frac{18 \times 7}{25^2 \times 26}} = \sqrt{\frac{126}{16\,250}} \approx 0.088\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nghĩ rằng \(\text{Beta}(1,1)\) luôn “khách quan tuyệt đối”. Nếu ta biến đổi tham số sang log-odds \(\eta = \log\frac{\theta}{1-\theta}\), một phân phối đều trên \(\theta\) sẽ không còn đều trên \(\eta\) nữa.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Với \(\text{Beta}(18, 7)\), mode (MAP) bằng \(\frac{18-1}{18+7-2} = \frac{17}{23} \approx 0.739\) — hơi lớn hơn trung bình \(0.72\) vì phân phối hơi lệch trái.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=juF3r12nM5A&quot;&gt;The Beta distribution in 12 minutes!&lt;/a&gt; — Luis Serrano Academy, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giải thích cách đọc \(\alpha\) và \(\beta\) như số lần thành công và thất bại giả định trên đoạn \([0,1]\).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=9IIcHAJlcWc&quot;&gt;The Gamma Distribution&lt;/a&gt; — Steve Brunton, English. Minh họa hình dạng phân phối Gamma cho các đại lượng dương như tỷ lệ sự kiện và thời gian chờ.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How to Estimate Rates with a Gamma-Poisson Bayesian Model&lt;/td&gt;
          &lt;td&gt;Conjugate Priors](https://www.youtube.com/watch?v=m8roQUqmybg) — Drawing Distributions, English. Trình bày cặp liên hợp Gamma–Poisson khi ước lượng tốc độ sự kiện trong cập nhật Bayesian.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài 1.&lt;/strong&gt; Dùng công thức đệ quy để tính \(\Gamma(4)\) và \(\Gamma(5)\), sau đó đối chiếu với \(3!\) và \(4!\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài 2.&lt;/strong&gt; Từ \(\Gamma\!\left(\tfrac{1}{2}\right)=\sqrt{\pi}\), suy ra \(\Gamma\!\left(\tfrac{3}{2}\right)\) và \(\Gamma\!\left(\tfrac{5}{2}\right)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài 3.&lt;/strong&gt; Viết lại hằng số chuẩn hóa của \(\text{Beta}(a,b)\) qua hàm Gamma và giải thích vì sao cần hằng số này để tích phân mật độ bằng 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài 4.&lt;/strong&gt; Trong Python, tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gamma(10)&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln(10)&lt;/code&gt;, sau đó kiểm tra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.log(gamma(10))&lt;/code&gt; có khớp với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln(10)&lt;/code&gt; không.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài 5.&lt;/strong&gt; Chứng minh nhanh \(B(a,1)=\frac{1}{a}\) từ định nghĩa tích phân, rồi đối chiếu với công thức tỷ số hàm Gamma.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.). CRC Press.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. K. (2015). &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.). Academic Press.&lt;/li&gt;
  &lt;li&gt;SciPy Special Functions: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gamma&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;tổng-kết&quot;&gt;Tổng kết&lt;/h2&gt;

&lt;p&gt;Beta và Gamma là hai họ phân phối nền tảng trong thống kê: Beta dành cho biến trên \([0,1]\), còn Gamma dành cho biến dương. Điểm cốt lõi cần nhớ là chọn đúng phân phối theo miền giá trị và hiểu vai trò của hằng số chuẩn hóa trong việc biến một phần lõi hàm thành phân phối hợp lệ.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_03_descriptive_statistics/&quot;&gt;0.6 Thống kê Mô tả&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.4: Normal và Trực giác CLT - Khi nào Dữ liệu có dạng Chuông?</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_02_03_normal_clt_intuition/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_02_03_normal_clt_intuition</id>
   <content type="html">&lt;p&gt;Tại sao chiều cao của hàng nghìn sinh viên, sai số đo đạc thiên văn của Carl Friedrich Gauss năm 1809, và nhiễu nhiệt trong mạch điện tử — ba hiện tượng hoàn toàn không liên quan — lại cùng vẽ nên đúng một đường cong hình chuông? Câu trả lời không phải là sự trùng hợp ngẫu nhiên, mà là &lt;strong&gt;Định lý Giới hạn Trung tâm (CLT)&lt;/strong&gt;: bất cứ khi nào một đại lượng là tổng của nhiều tác động nhỏ, độc lập, phân phối của nó sẽ tự động bị “hút” về phân phối Chuẩn (&lt;em&gt;Normal&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Trong thống kê Bayes, phân phối Chuẩn giữ hai vai trò tối quan trọng: vừa là mô hình chuẩn mực cho dữ liệu liên tục và prior liên hợp Normal–Normal, vừa là đích đến tiệm cận của hầu hết phân phối hậu nghiệm khi cỡ mẫu lớn (định lý Bernstein–von Mises và xấp xỉ Laplace).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ hiểu vai trò của phân phối Normal, diễn giải chính xác hai tham số \(\mu\) và \(\sigma\), đồng thời vận dụng trực giác của định lý giới hạn trung tâm (CLT) để giải thích vì sao nhiều đại lượng tổng hợp có dạng gần chuẩn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-entropy-cực-đại-định-lý-giới-hạn-trung-tâm-và-cập-nhật-normalnormal&quot;&gt;Kiến thức cần nhớ: Entropy cực đại, Định lý Giới hạn Trung tâm và Cập nhật Normal–Normal&lt;/h2&gt;

&lt;p&gt;Nhìn ở bậc đại học trở lên, sự thống trị của phân phối Chuẩn đến từ ba trụ cột lý thuyết:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết thông tin (Maximum Entropy):&lt;/strong&gt; Trong tất cả các phân phối liên tục trên \((-\infty, +\infty)\) có cùng trung bình \(\mu\) và phương sai \(\sigma^2\), phân phối Chuẩn có &lt;strong&gt;entropy lớn nhất&lt;/strong&gt; — tức là phân phối “ít giả định thừa nhất” khi bạn chỉ biết trung tâm và độ phân tán.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết giới hạn (CLT &amp;amp; Laplace Approximation):&lt;/strong&gt; Không chỉ tổng các biến ngẫu nhiên hội tụ về Chuẩn, mà ngay cả log-posterior \(\log p(\theta \mid y)\) quanh đỉnh cực đại (MAP) khi khai triển Taylor bậc 2 cũng cho một parabol úp ngược — đồng nghĩa posterior gần đỉnh xấp xỉ một phân phối Chuẩn. Đây là nền tảng của xấp xỉ Laplace và nhiều biến thể Variational Inference.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Prior liên hợp (Normal–Normal):&lt;/strong&gt; Khi dữ liệu tuân theo \(y_i \sim \mathcal{N}(\mu, \sigma^2)\) (biết \(\sigma^2\)) và prior là \(\mu \sim \mathcal{N}(\mu_0, \tau_0^2)\), hậu nghiệm của \(\mu\) vẫn là phân phối Chuẩn với &lt;strong&gt;độ chính xác cộng dồn&lt;/strong&gt; (precision \(= 1/\text{variance}\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-phân-phối-normal-là-gì&quot;&gt;1) Phân phối Normal là gì?&lt;/h2&gt;

&lt;p&gt;Với một biến ngẫu nhiên liên tục \(X\) tuân theo phân phối Normal:&lt;/p&gt;

\[X\sim\mathcal{N}(\mu,\sigma^2),\]

&lt;p&gt;hàm mật độ xác suất có dạng:&lt;/p&gt;

\[f(x)=\frac{1}{\sigma\sqrt{2\pi}}\exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right).\]

&lt;p&gt;Trong đó, \(\mu\) xác định vị trí trung tâm của phân phối, còn \(\sigma\) đo độ phân tán quanh trung tâm đó. Một quy tắc ước lượng nhanh thường dùng là khoảng \(\mu\pm\sigma\) chứa xấp xỉ 68% khối lượng xác suất, khoảng \(\mu\pm 2\sigma\) chứa xấp xỉ 95%, và khoảng \(\mu\pm 3\sigma\) chứa xấp xỉ 99.7%.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/normal_distribution_rule.png&quot; alt=&quot;Quy tắc 68-95-99.7 của phân phối Normal&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Đường cong chuông minh họa quy tắc 68–95–99.7 quanh giá trị trung tâm \(\mu\); mỗi dải màu thể hiện phần diện tích xác suất ứng với 1, 2 và 3 độ lệch chuẩn \(\sigma\).&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-phân-phối-normal-tham-số-μ-σ--quy-tắc-6895997&quot;&gt;Video ngắn: Phân phối Normal: Tham số μ, σ &amp;amp; Quy tắc 68–95–99.7&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-04a-normal-mu-sigma.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 1 giây: trượt tâm μ, co hẹp độ lệch chuẩn σ, tô vùng 68–95–99.7%, cộng độ chính xác Normal–Normal và nguyên lý Entropy cực đại.&lt;/p&gt;

&lt;h2 id=&quot;2-vì-sao-normal-xuất-hiện-nhiều&quot;&gt;2) Vì sao Normal xuất hiện nhiều?&lt;/h2&gt;

&lt;p&gt;Định lý giới hạn trung tâm (CLT) cho biết khi cộng hoặc lấy trung bình nhiều thành phần nhiễu độc lập, đại lượng tổng hợp thường tiến gần dạng phân phối chuẩn, ngay cả khi từng thành phần riêng lẻ không có dạng chuẩn. Nhờ tính chất này, nhiều đại lượng trong thực tế như sai số đo lường, điểm trung bình hay tổng tác động của nhiều yếu tố nhỏ thường phân bố gần dạng Normal.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/clt_sample_means_overlay.png&quot; alt=&quot;CLT làm phân phối của trung bình mẫu dần trở nên tròn và hẹp hơn&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Các đường cong chồng lớp cho thấy khi cỡ mẫu tăng lên, phân phối của trung bình mẫu dần đối xứng dạng chuông và thu hẹp quanh kỳ vọng chung.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-trực-giác-clt-tại-sao-tổng-lại-ra-hình-chuông&quot;&gt;Video ngắn: Trực giác CLT: Tại sao tổng lại ra hình Chuông?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-04b-clt-galton-simulation.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 1 giây: mô phỏng trung bình từ n=1, n=2 đến n=10 trên phân phối Đều và Exponential lệch, tốc độ hội tụ 1/√n và định lý Bernstein–von Mises.&lt;/p&gt;

&lt;h2 id=&quot;3-hằng-số-chuẩn-hóa-của-normal-đến-từ-đâu&quot;&gt;3) Hằng số chuẩn hóa của Normal đến từ đâu?&lt;/h2&gt;

&lt;p&gt;Xét lại hàm mật độ Normal:&lt;/p&gt;

\[f(x)=\frac{1}{\sigma\sqrt{2\pi}}\exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right).\]

&lt;p&gt;Hệ số \(\frac{1}{\sigma\sqrt{2\pi}}\) là hằng số chuẩn hóa bảo đảm tổng diện tích dưới đường cong bằng 1:&lt;/p&gt;

\[\int_{-\infty}^{\infty} f(x)\,dx=1.\]

&lt;p&gt;Đặt biến chuẩn hóa \(z=\frac{x-\mu}{\sigma}\), ta có:&lt;/p&gt;

\[\int_{-\infty}^{\infty} f(x)\,dx
=\int_{-\infty}^{\infty}\frac{1}{\sqrt{2\pi}}e^{-z^2/2}\,dz
=1.\]

&lt;p&gt;Nhờ hệ số này, toàn bộ khối lượng xác suất dưới đường cong chuông bằng đúng 1, giúp \(f(x)\) trở thành một hàm mật độ hợp lệ.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-ví-dụ-lịch-sử-5738-người-lính-scotland-quetelet-1846&quot;&gt;Video ngắn: Ví dụ lịch sử: 5.738 Người lính Scotland (Quetelet, 1846)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-04d-quetelet-soldiers-normal.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 28 giây (dữ liệu lịch sử thực tế &amp;amp; mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): dữ liệu thật số đo vòng ngực 5.738 binh sĩ Scotland (μ = 39.83, σ = 2.05 inch) khớp đường cong Normal cùng trực quan hóa vùng 68% – 95% – 99.7% khi may quân phục.&lt;/p&gt;

&lt;h2 id=&quot;4-ví-dụ-trực-giác&quot;&gt;4) Ví dụ trực giác&lt;/h2&gt;

&lt;p&gt;Giả sử điểm kiểm tra cuối kỳ chịu tác động đồng thời của nhiều yếu tố nhỏ như chất lượng giấc ngủ, mức độ ôn tập, độ khó từng câu hỏi và trạng thái tâm lý khi làm bài. Mỗi yếu tố chỉ gây biến thiên nhỏ, nhưng khi cộng gộp lại, phân phối điểm tổng thường có dạng gần hình chuông. Vì lý do đó, dùng mô hình Normal cho sai số hoặc cho điểm tổng hợp là lựa chọn hợp lý trong nhiều bối cảnh.&lt;/p&gt;

&lt;h3 id=&quot;41-một-cách-đọc-nhanh-bằng-độ-lệch-chuẩn&quot;&gt;4.1) Một cách đọc nhanh bằng độ lệch chuẩn&lt;/h3&gt;

&lt;p&gt;Giả sử chiều cao của một nhóm người được xấp xỉ bởi:&lt;/p&gt;

\[X \sim \mathcal{N}(170, 6^2).\]

&lt;p&gt;Ta có thể ước lượng nhanh mà chưa cần tra bảng hay tính tích phân:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Khoảng \(164\) đến \(176\) cm tương ứng \(\mu \pm 1\sigma\), chứa xấp xỉ 68% quan sát.&lt;/li&gt;
  &lt;li&gt;Khoảng \(158\) đến \(182\) cm tương ứng \(\mu \pm 2\sigma\), chứa xấp xỉ 95% quan sát.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Do đó, một người cao \(182\) cm không phải trường hợp quá bất thường, mà chỉ nằm gần biên trên của vùng 95%.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-vì-sao-tự-nhiên-chuộng-hình-chuông-xúc-xắc-bảng-galton--độ-rộng-σ&quot;&gt;Video ngắn: Vì sao Tự nhiên chuộng Hình Chuông? (Xúc xắc, Bảng Galton &amp;amp; Độ rộng σ)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-04c-why-normal-bell-shape.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 59 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): cộng trực tiếp N = 1 → 2 → 4 → 12 viên xúc xắc (phẳng → tam giác → chuông), mô phỏng viên bi rơi qua bảng Galton 6 hàng chốt và trượt mượt μ, σ giữ nguyên diện tích bằng 1.&lt;/p&gt;

&lt;h2 id=&quot;5-khi-nào-không-nên-dùng-normal&quot;&gt;5) Khi nào không nên dùng Normal?&lt;/h2&gt;

&lt;p&gt;Phân phối Normal không phù hợp khi dữ liệu bị giới hạn miền (chẳng hạn xác suất nằm trong \([0,1]\) hoặc thời gian chờ luôn dương), khi dữ liệu là số đếm nguyên không âm, hoặc khi phân phối bị lệch mạnh, có đuôi dày hay chứa nhiều giá trị ngoại lai (outlier). Trong các trường hợp này, giả định Normal có thể làm sai lệch đáng kể khoảng bất định.&lt;/p&gt;

&lt;h2 id=&quot;6-liên-hệ-bayesian&quot;&gt;6) Liên hệ Bayesian&lt;/h2&gt;

&lt;p&gt;Trong mô hình hóa Bayesian, phân phối Normal xuất hiện ở nhiều vai trò khác nhau: làm hàm hợp lý (likelihood) cho dữ liệu liên tục, làm phân phối tiên nghiệm (prior) cho các hệ số hồi quy, hoặc đóng vai trò xấp xỉ tiện lợi cho phân phối hậu nghiệm (posterior) khi cỡ mẫu đủ lớn. Tuy vậy, quy trình phân tích Bayesian luôn yêu cầu kiểm tra lại giả định mô hình thay vì mặc định gán Normal cho mọi dữ liệu liên tục.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-cơ-chế-cộng-độ-chính-xác-trong-cập-nhật-normalnormal-bằng-tay&quot;&gt;Giải thích: Cơ chế “cộng độ chính xác” trong cập nhật Normal–Normal bằng tay&lt;/h2&gt;

&lt;p&gt;Nếu bạn đã quen viết phân phối Chuẩn theo phương sai \(\sigma^2\), cập nhật Bayes trông khá rắc rối. Bí quyết để mọi thứ trở nên trong suốt là chuyển sang &lt;strong&gt;độ chính xác (&lt;em&gt;precision&lt;/em&gt;)&lt;/strong&gt; — nghịch đảo của phương sai:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Định nghĩa độ chính xác:&lt;/strong&gt; Prior có độ chính xác \(\lambda_0 = \frac{1}{\tau_0^2}\); trung bình mẫu \(\bar{y}\) từ \(n\) quan sát có phương sai \(\sigma^2/n\), nên độ chính xác của dữ liệu là \(\lambda_{\text{data}} = \frac{n}{\sigma^2}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ chính xác hậu nghiệm là phép cộng đơn thuần:&lt;/strong&gt; \(\lambda_{\text{post}} = \lambda_0 + \lambda_{\text{data}}\). Có thêm dữ liệu luôn làm độ chính xác tăng lên (phương sai hậu nghiệm thu nhỏ lại).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trung bình hậu nghiệm là trung bình có trọng số theo độ chính xác:&lt;/strong&gt;
\(\mu_{\text{post}} = \frac{\lambda_0 \mu_0 + \lambda_{\text{data}} \bar{y}}{\lambda_0 + \lambda_{\text{data}}}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trực giác kéo co:&lt;/strong&gt; Ai có độ chính xác cao hơn (phương sai nhỏ hơn) sẽ kéo trung bình hậu nghiệm về phía mình mạnh hơn.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-đo-tốc-độ-phản-ứng-của-một-cảm-biến-mới&quot;&gt;Ví dụ tính toán làm từng bước: Đo tốc độ phản ứng của một cảm biến mới&lt;/h3&gt;

&lt;p&gt;Nhà sản xuất cho biết thời gian trễ trung bình \(\mu\) của dòng cảm biến này quanh mức \(\mu_0 = 50\text{ ms}\) với độ lệch chuẩn tiên nghiệm \(\tau_0 = 4\text{ ms}\) (\(\tau_0^2 = 16\)). Sai số đo mỗi lần thử đã biết là \(\sigma = 6\text{ ms}\) (\(\sigma^2 = 36\)). Bạn đo \(n = 9\) lần và thu được trung bình mẫu \(\bar{y} = 44\text{ ms}\).&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Tính độ chính xác của prior và dữ liệu:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Prior: \(\lambda_0 = \frac{1}{4^2} = \frac{1}{16} = 0.0625\).&lt;/li&gt;
      &lt;li&gt;Dữ liệu: \(\lambda_{\text{data}} = \frac{n}{\sigma^2} = \frac{9}{36} = \frac{1}{4} = 0.2500\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Độ chính xác và phương sai hậu nghiệm:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(\lambda_{\text{post}} = 0.0625 + 0.2500 = 0.3125 = \frac{5}{16}\).&lt;/li&gt;
      &lt;li&gt;Phương sai hậu nghiệm: \(\tau_{\text{post}}^2 = \frac{1}{0.3125} = 3.2 \implies \tau_{\text{post}} = \sqrt{3.2} \approx 1.79\text{ ms}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Trung bình hậu nghiệm:&lt;/strong&gt;
\(\mu_{\text{post}} = \frac{0.0625 \times 50 + 0.2500 \times 44}{0.3125} = \frac{3.125 + 11.0}{0.3125} = \frac{14.125}{0.3125} = 45.2\text{ ms}.\)
Nhận xét: Vì \(\lambda_{\text{data}}\) gấp 4 lần \(\lambda_0\), dữ liệu chiếm trọng số \(4/5 = 80\%\) và prior chiếm \(1/5 = 20\%\): \(0.2 \times 50 + 0.8 \times 44 = 10 + 35.2 = 45.2\text{ ms}\)!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Giả định mọi dữ liệu đều chuẩn khi phân phối thực tế có &lt;strong&gt;đuôi nặng&lt;/strong&gt; (&lt;em&gt;heavy tails&lt;/em&gt;, nhiều ngoại lai). Với dữ liệu có ngoại lai, likelihood Chuẩn sẽ bị kéo lệch mạnh; trong Bayes ta thường thay bằng phân phối Student-\(t\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Khoảng tin cậy Bayes 95% (95% credible interval) của \(\mu\) trong ví dụ trên là \(45.2 \pm 1.96 \times 1.79 \approx [41.7, 48.7]\text{ ms}\), hẹp hơn hẳn khoảng tiên nghiệm \(50 \pm 1.96 \times 4 = [42.2, 57.8]\text{ ms}\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=rzFX5NWojp0&quot;&gt;The Normal Distribution, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giải thích trực quan cách đọc \(\mu\) và \(\sigma\) trên đường cong chuông.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zeJD6dqJ5lo&quot;&gt;But what is the Central Limit Theorem?&lt;/a&gt; — 3Blue1Brown, English. Minh họa trực giác vì sao trung bình của nhiều biến độc lập tiến gần phân phối chuẩn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Sm2yBx3Jn6c&quot;&gt;Định lý giới hạn trung tâm (Central limit theorem)&lt;/a&gt; — Bài Học 10 Phút, Tiếng Việt. Video tiếng Việt ngắn gọn giúp đối chiếu trực tiếp với lập luận CLT trong bài.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Nêu một đại lượng liên tục phù hợp để mô hình hóa bằng phân phối Normal và giải thích lý do.&lt;/li&gt;
  &lt;li&gt;Nêu một đại lượng liên tục nhưng không nên dùng phân phối Normal, đồng thời đề xuất phân phối thay thế.&lt;/li&gt;
  &lt;li&gt;Định lý giới hạn trung tâm (CLT) giúp ích gì cho trực giác về phân phối của trung bình mẫu?&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_02_04_beta_gamma_bayesian/&quot;&gt;0.5 Beta và Gamma&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.3: Poisson và Exponential - Đếm Sự kiện và Thời gian Chờ</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_02_02_poisson_exponential/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_02_02_poisson_exponential</id>
   <content type="html">&lt;p&gt;Cuối thế kỷ 19, nhà thống kê Ladislaus Bortkiewicz thống kê số binh sĩ Phổ tử vong vì bị ngựa đá mỗi năm trong 10 quân đoàn suốt 20 năm — một dữ liệu kỳ lạ nhưng lại trở thành minh họa bất hủ cho phân phối Poisson. Cùng một quá trình ngẫu nhiên xảy ra đều đặn theo thời gian, nếu ta hỏi &lt;em&gt;“có bao nhiêu sự kiện trong 1 giờ?”&lt;/em&gt; ta gặp &lt;strong&gt;Poisson&lt;/strong&gt;; còn nếu ta bấm đồng hồ hỏi &lt;em&gt;“phải chờ bao lâu tới sự kiện kế tiếp?”&lt;/em&gt; ta gặp &lt;strong&gt;Exponential&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Trong thực hành Bayes hiện đại — từ đếm số cuộc gọi tổng đài, số lỗi máy chủ đến số ca bệnh hiếm mỗi tuần — cặp Poisson–Exponential là điểm khởi đầu để hiểu cách mô hình hóa tốc độ \(\lambda &amp;gt; 0\) và cặp liên hợp Gamma–Poisson.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ biết cách mô hình hóa dữ liệu đếm bằng phân phối Poisson, mô hình hóa thời gian chờ bằng phân phối Exponential, và hiểu vì sao hai phân phối này là hai góc nhìn của cùng một quá trình sự kiện ngẫu nhiên theo thời gian.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-quá-trình-điểm-poisson-tính-không-nhớ-và-cặp-liên-hợp-gammapoisson&quot;&gt;Kiến thức cần nhớ: Quá trình điểm Poisson, Tính không nhớ và Cặp liên hợp Gamma–Poisson&lt;/h2&gt;

&lt;p&gt;Ba trụ cột toán học đằng sau bài học này gồm:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Quá trình Poisson (Poisson Process):&lt;/strong&gt; Mô hình hóa các sự kiện xảy ra ngẫu nhiên, độc lập trên trục thời gian hoặc không gian với tốc độ trung bình không đổi \(\lambda\). Nó là giới hạn của phân phối Binomial khi số khoảng thời gian nhỏ \(n \to \infty\) và xác suất mỗi khoảng \(p \to 0\) sao cho \(np = \lambda\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính không nhớ (Memoryless Property) của Exponential:&lt;/strong&gt; \(P(T &amp;gt; t + s \mid T &amp;gt; t) = P(T &amp;gt; s)\). Thời gian đã chờ không làm thay đổi phân phối thời gian phải chờ thêm — đây là lý do phân phối Exponential mô tả cực tốt sự kiện ngẫu nhiên thuần túy nhưng &lt;em&gt;không&lt;/em&gt; phù hợp với thiết bị bị hao mòn theo tuổi thọ (khi đó cần phân phối Weibull).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Thống kê Bayes (Gamma–Poisson):&lt;/strong&gt; Tốc độ \(\lambda\) là tham số dương liên tục (\(\lambda &amp;gt; 0\)). Khi đặt prior \(\text{Gamma}(\alpha, \beta)\) lên \(\lambda\) và quan sát \(n\) khoảng thời gian có tổng số sự kiện \(S = \sum_{i=1}^n y_i\), hậu nghiệm lại là \(\text{Gamma}(\alpha + S, \beta + n)\) — một cập nhật dạng đóng cực kỳ gọn gàng.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-khi-nào-dùng-poisson&quot;&gt;1) Khi nào dùng Poisson?&lt;/h2&gt;

&lt;p&gt;Phân phối Poisson phù hợp khi ta đếm số sự kiện xảy ra trong một khoảng cố định, chẳng hạn số cuộc gọi trong 1 giờ, số lỗi trên 1 trang văn bản, hay số tai nạn tại một giao lộ trong 1 tháng.&lt;/p&gt;

&lt;p&gt;Nếu \(Y\) là số sự kiện trong khoảng quan sát:&lt;/p&gt;

\[Y \sim \text{Poisson}(\lambda), \quad P(Y=k)=\frac{\lambda^k e^{-\lambda}}{k!},\; k=0,1,2,\dots\]

&lt;p&gt;Ở đây, \(\lambda\) là số sự kiện trung bình trong mỗi khoảng. Tính chất đặc trưng của phân phối Poisson là kỳ vọng và phương sai bằng nhau:&lt;/p&gt;

\[\mathbb{E}[Y]=\lambda, \qquad \mathrm{Var}(Y)=\lambda.\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/poisson_counts_timeline.png&quot; alt=&quot;Poisson mô tả số sự kiện đếm được trong các khoảng thời gian cố định&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Biểu đồ minh họa cách phân phối Poisson mô tả số sự kiện đếm được trong các khoảng thời gian cố định; hãy đối chiếu trục giá trị đếm với xác suất tương ứng để thấy vị trí đỉnh và độ rộng của phân phối.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-quá-trình-poisson-đếm-sự-kiện-theo-thời-gian&quot;&gt;Video ngắn: Quá trình Poisson: Đếm sự kiện theo thời gian&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-03a-poisson-from-binomial.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 17 giây: chia nhỏ trục 60 phút để đi từ Binomial đến giới hạn Poisson(λ), dịch chuyển λ=3→5, cảnh báo quá phân tán và tính cộng.&lt;/p&gt;

&lt;h2 id=&quot;2-khi-nào-dùng-exponential&quot;&gt;2) Khi nào dùng Exponential?&lt;/h2&gt;

&lt;p&gt;Phân phối Exponential phù hợp khi đại lượng quan tâm là thời gian chờ cho đến sự kiện tiếp theo. Nếu \(T\) là thời gian chờ:&lt;/p&gt;

\[T \sim \text{Exponential}(\lambda), \quad f(t)=\lambda e^{-\lambda t},\; t\ge 0.\]

&lt;p&gt;Kỳ vọng của \(T\) là:&lt;/p&gt;

\[\mathbb{E}[T]=\frac{1}{\lambda}.\]

&lt;p&gt;Điều này hoàn toàn thuận tự nhiên: tốc độ xảy ra sự kiện \(\lambda\) càng cao thì thời gian chờ trung bình càng ngắn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/exponential_waiting_time_curve.png&quot; alt=&quot;Exponential mô tả thời gian chờ tới sự kiện kế tiếp&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Đường cong minh họa hàm mật độ Exponential cho thời gian chờ tới sự kiện kế tiếp, giảm dần theo hàm mũ khi thời gian chờ tăng lên.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-exponential-thời-gian-chờ--tính-không-nhớ&quot;&gt;Video ngắn: Exponential: Thời gian chờ &amp;amp; Tính không nhớ&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-03b-exponential-memoryless.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 2 giây: mật độ thời gian chờ Exp(λ), chứng minh trực quan tính không nhớ, ví dụ Gamma–Poisson lỗi máy chủ và cầu nối e^(-λt).&lt;/p&gt;

&lt;h2 id=&quot;3-hằng-số-chuẩn-hóa-trong-poisson-và-exponential&quot;&gt;3) Hằng số chuẩn hóa trong Poisson và Exponential&lt;/h2&gt;

&lt;p&gt;Với phân phối Poisson:&lt;/p&gt;

\[P(Y=k)=\frac{\lambda^k e^{-\lambda}}{k!},\quad k=0,1,2,\dots\]

&lt;p&gt;Trong công thức này, \(k!\) xuất hiện từ lập luận đếm tổ hợp về số cách sắp xếp các sự kiện, còn \(e^{-\lambda}\) là hệ số chuẩn hóa bảo đảm tổng toàn bộ PMF bằng đúng 1:&lt;/p&gt;

\[\sum_{k=0}^{\infty} \frac{\lambda^k e^{-\lambda}}{k!}
=e^{-\lambda}\sum_{k=0}^{\infty}\frac{\lambda^k}{k!}
=e^{-\lambda}e^{\lambda}=1.\]

&lt;p&gt;Với phân phối Exponential:&lt;/p&gt;

\[f(t)=\lambda e^{-\lambda t},\quad t\ge 0.\]

&lt;p&gt;Hệ số \(\lambda\) chính là hằng số chuẩn hóa để tích phân hàm mật độ trên \([0, \infty)\) bằng 1:&lt;/p&gt;

\[\int_0^{\infty} \lambda e^{-\lambda t}\,dt=1.\]

&lt;p&gt;Nếu bỏ \(\lambda\), biểu thức \(e^{-\lambda t}\) mới chỉ thể hiện dạng suy giảm theo hàm mũ chứ chưa phải một hàm mật độ xác suất hợp lệ.&lt;/p&gt;

&lt;h2 id=&quot;4-liên-hệ-trực-tiếp-giữa-poisson-và-exponential&quot;&gt;4) Liên hệ trực tiếp giữa Poisson và Exponential&lt;/h2&gt;

&lt;p&gt;Nếu các sự kiện xảy ra theo một quá trình Poisson với tốc độ \(\lambda\), thì số sự kiện trong khoảng thời gian dài \(\Delta t\) tuân theo phân phối \(\text{Poisson}(\lambda\Delta t)\), còn khoảng thời gian giữa hai sự kiện liên tiếp tuân theo phân phối \(\text{Exponential}(\lambda)\). Vì vậy, hai câu hỏi “có bao nhiêu sự kiện trong một khoảng thời gian” và “phải chờ bao lâu đến sự kiện tiếp theo” thực chất xuất phát từ cùng một mô hình.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-quán-cà-phê--trạm-xe-buýt-poisson-và-exponential-sinh-ra-từ-đâu&quot;&gt;Video ngắn: Quán Cà phê &amp;amp; Trạm Xe buýt: Poisson và Exponential sinh ra từ đâu?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-03c-poisson-exp-live-world.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 47 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): một dòng khách duy nhất trong 48 giờ đồng thời dựng cả biểu đồ Poisson (đếm số khách) lẫn Exponential (đo khoảng chờ), rồi trượt mượt tốc độ λ từ 0.8 → 9.0.&lt;/p&gt;

&lt;h2 id=&quot;5-ví-dụ-ngắn&quot;&gt;5) Ví dụ ngắn&lt;/h2&gt;

&lt;p&gt;Giả sử một tổng đài nhận trung bình 6 cuộc gọi mỗi giờ. Số cuộc gọi trong 1 giờ có thể mô hình hóa bằng \(Y\sim\text{Poisson}(6)\). Khi đó, xác suất không có cuộc gọi nào trong 10 phút (tức \(1/6\) giờ) là:&lt;/p&gt;

\[P(Y=0)=e^{-6\times(1/6)}=e^{-1}\approx 0.368.\]

&lt;p&gt;Trong khi đó, thời gian chờ trung bình đến cuộc gọi tiếp theo là:&lt;/p&gt;

\[\mathbb{E}[T]=\frac{1}{6}\text{ giờ}=10\text{ phút}.\]

&lt;h3 id=&quot;51-cùng-một-lambda-trả-lời-hai-câu-hỏi-khác-nhau&quot;&gt;5.1) Cùng một \(\lambda\), trả lời hai câu hỏi khác nhau&lt;/h3&gt;

&lt;p&gt;Vẫn với tốc độ \(\lambda = 6\) cuộc gọi mỗi giờ:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Trong 30 phút, số cuộc gọi kỳ vọng là \(6 \times 0.5 = 3\), nên ta dùng phân phối Poisson để đánh giá nguy cơ quá tải theo số cuộc gọi.&lt;/li&gt;
  &lt;li&gt;Trong 5 phút đầu, xác suất xuất hiện ít nhất một cuộc gọi được tính bằng Exponential:&lt;/li&gt;
&lt;/ul&gt;

\[P(T \leq 5\text{ phút}) = 1 - e^{-6\times(5/60)} = 1 - e^{-0.5} \approx 0.393.\]

&lt;p&gt;Nghĩa là trong 5 phút đầu, xác suất tổng đài nhận ít nhất một cuộc gọi vào khoảng 39.3%.&lt;/p&gt;

&lt;p&gt;Điểm mấu chốt là Poisson trả lời câu hỏi về số lần đếm trong một khoảng thời gian cố định, còn Exponential trả lời câu hỏi về thời gian chờ đến sự kiện kế tiếp; cả hai cùng dùng chung một tham số tốc độ \(\lambda\).&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-ví-dụ-lịch-sử-bom-bay-v-1-ở-london-1944--kỵ-binh-phổ-1898&quot;&gt;Video ngắn: Ví dụ lịch sử: Bom bay V-1 ở London (1944) &amp;amp; Kỵ binh Phổ (1898)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-03d-london-v1-poisson-map.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 27 giây (dữ liệu lịch sử thực tế &amp;amp; mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): kiểm chứng 537 quả bom V-1 trên 576 ô Nam London của R. D. Clarke (1946) và 200 quân đoàn-năm kỵ binh Phổ của Bortkiewicz (1898) khớp sát phân phối Poisson.&lt;/p&gt;

&lt;h2 id=&quot;6-cảnh-báo-mô-hình-hóa&quot;&gt;6) Cảnh báo mô hình hóa&lt;/h2&gt;

&lt;p&gt;Nếu dữ liệu đếm có phương sai lớn hơn trung bình đáng kể (hiện tượng quá phân tán — overdispersion), phân phối Poisson thường quá chặt; khi đó nên cân nhắc phân phối Negative Binomial hoặc mô hình phân cấp. Ngoài ra, nếu tốc độ sự kiện thay đổi theo thời gian (như giờ cao điểm và giờ thấp điểm), giả định \(\lambda\) là hằng số cũng không còn phù hợp.&lt;/p&gt;

&lt;h2 id=&quot;7-liên-hệ-bayesian&quot;&gt;7) Liên hệ Bayesian&lt;/h2&gt;

&lt;p&gt;Trong thống kê Bayesian, việc kết hợp phân phối tiên nghiệm Gamma cho \(\lambda\) với hàm hợp lý (likelihood) Poisson sẽ cho phân phối hậu nghiệm (posterior) cũng thuộc họ Gamma. Đây là cặp liên hợp rất tiện lợi cho các bài toán đếm sự kiện.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_02_03_normal_clt_intuition/&quot;&gt;0.4 Normal và trực giác CLT&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-hai-mặt-của-cùng-một-đồng-xu-và-cập-nhật-gammapoisson-bằng-tay&quot;&gt;Giải thích: Hai mặt của cùng một đồng xu và cập nhật Gamma–Poisson bằng tay&lt;/h2&gt;

&lt;p&gt;Hãy đọc chậm mối liên hệ toán học giữa đếm sự kiện (Poisson) và thời gian chờ (Exponential):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Biến cố tương đương:&lt;/strong&gt; “Thời gian chờ đến sự kiện đầu tiên lớn hơn \(t\)” (\(T &amp;gt; t\)) hoàn toàn tương đương với “Có đúng \(0\) sự kiện xảy ra trong khoảng \([0, t]\)” (\(N(t) = 0\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Suy ra hàm sống còn (Survival Function):&lt;/strong&gt; Với \(N(t) \sim \text{Poisson}(\lambda t)\), ta có \(P(T &amp;gt; t) = P(N(t) = 0) = \frac{(\lambda t)^0 e^{-\lambda t}}{0!} = e^{-\lambda t}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lấy đạo hàm để ra mật độ Exponential:&lt;/strong&gt; \(F(t) = 1 - e^{-\lambda t} \implies f(t) = \lambda e^{-\lambda t}\) với \(t \ge 0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đưa vào cập nhật Bayes:&lt;/strong&gt; Nhân prior \(\text{Gamma}(\alpha, \beta) \propto \lambda^{\alpha-1} e^{-\beta \lambda}\) với likelihood Poisson \(\prod_{i=1}^n \frac{\lambda^{y_i} e^{-\lambda}}{y_i!} \propto \lambda^{\sum y_i} e^{-n\lambda}\), số mũ của \(\lambda\) và hệ số trên \(e\) tự động cộng dồn!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-ước-lượng-tốc-độ-lỗi-máy-chủ-lambda-lỗigiờ&quot;&gt;Ví dụ tính toán làm từng bước: Ước lượng tốc độ lỗi máy chủ \(\lambda\) (lỗi/giờ)&lt;/h3&gt;

&lt;p&gt;Trước khi triển khai bản cập nhật phần mềm, đội vận hành tin tốc độ lỗi quanh mức 2 lỗi/giờ với độ bất định vừa phải, mã hóa bằng prior \(\lambda \sim \text{Gamma}(\alpha=4, \beta=2)\) (trung bình tiên nghiệm \(\alpha/\beta = 4/2 = 2.0\) lỗi/giờ, tương đương kinh nghiệm 2 giờ quan sát thấy 4 lỗi).&lt;/p&gt;

&lt;p&gt;Trong \(n = 3\) giờ đầu sau khi phát hành, hệ thống ghi nhận số lỗi lần lượt là \(y = (5, 3, 4)\), tổng \(S = 5 + 3 + 4 = 12\) lỗi.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Xác suất quan sát được đúng 5 lỗi trong giờ đầu nếu \(\lambda = 2\):&lt;/strong&gt;
\(P(Y = 5 \mid \lambda = 2) = \frac{2^5 e^{-2}}{5!} = \frac{32 \times 0.1353}{120} \approx 0.0361 \quad (3.61\%).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Cập nhật hậu nghiệm Gamma–Poisson:&lt;/strong&gt;
\(\alpha_{\text{post}} = 4 + 12 = 16, \qquad \beta_{\text{post}} = 2 + 3 = 5 \implies \lambda \mid y \sim \text{Gamma}(16, 5).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Tóm tắt hậu nghiệm tính tay:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Trung bình hậu nghiệm: \(\mathbb{E}[\lambda \mid y] = \frac{16}{5} = 3.2\) lỗi/giờ (nằm giữa prior \(2.0\) và trung bình mẫu \(12/3 = 4.0\)).&lt;/li&gt;
      &lt;li&gt;Độ lệch chuẩn hậu nghiệm: \(\frac{\sqrt{16}}{5} = \frac{4}{5} = 0.8\) lỗi/giờ.&lt;/li&gt;
      &lt;li&gt;Thời gian chờ kỳ vọng giữa hai lỗi mới theo ước lượng trung bình hậu nghiệm: \(1 / 3.2 = 0.3125\) giờ (\(\approx 18.75\) phút).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhầm giữa tham số &lt;em&gt;rate&lt;/em&gt; \(\beta\) và tham số &lt;em&gt;scale&lt;/em&gt; \(\theta = 1/\beta\) của phân phối Gamma khi viết mã Python/SciPy — luôn kiểm tra kỳ vọng \(\alpha/\beta\) (rate) hay \(\alpha\theta\) (scale).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu quan sát thêm 1 giờ nữa không có lỗi nào (\(y_4 = 0\)), hậu nghiệm mới là \(\text{Gamma}(16 + 0, 5 + 1) = \text{Gamma}(16, 6)\), trung bình giảm từ \(3.2\) xuống \(16/6 \approx 2.67\) lỗi/giờ — ngay cả dữ liệu “không có sự kiện” cũng cung cấp thông tin!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jmqZG6roVqU&quot;&gt;An Introduction to the Poisson Distribution&lt;/a&gt; — jbstatistics, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Trình bày phân phối Poisson như mô hình đếm số sự kiện trong một khoảng cố định, khớp với nửa đầu bài học.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=n7K8s4vryCQ&quot;&gt;Understanding Exponential vs Poisson Distributions&lt;/a&gt; — Explained by Michael, English. Đối chiếu trực tiếp giữa thời gian chờ và số lần đếm, làm rõ mối liên hệ giữa hai phân phối.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=wtLQUjfomig&quot;&gt;The Exponential Distribution&lt;/a&gt; — StatQuest with Josh Starmer, English. Giải thích hình dạng và tham số của phân phối Exponential cho bài toán thời gian chờ.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.2: Bernoulli và Binomial - Từ Kết quả Nhị phân đến Số lần Thành công</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_02_01_bernoulli_binomial/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_02_01_bernoulli_binomial</id>
   <content type="html">&lt;p&gt;Mọi dữ liệu lớn nhất trên Internet — từ một cú nhấp chuột vào quảng cáo, một ca phẫu thuật thành công hay thất bại, đến việc một khách hàng rời bỏ dịch vụ — ở cấp độ nguyên tử đều bắt đầu từ một câu hỏi nhị phân: &lt;em&gt;Có&lt;/em&gt; hay &lt;em&gt;Không&lt;/em&gt;? Jacob Bernoulli đã dành hơn hai mươi năm cuối đời viết cuốn &lt;em&gt;Ars Conjectandi&lt;/em&gt; (1713) để chứng minh rằng khi lặp lại phép thử đơn giản ấy đủ nhiều lần, tần suất quan sát sẽ tiến sát về xác suất thật \(p\).&lt;/p&gt;

&lt;p&gt;Trong thống kê Bayes, Bernoulli và Binomial là &lt;strong&gt;phòng thí nghiệm đầu tiên&lt;/strong&gt; cho mọi ý tưởng lớn: ta đặt một phân phối prior lên \(p\), thu thập \(k\) thành công trong \(n\) lần thử qua likelihood Binomial, và chứng kiến niềm tin về \(p\) sắc nét dần theo từng quan sát.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau bài này, bạn sẽ phân biệt rõ phân phối Bernoulli và Binomial, hiểu cơ chế sinh dữ liệu nối giữa hai phân phối này, và biết cách diễn giải các tham số theo ngôn ngữ thực tế thay vì chỉ đọc công thức.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-mô-hình-sinh-dữ-liệu-nhị-phân-likelihood-và-tính-liên-hợp&quot;&gt;Kiến thức cần nhớ: Mô hình sinh dữ liệu nhị phân, Likelihood và Tính liên hợp&lt;/h2&gt;

&lt;p&gt;Để đọc sâu bài này dưới góc nhìn tốt nghiệp đại học, hãy nối ba mảnh ghép:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tổ hợp và Phân phối rời rạc (Combinatorics &amp;amp; Discrete PMF):&lt;/strong&gt; Bernoulli mô tả một phép thử đơn \(X \in \{0, 1\}\), còn Binomial tổng hợp \(n\) phép thử độc lập cùng xác suất \(p\) bằng hệ số tổ hợp \(\binom{n}{k}\). Đây là bước chuyển từ dữ liệu chi tiết từng lần thử sang &lt;strong&gt;thống kê đủ&lt;/strong&gt; (&lt;em&gt;sufficient statistic&lt;/em&gt;) \((n, k)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm hợp lý (Likelihood Function):&lt;/strong&gt; Khi dữ liệu \((n, k)\) đã cố định, ta đọc biểu thức \(\binom{n}{k} p^k (1-p)^{n-k}\) như hàm theo tham số \(p\). Hệ số \(\binom{n}{k}\) không phụ thuộc \(p\) nên trở thành hằng số tỷ lệ trong công thức Bayes — chỉ còn lõi \(p^k (1-p)^{n-k}\) thực sự “kéo” hậu nghiệm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Prior liên hợp (Conjugate Priors):&lt;/strong&gt; Dạng lõi \(p^k (1-p)^{n-k}\) có cùng cấu trúc đại số với phân phối \(\text{Beta}(\alpha, \beta) \propto p^{\alpha-1}(1-p)^{\beta-1}\). Nhờ đó, cập nhật Bayes cho dữ liệu nhị phân chỉ quy về phép cộng số nguyên: \(\alpha_{\text{post}} = \alpha + k\) và \(\beta_{\text{post}} = \beta + (n - k)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-câu-chuyện-sinh-dữ-liệu-nhị-phân&quot;&gt;1) Câu chuyện sinh dữ liệu nhị phân&lt;/h2&gt;

&lt;p&gt;Nhiều bài toán dữ liệu bắt đầu từ một câu hỏi nhị phân, chẳng hạn một người dùng có nhấp chuột hay không, bệnh nhân có đáp ứng điều trị hay không, hay gói hàng có được giao đúng hẹn hay không. Vì mỗi quan sát chỉ nhận một trong hai trạng thái, biến ngẫu nhiên cơ bản để mô tả nó là phân phối Bernoulli:&lt;/p&gt;

\[X \sim \text{Bernoulli}(p), \quad P(X=1)=p,\; P(X=0)=1-p.\]

&lt;p&gt;Trong đó, \(p\) là xác suất thành công trong một phép thử.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/bernoulli_binary_outcomes.png&quot; alt=&quot;Bernoulli mô tả một lần thử nhị phân với hai kết quả có thể&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cách đọc hình: Biểu đồ minh họa phân phối Bernoulli cho một phép thử nhị phân với hai kết quả có thể (0 và 1). Chú ý độ cao hai cột biểu thị xác suất \(1-p\) và \(p\), với tổng luôn bằng 1.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-từ-bernoulli-sang-binomial&quot;&gt;2) Từ Bernoulli sang Binomial&lt;/h2&gt;

&lt;p&gt;Nếu lặp lại phép thử Bernoulli \(n\) lần độc lập với cùng xác suất thành công \(p\), tổng số lần thành công \(K\) sẽ tuân theo phân phối Binomial:&lt;/p&gt;

\[K \sim \text{Binomial}(n,p), \quad P(K=k)=\binom{n}{k}p^k(1-p)^{n-k}.\]

&lt;p&gt;Đây là bước chuyển quan trọng trong mô hình hóa: Bernoulli mô tả một quan sát nhị phân đơn lẻ, còn Binomial mô tả tổng số lần thành công sau nhiều phép thử cùng loại.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/binomial_success_count_distribution.png&quot; alt=&quot;Binomial đếm số lần thành công sau nhiều lần thử Bernoulli độc lập&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Trong hình minh họa này, ta dùng tham số \(n=12\) và \(p=0.35\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cách đọc biểu đồ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;binomial_success_count_distribution.png&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Trục ngang là số lần thành công \(k\) (từ \(0\) đến \(n\)), trục dọc là xác suất \(P(K=k)\).&lt;/li&gt;
  &lt;li&gt;Mỗi cột cho biết xác suất thu được đúng \(k\) lần thành công sau \(n\) phép thử.&lt;/li&gt;
  &lt;li&gt;Đỉnh phân phối thường nằm gần \(k\approx np\), nên khi \(p\) tăng thì khối lượng xác suất dịch sang phải.&lt;/li&gt;
  &lt;li&gt;Về trực giác, biểu đồ cho thấy ngay giá trị \(k\) nào dễ xảy ra nhất và mức độ phân tán quanh giá trị kỳ vọng.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;video-ngắn-từ-bernoulli-đến-binomialn-p&quot;&gt;Video ngắn: Từ Bernoulli đến Binomial(n, p)&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-02a-bernoulli-to-binomial.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 5 giây: từ một phép thử nhị phân sang phân phối Nhị thức n=4, hệ số tổ hợp C(n,k), ảnh hưởng của tham số p và kiểm chứng tổng xác suất bằng 1.&lt;/p&gt;

&lt;h2 id=&quot;3-hằng-số-chuẩn-hóa-trong-bernoulli-và-binomial&quot;&gt;3) Hằng số chuẩn hóa trong Bernoulli và Binomial&lt;/h2&gt;

&lt;p&gt;Với Bernoulli, hàm khối lượng xác suất (PMF) thường được viết gọn là:&lt;/p&gt;

\[P(X=x)=p^x(1-p)^{1-x},
\quad x\in\{0,1\}.\]

&lt;p&gt;Điều kiện để một phân phối rời rạc hợp lệ là tổng xác suất bằng 1:&lt;/p&gt;

\[\sum_{x\in\{0,1\}} p^x(1-p)^{1-x}
=(1-p)+p=1.\]

&lt;p&gt;Với Binomial:&lt;/p&gt;

\[P(K=k)=\binom{n}{k}p^k(1-p)^{n-k},\quad k=0,1,\dots,n.\]

&lt;p&gt;Hệ số tổ hợp \(\binom{n}{k}\) đếm số cách bố trí \(k\) lần thành công trong \(n\) phép thử. Nhờ hệ số này, tổng xác suất trên toàn bộ miền giá trị bằng đúng 1:&lt;/p&gt;

\[\sum_{k=0}^{n} \binom{n}{k}p^k(1-p)^{n-k}
=(p+1-p)^n=1.\]

&lt;p&gt;Nói ngắn gọn, cả PMF của Bernoulli lẫn Binomial đều đã được chuẩn hóa sẵn, không cần nhân thêm hằng số chuẩn hóa nào bên ngoài.&lt;/p&gt;

&lt;h2 id=&quot;4-ý-nghĩa-của-các-tham-số&quot;&gt;4) Ý nghĩa của các tham số&lt;/h2&gt;

&lt;p&gt;Trong mô hình Binomial, \(p\) biểu thị khả năng thành công của mỗi phép thử, \(n\) cho biết quy mô thí nghiệm (số phép thử), còn \(k\) là số lần thành công quan sát được. Hai đặc trưng tóm tắt quan trọng nhất của phân phối này là kỳ vọng và phương sai:&lt;/p&gt;

\[\mathbb{E}[K]=np, \qquad \mathrm{Var}(K)=np(1-p).\]

&lt;p&gt;Từ công thức trên có thể thấy hai thí nghiệm cùng kỳ vọng \(np\) nhưng khác \(p\) vẫn có thể có độ phân tán rất khác nhau.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-băng-chuyền-nhà-máy--vì-sao-binomial-có-hình-vòm&quot;&gt;Video ngắn: Băng chuyền Nhà máy &amp;amp; Vì sao Binomial có hình Vòm?&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-02c-binomial-where-and-shape.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 1 phút 8 giây (mô phỏng chuyển động liên tục, sẽ bổ sung thuyết minh): mô phỏng trực tiếp băng chuyền kiểm định chip (p = 0.3), lặp 60 lô hàng dựng biểu đồ Binomial, giải thích cuộc kéo co giữa C(n, k) với pᵏ(1−p)ⁿ⁻ᵏ và trượt mượt p từ 0.08 → 0.50 → 0.92.&lt;/p&gt;

&lt;h2 id=&quot;5-ví-dụ-thực-hành-ngắn&quot;&gt;5) Ví dụ thực hành ngắn&lt;/h2&gt;

&lt;p&gt;Giả sử một API có xác suất lỗi ở mỗi yêu cầu (request) là \(p=0.05\). Trong \(n=40\) yêu cầu độc lập, số yêu cầu lỗi \(K\) tuân theo phân phối Binomial. Khi đó, số lỗi kỳ vọng là \(\mathbb{E}[K]=40\times 0.05=2\), còn xác suất không có lỗi nào xảy ra là:&lt;/p&gt;

\[P(K=0)=(1-0.05)^{40}\approx 0.129.\]

&lt;p&gt;Như vậy, dù tỷ lệ lỗi chỉ là 5%, khả năng một lô 40 yêu cầu hoàn toàn không phát sinh lỗi chỉ vào khoảng 12.9%.&lt;/p&gt;

&lt;h3 id=&quot;51-cùng-kỳ-vọng-2-nhưng-độ-bất-định-khác-nhau&quot;&gt;5.1) Cùng kỳ vọng 2, nhưng độ bất định khác nhau&lt;/h3&gt;

&lt;p&gt;Xét hai tình huống sau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Một bài kiểm tra ngắn có 4 câu, mỗi câu trả lời đúng với xác suất \(0.5\).&lt;/li&gt;
  &lt;li&gt;Một chiến dịch email gửi đến 20 khách hàng, mỗi khách phản hồi với xác suất \(0.1\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cả hai đều có số thành công kỳ vọng bằng 2:&lt;/p&gt;

\[4 \times 0.5 = 2, \qquad 20 \times 0.1 = 2.\]

&lt;p&gt;Tuy nhiên, phương sai của chúng khác nhau:&lt;/p&gt;

\[4 \times 0.5 \times 0.5 = 1, \qquad 20 \times 0.1 \times 0.9 = 1.8.\]

&lt;p&gt;Dù cùng có trung bình 2 lần thành công, chiến dịch email có mức dao động lớn hơn rõ rệt. Vì vậy, chỉ nhìn kỳ vọng \(np\) là chưa đủ; cần xem thêm phương sai \(np(1-p)\) để đánh giá độ ổn định của kết quả.&lt;/p&gt;

&lt;h2 id=&quot;6-các-lỗi-mô-hình-hóa-thường-gặp&quot;&gt;6) Các lỗi mô hình hóa thường gặp&lt;/h2&gt;

&lt;p&gt;Ba sai lầm hay gặp khi dùng Binomial là: giả định \(p\) cố định dù thực tế xác suất thay đổi theo thời gian; giả định các phép thử độc lập dù dữ liệu phụ thuộc theo nhóm hoặc theo phiên truy cập; và đồng nhất tỷ lệ quan sát được với xác suất thật mà bỏ qua độ bất định. Trong những trường hợp này, cần mở rộng sang các mô hình có cấu trúc phù hợp hơn như mô hình phân cấp (hierarchical model), mô hình hỗn hợp (mixture model), hoặc hồi quy logistic có biến giải thích (covariate).&lt;/p&gt;

&lt;h2 id=&quot;7-liên-hệ-bayesian&quot;&gt;7) Liên hệ Bayesian&lt;/h2&gt;

&lt;p&gt;Trong thống kê Bayesian, ta thường đặt phân phối tiên nghiệm (prior) cho tham số \(p\) rồi cập nhật bằng dữ liệu Binomial. Cặp liên hợp phổ biến nhất là Beta–Binomial, sẽ được trình bày chi tiết ở Bài 0.5.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_02_02_poisson_exponential/&quot;&gt;0.3 Poisson và Exponential&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-từ-một-chuỗi-tung-xu-đến-cập-nhật-betabinomial-bằng-tay&quot;&gt;Giải thích: Từ một chuỗi tung xu đến cập nhật Beta–Binomial bằng tay&lt;/h2&gt;

&lt;p&gt;Nhiều bạn thắc mắc: &lt;em&gt;vì sao khi tính posterior cho Binomial ta được phép bỏ qua hệ số \(\binom{n}{k}\)?&lt;/em&gt; Hãy đi chậm qua 4 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Một chuỗi cụ thể vs. tổng số thành công:&lt;/strong&gt; Một chuỗi cố định gồm \(k\) mặt ngửa và \(n-k\) mặt sấp có xác suất đúng bằng \(p^k(1-p)^{n-k}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đếm số chuỗi có cùng \(k\):&lt;/strong&gt; Có đúng \(\binom{n}{k}\) cách sắp xếp \(k\) mặt ngửa vào \(n\) vị trí, nên \(P(X=k \mid p) = \binom{n}{k} p^k(1-p)^{n-k}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhân với prior \(\text{Beta}(\alpha, \beta)\):&lt;/strong&gt; Mật độ hậu nghiệm tỷ lệ với \(p^{\alpha-1}(1-p)^{\beta-1} \cdot p^k(1-p)^{n-k} = p^{(\alpha+k)-1}(1-p)^{(\beta+n-k)-1}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhận diện họ phân phối:&lt;/strong&gt; Biểu thức trên chính là lõi của \(\text{Beta}(\alpha+k, \beta+n-k)\), nên mọi hằng số không chứa \(p\) (kể cả \(\binom{n}{k}\)) tự động triệt tiêu khi chuẩn hóa!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-đánh-giá-tỷ-lệ-chuyển-đổi-landing-page&quot;&gt;Ví dụ tính toán làm từng bước: Đánh giá tỷ lệ chuyển đổi landing page&lt;/h3&gt;

&lt;p&gt;Một sản phẩm mới chưa có dữ liệu, nên bạn đặt prior không thiên vị \(\text{Beta}(2, 2)\) (trung bình tiên nghiệm \(\frac{2}{2+2} = 0.50\), tương đương 4 lượt thử ảo: 2 thành công, 2 thất bại). Sau ngày đầu chạy thử với \(n = 10\) khách truy cập, có \(k = 3\) người mua hàng.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Likelihood tại hai mốc thử \(p=0.3\) và \(p=0.5\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Tại \(p=0.3\): \(L(0.3) = \binom{10}{3} (0.3)^3 (0.7)^7 = 120 \times 0.027 \times 0.0823543 \approx 0.2668\).&lt;/li&gt;
      &lt;li&gt;Tại \(p=0.5\): \(L(0.5) = 120 \times (0.5)^{10} = 120 / 1024 \approx 0.1172\).&lt;/li&gt;
      &lt;li&gt;Dữ liệu ủng hộ \(p=0.3\) mạnh hơn \(p=0.5\) khoảng \(0.2668 / 0.1172 \approx 2.28\) lần.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Cập nhật hậu nghiệm liên hợp:&lt;/strong&gt;
\(\alpha_{\text{post}} = 2 + 3 = 5, \qquad \beta_{\text{post}} = 2 + (10 - 3) = 9 \implies p \mid \text{data} \sim \text{Beta}(5, 9).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Tóm tắt hậu nghiệm tính tay:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Trung bình hậu nghiệm: \(\mathbb{E}[p \mid \text{data}] = \frac{5}{5 + 9} = \frac{5}{14} \approx 0.3571\) (bị “kéo co” giữa prior \(0.50\) và tỷ lệ mẫu \(0.30\)).&lt;/li&gt;
      &lt;li&gt;Mode (MAP): \(\frac{5 - 1}{5 + 9 - 2} = \frac{4}{12} \approx 0.3333\).&lt;/li&gt;
      &lt;li&gt;Độ lệch chuẩn hậu nghiệm: \(\sqrt{\frac{5 \times 9}{14^2 \times 15}} = \sqrt{\frac{45}{2940}} \approx 0.1237\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Dùng Binomial khi các phép thử có xác suất \(p\) thay đổi giữa các nhóm khách hàng hoặc phụ thuộc lẫn nhau (ví dụ hiệu ứng lan truyền mạng xã hội); khi đó phương sai thực tế lớn hơn \(np(1-p)\) (&lt;em&gt;overdispersion&lt;/em&gt;) và ta cần mô hình phân cấp Beta–Binomial.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu hôm sau có thêm 10 khách nữa với 2 người mua, hậu nghiệm mới là \(\text{Beta}(5+2, 9+8) = \text{Beta}(7, 17)\), trùng khớp hoàn toàn với việc gộp chung 20 khách, 5 người mua ngay từ đầu!&lt;/p&gt;

&lt;hr /&gt;

&lt;h4 id=&quot;video-ngắn-landing-page--cập-nhật-betabinomial&quot;&gt;Video ngắn: Landing Page &amp;amp; Cập nhật Beta–Binomial&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-02b-beta-binomial-landing.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 2 giây: so sánh cùng kỳ vọng 2 với cỡ mẫu khác nhau, cập nhật từ Beta(2,8) qua dữ liệu 6/20 và 56/200, tính bất biến thứ tự và khoảng tin cậy Bayes 95%.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Tc6g-Y-l0Rg&quot;&gt;Bernoulli and Binomial Random Variables&lt;/a&gt; — Steve Brunton, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giúp tách bạch một phép thử nhị phân với tổng số lần thành công trên nhiều phép thử.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=J8jNoF-K8E8&quot;&gt;The Binomial Distribution and Test, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Minh họa ví dụ đếm số lần thành công và công thức tổ hợp, hỗ trợ cách diễn giải tham số theo dữ liệu thực tế.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Binomial distributions&lt;/td&gt;
          &lt;td&gt;Probabilities of probabilities, part 1](https://www.youtube.com/watch?v=8idr1WZ1A7Q) — 3Blue1Brown, English. Cho thấy Binomial như một mô hình sinh dữ liệu nhị phân lặp lại, làm cầu nối sang các bài suy diễn Bayesian phía sau.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Bài 0.1: Nền tảng Xác suất - Ngôn ngữ của Sự Không chắc chắn</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_01_probability_basics/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/vi/chapter00/00_01_probability_basics</id>
   <content type="html">&lt;p&gt;Năm 1654, một quý tộc Pháp mê cờ bạc tên Chevalier de Méré viết thư cầu cứu Blaise Pascal về một câu đố tưởng chừng vụn vặt: nếu một ván xúc xắc buộc phải dừng giữa chừng, nên chia tiền cược thế nào cho công bằng? Từ bức thư ấy — và chuỗi thư trao đổi giữa Pascal với Pierre de Fermat — lý thuyết xác suất hiện đại ra đời. Ba thế kỷ sau, xác suất không còn là chuyện của sòng bạc: nó trở thành ngôn ngữ định lượng duy nhất giúp bác sĩ diễn giải xét nghiệm dương tính, kỹ sư máy học ước lượng bất định của mô hình, và nhà thống kê Bayes biến dữ liệu rời rạc thành tri thức có cấu trúc.&lt;/p&gt;

&lt;p&gt;Trong bài mở đầu này, ta không chỉ nhắc lại các tiên đề Kolmogorov như những định luật khô khan, mà nhìn chúng như &lt;strong&gt;bộ quy tắc kế toán của niềm tin hợp lý&lt;/strong&gt; — nền móng trực tiếp dẫn tới công thức Bayes và toàn bộ quy trình cập nhật prior–likelihood–posterior.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu Học tập&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành bài học này, bạn sẽ hiểu xác suất không chỉ là tập hợp các công thức tính toán mà là một ngôn ngữ toán học hoàn chỉnh để mô tả, định lượng và suy luận về sự không chắc chắn. Bạn sẽ nắm vững các khái niệm cơ bản về không gian mẫu, biến cố và các quy tắc xác suất, đồng thời thấy rõ vì sao chúng là nền tảng của suy diễn Bayesian. Quan trọng hơn, bạn sẽ tiếp cận xác suất như một cách mã hóa mức độ tin tưởng và cập nhật niềm tin đó khi có thêm thông tin mới.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-lý-thuyết-độ-đo-xác-suất-có-điều-kiện-và-suy-diễn-bayes-gặp-nhau-ở-đâu&quot;&gt;Kiến thức cần nhớ: Lý thuyết độ đo, Xác suất có điều kiện và Suy diễn Bayes gặp nhau ở đâu?&lt;/h2&gt;

&lt;p&gt;Với người học đã qua chương trình đại học, câu hỏi quan trọng nhất là: &lt;em&gt;xác suất cơ bản liên quan gì đến các phương pháp hiện đại như MCMC hay suy diễn biến phân (Variational Inference)?&lt;/em&gt; Bức tranh tổng thể tựa trên ba trụ cột:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết xác suất tiên đề (Axiomatic Probability):&lt;/strong&gt; Xây dựng trên không gian mẫu \(\Omega\), hệ biến cố và hàm độ đo xác suất \(P\) thỏa mãn ba tiên đề Kolmogorov (không âm, chuẩn hóa bằng 1, cộng tính). Đây là “luật giao thông” đảm bảo mọi phép tính niềm tin đều nhất quán và không tự mâu thuẫn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất có điều kiện &amp;amp; Độc lập có điều kiện:&lt;/strong&gt; Nghiên cứu cách không gian mẫu co lại khi có bằng chứng mới. Trong thống kê Bayes, khái niệm &lt;strong&gt;độc lập có điều kiện&lt;/strong&gt; (các quan sát \(y_1, \ldots, y_n\) độc lập khi biết tham số \(\theta\)) chính là lý do ta có thể nhân các likelihood riêng lẻ thành tích \(\prod_i p(y_i \mid \theta)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối sang Thống kê Bayes:&lt;/strong&gt; Định lý Bayes không phải là một tiên đề mới, mà là hệ quả đại số trực tiếp của định nghĩa xác suất có điều kiện \(P(A \cap B) = P(A \mid B)P(B) = P(B \mid A)P(A)\). Từ đây, mọi mô hình Bayes — dù đơn giản như Beta–Binomial hay phức tạp đến mức phải dùng MCMC — đều chỉ là bài toán chuẩn hóa một tích &lt;em&gt;prior × likelihood&lt;/em&gt; sao cho tổng (hoặc tích phân) bằng 1.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-tại-sao-chúng-ta-cần-xác-suất&quot;&gt;Giới thiệu: Tại sao chúng ta cần Xác suất?&lt;/h2&gt;

&lt;p&gt;Trong thực tế, chúng ta hiếm khi có thông tin hoàn hảo. Một bác sĩ chẩn đoán bệnh từ những triệu chứng chưa rõ ràng; một nhà khoa học tìm cách suy ra quy luật tự nhiên từ dữ liệu có nhiễu; một kỹ sư thiết kế hệ thống sao cho vẫn vận hành ổn định khi điều kiện môi trường biến động khó lường. Trong mọi tình huống như vậy, sự không chắc chắn không phải là phiền toái cần gạt bỏ, mà là đặc tính vốn có của bài toán cần được mô hình hóa và xử lý một cách có nguyên tắc.&lt;/p&gt;

&lt;p&gt;Xác suất cung cấp ngôn ngữ toán học cho việc này. Nó cho phép chúng ta &lt;strong&gt;định lượng mức độ tin tưởng&lt;/strong&gt; vào các mệnh đề khác nhau, kết hợp thông tin từ nhiều nguồn và đưa ra quyết định hợp lý ngay cả khi chưa biết chắc kết quả. &lt;strong&gt;Trong khóa học phân tích dữ liệu Bayesian này, xác suất không chỉ là công cụ tính toán mà còn là cách tư duy về dữ liệu, mô hình và suy luận.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Trước khi áp dụng xác suất vào suy diễn Bayesian, chúng ta cần nắm chắc các khái niệm nền tảng. Bài học này trình bày từng khái niệm cơ bản một cách hệ thống, giúp bạn vừa tính toán được xác suất vừa hiểu rõ ý nghĩa của các con số đó trong suy luận thống kê.&lt;/p&gt;

&lt;h2 id=&quot;không-gian-mẫu-và-biến-cố-mô-tả-những-gì-có-thể-xảy-ra&quot;&gt;Không gian Mẫu và Biến cố: Mô tả những gì có thể xảy ra&lt;/h2&gt;

&lt;p&gt;Mọi phân tích xác suất đều bắt đầu từ việc xác định rõ những kết quả nào có thể xảy ra. Tập hợp tất cả các kết quả có thể có của một thí nghiệm hay quá trình ngẫu nhiên được gọi là &lt;strong&gt;không gian mẫu&lt;/strong&gt; (sample space), thường ký hiệu là \(\Omega\). Mỗi phần tử của không gian mẫu biểu diễn một kết quả cụ thể, đầy đủ và phân biệt được với các kết quả khác.&lt;/p&gt;

&lt;p&gt;Xét ví dụ đơn giản: tung một đồng xu công bằng. Không gian mẫu là \(\Omega = \{\text{Sấp}, \text{Ngửa}\}\). Ở mỗi lần tung, ta quan sát được một trong hai mặt này và không có kết quả nào khác. Dù rất đơn giản, ví dụ này cho thấy một điểm cốt lõi: xác định đúng không gian mẫu luôn là bước đầu tiên và quan trọng nhất của mọi phân tích xác suất.&lt;/p&gt;

&lt;p&gt;Trong thực tế, không gian mẫu thường phức tạp hơn nhiều. Nếu tung đồng xu hai lần, không gian mẫu là \(\Omega = \{SS, SN, NS, NN\}\), trong đó \(S\) là Sấp và \(N\) là Ngửa. Nếu đo chiều cao của một người được chọn ngẫu nhiên, không gian mẫu là tập hợp các số thực dương có thể có (trong thực tế nằm trong giới hạn sinh học); đây là không gian liên tục chứ không phải rời rạc.&lt;/p&gt;

&lt;p&gt;Khi đã có không gian mẫu, ta định nghĩa &lt;strong&gt;biến cố&lt;/strong&gt; (event) là một tập hợp con của không gian mẫu, đại diện cho nhóm kết quả ta quan tâm. Ví dụ, khi tung đồng xu hai lần, biến cố “ít nhất một lần ra Sấp” là tập hợp \(\{SS, SN, NS\}\), còn biến cố “cả hai lần đều ra Sấp” là tập hợp \(\{SS\}\).&lt;/p&gt;

&lt;p&gt;Định nghĩa biến cố như tập hợp con của không gian mẫu nghe có vẻ trừu tượng, nhưng nhờ đó ta có thể dùng lý thuyết tập hợp để suy luận về xác suất: hợp của hai biến cố (ít nhất một trong hai xảy ra), giao của hai biến cố (cả hai cùng xảy ra) và phần bù của một biến cố (biến cố đó không xảy ra). Các phép toán tập hợp này tương ứng trực tiếp với các quy tắc xác suất dưới đây.&lt;/p&gt;

&lt;h2 id=&quot;định-nghĩa-xác-suất-từ-tần-suất-đến-niềm-tin&quot;&gt;Định nghĩa Xác suất: Từ Tần suất đến Niềm tin&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Có nhiều cách hiểu về bản chất của xác suất&lt;/strong&gt;, và cách hiểu đó ảnh hưởng trực tiếp đến cách chúng ta áp dụng nó. Trong khóa học này, ta chủ yếu làm việc theo &lt;strong&gt;quan điểm Bayesian&lt;/strong&gt;, nhưng trước hết hãy điểm qua &lt;strong&gt;quan điểm tần suất (frequentist)&lt;/strong&gt; truyền thống để thấy rõ sự khác biệt.&lt;/p&gt;

&lt;p&gt;Theo quan điểm tần suất, xác suất của một biến cố là tần suất tương đối mà biến cố đó xảy ra khi lặp lại thí nghiệm vô số lần trong điều kiện như nhau. Khi tung một đồng xu công bằng nhiều lần, tỷ lệ lần ra Sấp sẽ tiến gần đến \(0.5\) khi số lần tung tăng lên. &lt;strong&gt;Định nghĩa này khách quan và dễ hiểu, nhưng có một hạn chế lớn: nó chỉ áp dụng được cho những hiện tượng có thể lặp lại nhiều lần. Ta không thể nói về “xác suất ngày mai trời mưa” hay “xác suất một giả thuyết khoa học là đúng” theo nghĩa tần suất, vì những sự kiện này không thể lặp lại trong điều kiện giống hệt nhau.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quan điểm Bayesian về xác suất&lt;/strong&gt; rộng và linh hoạt hơn. Theo cách hiểu này, xác suất là thước đo &lt;strong&gt;mức độ tin tưởng&lt;/strong&gt; (degree of belief) hay &lt;strong&gt;độ hợp lý&lt;/strong&gt; (plausibility) của một mệnh đề dựa trên thông tin hiện có. Xác suất bằng \(0\) biểu thị sự chắc chắn rằng mệnh đề sai, xác suất bằng \(1\) biểu thị sự chắc chắn rằng mệnh đề đúng, còn các giá trị nằm giữa phản ánh những mức độ không chắc chắn khác nhau. Quan trọng là &lt;strong&gt;xác suất Bayesian thay đổi khi có thêm thông tin mới, và đây chính là nền tảng của suy diễn Bayesian.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Dù hiểu xác suất theo quan điểm nào, nó vẫn phải tuân theo một số quy tắc toán học cơ bản để bảo đảm tính nhất quán. Các quy tắc này được gọi là các tiên đề xác suất (probability axioms) và là cơ sở của toàn bộ lý thuyết xác suất.&lt;/p&gt;

&lt;h2 id=&quot;các-tiên-đề-xác-suất-quy-tắc-của-trò-chơi&quot;&gt;Các Tiên đề Xác suất: Quy tắc của Trò chơi&lt;/h2&gt;

&lt;p&gt;Để xác suất trở thành một công cụ toán học chặt chẽ, nó phải thỏa mãn một số quy tắc nền tảng. Các quy tắc này do nhà toán học Nga Andrey Kolmogorov hệ thống hóa vào năm 1933, xác định những gì hợp lệ và không hợp lệ khi thao tác với xác suất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tiên đề 1: Tính không âm (Non-negativity).&lt;/strong&gt; Xác suất của mọi biến cố đều không âm: với mọi biến cố \(A\), ta có \(P(A) \geq 0\). Về mặt trực giác, không thể tồn tại “xác suất âm”; xác suất bằng \(0\) ứng với trường hợp biến cố chắc chắn không xảy ra.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tiên đề 2: Tính chuẩn hóa (Normalization).&lt;/strong&gt; Xác suất của toàn bộ không gian mẫu bằng \(1\), tức \(P(\Omega) = 1\). Điều này phản ánh thực tế rằng chắc chắn &lt;em&gt;một kết quả nào đó&lt;/em&gt; trong không gian mẫu sẽ xảy ra, dù ta chưa biết cụ thể là kết quả nào.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tiên đề 3: Tính cộng (Additivity).&lt;/strong&gt; Nếu hai biến cố \(A\) và \(B\) &lt;strong&gt;xung khắc&lt;/strong&gt; (mutually exclusive), tức không thể cùng xảy ra (\(A \cap B = \emptyset\)), thì xác suất của hợp hai biến cố bằng tổng các xác suất riêng lẻ: \(P(A \cup B) = P(A) + P(B)\). Quy tắc này mở rộng cho mọi họ hữu hạn hoặc đếm được các biến cố đôi một xung khắc.&lt;/p&gt;

&lt;p&gt;Ba tiên đề này tuy ngắn gọn nhưng tạo ra nhiều hệ quả quan trọng, từ đó suy ra toàn bộ các quy tắc tính xác suất khác. Chẳng hạn, xác suất của biến cố bù \(A^c\) (biến cố \(A\) không xảy ra) là \(P(A^c) = 1 - P(A)\), vì \(A\) và \(A^c\) xung khắc và hợp của chúng là toàn bộ không gian mẫu, nên \(P(A) + P(A^c) = P(\Omega) = 1\).&lt;/p&gt;

&lt;p&gt;Một hệ quả quan trọng khác là &lt;strong&gt;quy tắc cộng tổng quát&lt;/strong&gt; cho hai biến cố bất kỳ (không nhất thiết xung khắc):&lt;/p&gt;

\[P(A \cup B) = P(A) + P(B) - P(A \cap B)\]

&lt;p&gt;Ta phải trừ đi \(P(A \cap B)\) để tránh đếm hai lần những kết quả thuộc cả \(A\) lẫn \(B\). Công thức này tương ứng với nguyên lý bao hàm - loại trừ (inclusion-exclusion principle) trong lý thuyết tập hợp, thể hiện mối liên hệ chặt chẽ giữa xác suất và lý thuyết tập hợp.&lt;/p&gt;

&lt;h3 id=&quot;video-ngắn-không-gian-mẫu--tiên-đề-kolmogorov&quot;&gt;Video ngắn: Không gian mẫu &amp;amp; Tiên đề Kolmogorov&lt;/h3&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-01a-sample-space-kolmogorov.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 20 giây: trực quan hóa không gian mẫu Ω = {1..6}, ba tiên đề Kolmogorov, quy tắc cộng giao nhau, phần bù, tính độc lập và xác suất toàn phần.&lt;/p&gt;

&lt;h2 id=&quot;xác-suất-có-điều-kiện-cập-nhật-niềm-tin-với-thông-tin-mới&quot;&gt;Xác suất Có điều kiện: Cập nhật Niềm tin với Thông tin Mới&lt;/h2&gt;

&lt;p&gt;Một trong những khái niệm trung tâm của lý thuyết xác suất — và đặc biệt quan trọng đối với suy diễn Bayesian — là &lt;strong&gt;xác suất có điều kiện&lt;/strong&gt; (conditional probability). Đây là xác suất của một biến cố khi ta đã biết một biến cố khác xảy ra.&lt;/p&gt;

&lt;p&gt;Giả sử ta quan tâm đến xác suất của biến cố \(A\), nhưng đã biết biến cố \(B\) xảy ra. Thông tin này làm thay đổi đánh giá của ta về khả năng xảy ra của \(A\) như thế nào? Xác suất có điều kiện của \(A\) khi biết \(B\), ký hiệu là \(P(A \mid B)\), được định nghĩa là:&lt;/p&gt;

\[P(A \mid B) = \frac{P(A \cap B)}{P(B)}\]

&lt;p&gt;với điều kiện \(P(B) &amp;gt; 0\).&lt;/p&gt;

&lt;p&gt;Định nghĩa này có ý nghĩa trực quan rõ ràng. Khi biết \(B\) đã xảy ra, không gian các kết quả có thể bị thu hẹp lại chỉ còn các phần tử thuộc \(B\). Trong không gian thu hẹp đó, xác suất của \(A\) tỷ lệ với xác suất cả \(A\) và \(B\) cùng xảy ra, rồi chia cho \(P(B)\) để chuẩn hóa sao cho tổng xác suất trong không gian mới vẫn bằng \(1\).&lt;/p&gt;

&lt;p&gt;Xét một ví dụ cụ thể: tung một đồng xu công bằng hai lần. Không gian mẫu là \(\{SS, SN, NS, NN\}\), mỗi kết quả có xác suất \(1/4\). Xác suất của biến cố “cả hai lần đều ra Sấp” (\(A = \{SS\}\)) là \(P(A) = 1/4\). Tuy nhiên, nếu biết thêm rằng “ít nhất một lần ra Sấp” (\(B = \{SS, SN, NS\}\)), xác suất có điều kiện của \(A\) khi biết \(B\) trở thành:&lt;/p&gt;

\[P(A \mid B) = \frac{P(A \cap B)}{P(B)} = \frac{P(\{SS\})}{P(\{SS, SN, NS\})} = \frac{1/4}{3/4} = \frac{1}{3}\]

&lt;p&gt;Xác suất tăng từ \(1/4\) lên \(1/3\) khi có thêm thông tin. Đây là ví dụ đơn giản về việc cập nhật niềm tin theo bằng chứng mới — ý tưởng cốt lõi của suy diễn Bayesian.&lt;/p&gt;

&lt;h3 id=&quot;một-biến-thể-rất-dễ-nhầm&quot;&gt;Một biến thể rất dễ nhầm&lt;/h3&gt;

&lt;p&gt;Vẫn với hai lần tung đồng xu, hãy so sánh hai điều kiện khác nhau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Nếu biết &lt;strong&gt;ít nhất một lần ra Sấp&lt;/strong&gt;, xác suất cả hai lần đều Sấp là \(1/3\).&lt;/li&gt;
  &lt;li&gt;Nếu biết &lt;strong&gt;lần tung đầu tiên ra Sấp&lt;/strong&gt;, xác suất cả hai lần đều Sấp là \(1/2\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hai phát biểu nghe tương đối giống nhau, nhưng thông tin điều kiện khác nhau dẫn đến xác suất có điều kiện khác nhau. Điểm cần nhớ là trong xác suất, ý nghĩa của việc “biết thêm thông tin” phụ thuộc hoàn toàn vào việc biến cố điều kiện đã loại bỏ những khả năng nào khỏi không gian mẫu.&lt;/p&gt;

&lt;p&gt;Từ định nghĩa xác suất có điều kiện, ta suy ra &lt;strong&gt;quy tắc nhân&lt;/strong&gt; (multiplication rule):&lt;/p&gt;

\[P(A \cap B) = P(A \mid B) \cdot P(B) = P(B \mid A) \cdot P(A)\]

&lt;p&gt;Quy tắc này cho hai cách tương đương để tính xác suất giao của hai biến cố, và chính sự tương đương này dẫn trực tiếp đến định lý Bayes.&lt;/p&gt;

&lt;h2 id=&quot;độc-lập-khi-thông-tin-không-thay-đổi-niềm-tin&quot;&gt;Độc lập: Khi Thông tin Không thay đổi Niềm tin&lt;/h2&gt;

&lt;p&gt;Hai biến cố \(A\) và \(B\) được gọi là &lt;strong&gt;độc lập&lt;/strong&gt; (independent) nếu việc biết một biến cố xảy ra không làm thay đổi xác suất của biến cố kia. Một cách hình thức, \(A\) và \(B\) độc lập khi và chỉ khi:&lt;/p&gt;

\[P(A \mid B) = P(A)\]

&lt;p&gt;hoặc tương đương:&lt;/p&gt;

\[P(A \cap B) = P(A) \cdot P(B)\]

&lt;p&gt;Độc lập là một giả định mạnh và thường không hoàn toàn đúng ngoài thực tế, nhưng nó giúp đơn giản hóa đáng kể việc tính toán và làm nền tảng cho nhiều mô hình thống kê. Chẳng hạn, khi tung đồng xu nhiều lần, ta thường giả định các lần tung độc lập với nhau, tức kết quả của một lần tung không ảnh hưởng đến xác suất của các lần tung tiếp theo.&lt;/p&gt;

&lt;p&gt;Ngược lại, nhiều tình huống thực tế không có tính độc lập. Nếu rút hai lá bài từ một bộ bài mà không hoàn lại, kết quả lần rút thứ hai phụ thuộc vào lần rút thứ nhất. Nếu quan sát nhiệt độ trong hai ngày liên tiếp, hai giá trị thường tương quan với nhau. Nhận diện và mô hình hóa các mối phụ thuộc như vậy là một phần quan trọng của phân tích dữ liệu Bayesian.&lt;/p&gt;

&lt;h2 id=&quot;độc-lập-có-điều-kiện-khi-biết-biến-ẩn-thì-phụ-thuộc-biến-mất&quot;&gt;Độc lập có điều kiện: Khi biết biến ẩn thì phụ thuộc biến mất&lt;/h2&gt;

&lt;p&gt;Có một tình huống tinh tế hơn độc lập thông thường: hai biến cố có thể &lt;strong&gt;không độc lập khi xét tổng thể&lt;/strong&gt;, nhưng lại trở nên độc lập khi ta biết thêm một biến ẩn \(C\). Ta nói \(A\) và \(B\) &lt;strong&gt;độc lập có điều kiện theo \(C\)&lt;/strong&gt; nếu:&lt;/p&gt;

\[P(A \cap B \mid C) = P(A \mid C)P(B \mid C).\]

&lt;p&gt;Về mặt trực giác, khi chưa biết \(C\), ta đang gộp chung nhiều cơ chế sinh dữ liệu khác nhau vào cùng một bức tranh; khi đã biết \(C\), ta xác định rõ mình đang ở cơ chế nào, và bên trong từng cơ chế riêng lẻ đó, \(A\) và \(B\) có thể không còn ảnh hưởng lẫn nhau nữa.&lt;/p&gt;

&lt;p&gt;Ví dụ, giả sử ta chọn ngẫu nhiên một trong hai đồng xu: đồng xu thứ nhất công bằng, còn đồng xu thứ hai luôn ra Ngửa. Sau đó ta tung đồng xu đã chọn hai lần. Gọi \(C\) là biến cố “đã chọn đồng xu 1”, \(A\) là biến cố “lần tung thứ nhất ra Ngửa”, và \(B\) là biến cố “lần tung thứ hai ra Ngửa”. Nếu &lt;strong&gt;biết trước đã chọn đồng xu nào&lt;/strong&gt;, hai lần tung là độc lập có điều kiện: với đồng xu công bằng, mỗi lần tung độc lập với xác suất ra Ngửa bằng \(1/2\); với đồng xu luôn ra Ngửa, hai lần tung vẫn độc lập theo nghĩa cả hai đều chắc chắn ra Ngửa. Nhưng nếu &lt;strong&gt;không biết&lt;/strong&gt; đã chọn đồng xu nào, \(A\) và \(B\) không còn độc lập theo nghĩa thông thường, vì kết quả lần tung đầu tiết lộ thông tin về loại đồng xu đang dùng và từ đó làm thay đổi đánh giá về lần tung thứ hai.&lt;/p&gt;

&lt;p&gt;Đây là một ý tưởng quan trọng trong thống kê Bayesian: sự phụ thuộc không nhất thiết xuất phát từ việc hai biến tác động trực tiếp lên nhau; đôi khi nó chỉ xuất hiện vì ta chưa biết một biến ẩn đang đồng thời chi phối cả hai. Bạn sẽ gặp lại cơ chế này thường xuyên khi học mô hình hỗn hợp, mô hình phân cấp và đồ thị nhân quả.&lt;/p&gt;

&lt;h2 id=&quot;quy-tắc-xác-suất-toàn-phần-chia-để-tính&quot;&gt;Quy tắc Xác suất Toàn phần: Chia để Tính&lt;/h2&gt;

&lt;p&gt;Đôi khi cách thuận tiện nhất để tính xác suất của một biến cố là tách bài toán thành các trường hợp đơn giản hơn. &lt;strong&gt;Quy tắc xác suất toàn phần&lt;/strong&gt; (law of total probability) cho phép thực hiện việc này một cách có hệ thống.&lt;/p&gt;

&lt;p&gt;Giả sử không gian mẫu được phân hoạch thành các biến cố đôi một xung khắc \(B_1, B_2, \ldots, B_n\) sao cho \(\bigcup_{i=1}^n B_i = \Omega\), nghĩa là mỗi kết quả có thể thuộc về đúng một biến cố \(B_i\). Khi đó, xác suất của một biến cố \(A\) bất kỳ được tính bằng:&lt;/p&gt;

\[P(A) = \sum_{i=1}^n P(A \mid B_i) \cdot P(B_i)\]

&lt;p&gt;Công thức này cho biết để tính \(P(A)\), ta xét từng trường hợp \(B_i\), lấy xác suất của \(A\) trong trường hợp đó (\(P(A \mid B_i)\)) nhân với xác suất xảy ra trường hợp đó (\(P(B_i)\)), rồi cộng toàn bộ lại.&lt;/p&gt;

&lt;p&gt;Quy tắc này đặc biệt hữu ích trong các mô hình phân cấp có &lt;strong&gt;biến tiềm ẩn (latent variables)&lt;/strong&gt; không quan sát trực tiếp được. Trong suy diễn Bayesian, ta thường dùng quy tắc xác suất toàn phần để biên hóa (marginalize) — tức lấy tổng hoặc tích phân nhằm loại bỏ các tham số không trực tiếp quan tâm và tập trung vào đại lượng cần suy luận.&lt;/p&gt;

&lt;h2 id=&quot;ý-nghĩa-cho-suy-diễn-bayesian&quot;&gt;Ý nghĩa cho Suy diễn Bayesian&lt;/h2&gt;

&lt;p&gt;Các khái niệm trong bài học này không chỉ là phần mở đầu lý thuyết mà là khung xương trực tiếp của phân tích dữ liệu Bayesian. &lt;strong&gt;Trong suy diễn Bayesian, ta dùng xác suất có điều kiện để cập nhật niềm tin về tham số mô hình khi quan sát dữ liệu, dùng quy tắc xác suất toàn phần để biên hóa các tham số phiền nhiễu (nuisance parameters), và dựa vào các tiên đề xác suất để bảo đảm mọi suy luận đều nhất quán.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Hơn nữa, việc nhìn nhận xác suất như &lt;strong&gt;mức độ tin tưởng&lt;/strong&gt; cho phép ta phát biểu trực tiếp về “xác suất của một giả thuyết” hay “xác suất của một giá trị tham số” — những phát biểu không hợp lệ trong khuôn khổ tần suất nhưng lại tự nhiên và hữu ích trong thống kê Bayesian.&lt;/p&gt;

&lt;p&gt;Trong các bài học tiếp theo, mọi công cụ Bayesian — từ định lý Bayes cơ bản đến các mô hình phân cấp phức tạp — đều được xây dựng từ những nguyên tắc này. Nắm chắc nền tảng ngay từ đầu sẽ giúp bạn áp dụng phương pháp đúng chỗ, đồng thời hiểu rõ vì sao một mô hình hoạt động tốt hoặc gặp hạn chế.&lt;/p&gt;

&lt;h2 id=&quot;giải-thích-từ-bảng-tần-suất-22-đến-quy-tắc-cập-nhật-bayes&quot;&gt;Giải thích: Từ bảng tần suất 2×2 đến quy tắc cập nhật Bayes&lt;/h2&gt;

&lt;p&gt;Người học thường thuộc lòng công thức \(P(A \mid B) = \frac{P(B \mid A)P(A)}{P(B)}\) nhưng vẫn bị “đứng hình” khi mẫu số \(P(B)\) bị ẩn đi. Hãy đọc chậm chuỗi bốn bước sau để thấy mọi bài toán Bayes thực chất chỉ là &lt;strong&gt;cắt lát không gian mẫu&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bắt đầu từ xác suất tiên nghiệm (Prior):&lt;/strong&gt; Trước khi thấy bằng chứng \(B\), toàn bộ không gian mẫu được chia theo các giả thuyết \(A\) và \(A^c\) với tỷ lệ \(P(A)\) và \(P(A^c)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đưa bằng chứng qua hàm hợp lý (Likelihood):&lt;/strong&gt; Trong từng lát cắt, ta hỏi dữ liệu \(B\) có khả năng xuất hiện bao nhiêu: \(P(B \mid A)\) và \(P(B \mid A^c)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính xác suất đồng thời (Joint):&lt;/strong&gt; Nhân diện tích lát cắt với độ hợp lý để có khối lượng đồng thời \(P(A \cap B)\) và \(P(A^c \cap B)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa trên đúng lát cắt \(B\) (Posterior):&lt;/strong&gt; Bỏ toàn bộ phần không xảy ra \(B\), rồi chia mỗi phần cho tổng \(P(B) = P(A \cap B) + P(A^c \cap B)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tính-toán-làm-từng-bước-xét-nghiệm-sàng-lọc-trên-10000-người&quot;&gt;Ví dụ tính toán làm từng bước: Xét nghiệm sàng lọc trên 10.000 người&lt;/h3&gt;

&lt;p&gt;Giả sử một căn bệnh hiếm có tỷ lệ lưu hành \(P(D) = 0.01\) (1%). Một bộ xét nghiệm có độ nhạy \(P(+ \mid D) = 0.95\) và tỷ lệ dương tính giả \(P(+ \mid D^c) = 0.05\). Bạn nhận kết quả dương tính (\(+\)). Xác suất thực sự mắc bệnh \(P(D \mid +)\) là bao nhiêu?&lt;/p&gt;

&lt;p&gt;Hãy tính tay bằng &lt;strong&gt;quy đổi trên 10.000 người&lt;/strong&gt; (cách trực quan nhất để kiểm tra lại công thức):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Trạng thái&lt;/th&gt;
      &lt;th&gt;Tổng số người&lt;/th&gt;
      &lt;th&gt;Kết quả Dương tính (\(+\))&lt;/th&gt;
      &lt;th&gt;Kết quả Âm tính (\(-\))&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Mắc bệnh (\(D\))&lt;/td&gt;
      &lt;td&gt;\(10\,000 \times 0.01 = 100\)&lt;/td&gt;
      &lt;td&gt;\(100 \times 0.95 = 95\)&lt;/td&gt;
      &lt;td&gt;\(100 - 95 = 5\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Không bệnh (\(D^c\))&lt;/td&gt;
      &lt;td&gt;\(10\,000 \times 0.99 = 9\,900\)&lt;/td&gt;
      &lt;td&gt;\(9\,900 \times 0.05 = 495\)&lt;/td&gt;
      &lt;td&gt;\(9\,900 - 495 = 9\,405\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Tổng cộng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(10\,000\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(95 + 495 = 590\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;\(5 + 9\,405 = 9\,410\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Bây giờ chỉ nhìn vào cột Dương tính (\(590\) người):&lt;/p&gt;

\[P(D \mid +) = \frac{95}{590} \approx 0.1610 \quad (16.1\%)\]

&lt;p&gt;Kiểm tra lại bằng công thức Bayes:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tử số (prior × likelihood): \(0.01 \times 0.95 = 0.0095\).&lt;/li&gt;
  &lt;li&gt;Mẫu số (bằng chứng toàn phần): \(0.0095 + 0.99 \times 0.05 = 0.0095 + 0.0495 = 0.0590\).&lt;/li&gt;
  &lt;li&gt;Hậu nghiệm: \(0.0095 / 0.0590 \approx 0.1610\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hiểu lầm cần tránh:&lt;/strong&gt; Nhầm \(P(+ \mid D) = 95\%\) với \(P(D \mid +) = 16.1\%\) (lỗi đảo ngược xác suất có điều kiện — &lt;em&gt;prosecutor’s fallacy&lt;/em&gt;). Khi bệnh hiếm, số ca dương tính giả (\(495\)) áp đảo số ca dương tính thật (\(95\)).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm tra nhanh:&lt;/strong&gt; Nếu người đó làm &lt;strong&gt;lần xét nghiệm thứ hai độc lập có điều kiện&lt;/strong&gt; và tiếp tục dương tính, hãy lấy hậu nghiệm \(0.161\) làm prior mới: tử số mới là \(0.161 \times 0.95 = 0.15295\), phần không bệnh là \(0.839 \times 0.05 = 0.04195\), nên hậu nghiệm vọt lên \(0.15295 / (0.15295 + 0.04195) \approx 78.5\%\). Đó chính là sức mạnh của cập nhật tuần tự Bayes.&lt;/p&gt;

&lt;hr /&gt;

&lt;h4 id=&quot;video-ngắn-xác-suất-có-điều-kiện--xét-nghiệm-10000-người&quot;&gt;Video ngắn: Xác suất có điều kiện &amp;amp; Xét nghiệm 10.000 người&lt;/h4&gt;

&lt;div class=&quot;reel-video&quot; style=&quot;text-align:center;margin:1.5rem 0;&quot;&gt;
&lt;video controls=&quot;&quot; playsinline=&quot;&quot; preload=&quot;metadata&quot; style=&quot;width:100%;max-width:360px;height:auto;aspect-ratio:9/16;border-radius:8px;background:#0e0e10;&quot; src=&quot;/public/videos/reels/ch00-01b-bayes-screening-10k.mp4&quot;&gt;&lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Video dài khoảng 3 phút 3 giây: phân tách 10.000 người thành cây tần suất tự nhiên, giải bài toán dương tính giả 16.1%, cập nhật xét nghiệm lần 2 và bẫy bỏ qua tỷ lệ nền.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=oI3hZJqXJuc&quot;&gt;The Main Ideas behind Probability Distributions&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;Xem trước.&lt;/strong&gt; Giúp hình dung phân phối xác suất như cách biểu diễn mức độ chắc chắn, khớp với phần mở đầu của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=_IgyaD7vOOA&quot;&gt;Conditional Probabilities, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Trình bày trực quan về xác suất có điều kiện, phép tính nền tảng để cập nhật suy luận khi có thông tin mới.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Random variables&lt;/td&gt;
          &lt;td&gt;Probability and Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=3v9w79NhsfI) — Khan Academy, English. Giới thiệu cách định nghĩa biến ngẫu nhiên, hỗ trợ phân biệt kết quả quan sát với đại lượng chưa biết.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bài-tập&quot;&gt;Bài tập&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 1: Xác suất Cơ bản.&lt;/strong&gt; Một hộp chứa 5 viên bi đỏ, 3 viên bi xanh và 2 viên bi vàng. Rút ngẫu nhiên một viên bi. (a) Xác định không gian mẫu. (b) Tính xác suất rút được viên bi đỏ. (c) Tính xác suất rút được viên bi không phải màu vàng. Giải thích lập luận bằng lời, không chỉ ghi công thức.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 2: Xác suất Có điều kiện.&lt;/strong&gt; Trong một lớp học, 60% sinh viên học Python, 40% học R và 25% học cả hai. (a) Nếu chọn ngẫu nhiên một sinh viên và biết người đó học Python, xác suất người đó cũng học R là bao nhiêu? (b) Hai biến cố “học Python” và “học R” có độc lập không? Giải thích bằng cả tính toán và trực giác.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 3: Quy tắc Xác suất Toàn phần.&lt;/strong&gt; Một công ty sản xuất sản phẩm tại ba nhà máy A, B và C với tỷ lệ sản lượng lần lượt là 50%, 30% và 20%. Tỷ lệ sản phẩm lỗi của mỗi nhà máy lần lượt là 2%, 3% và 5%. (a) Tính xác suất một sản phẩm chọn ngẫu nhiên bị lỗi. (b) Nếu một sản phẩm được phát hiện bị lỗi, xác suất nó đến từ nhà máy C là bao nhiêu? (Gợi ý: phần (b) liên quan đến định lý Bayes sẽ học ở bài sau, nhưng bạn có thể thử suy luận trước bằng xác suất có điều kiện.)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 4: Nghịch lý Simpson.&lt;/strong&gt; Xét hai phương pháp điều trị A và B được thử nghiệm trên hai nhóm bệnh nhân: nhóm bệnh nhẹ và nhóm bệnh nặng. Trong nhóm bệnh nhẹ, A thành công 90/100 ca và B thành công 85/90 ca. Trong nhóm bệnh nặng, A thành công 20/100 ca và B thành công 24/110 ca. (a) Trong mỗi nhóm, phương pháp nào có tỷ lệ thành công cao hơn? (b) Tính tỷ lệ thành công tổng thể của mỗi phương pháp. (c) Giải thích vì sao kết quả có vẻ nghịch lý và điều này cho thấy gì về vai trò của các biến tiềm ẩn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bài tập 5: Suy ngẫm về Xác suất.&lt;/strong&gt; Viết một đoạn văn ngắn (200–300 từ) giải thích sự khác biệt giữa quan điểm tần suất và quan điểm Bayesian về xác suất. Nêu một ví dụ mà quan điểm Bayesian tỏ ra tự nhiên hơn và giải thích lý do. Phân tích ngắn gọn cách hiểu về xác suất ảnh hưởng ra sao đến việc thiết kế thí nghiệm và diễn giải kết quả.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo&quot;&gt;Tài liệu Tham khảo&lt;/h2&gt;

&lt;h3 id=&quot;primary-references&quot;&gt;Primary References:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., &amp;amp; Rubin, D. B. (2013).&lt;/strong&gt; &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 1: Probability and inference&lt;/li&gt;
  &lt;li&gt;Appendix A: Standard probability distributions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kruschke, J. K. (2015).&lt;/strong&gt; &lt;em&gt;Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan&lt;/em&gt; (2nd Edition). Academic Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 4: What is This Stuff Called Probability?&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;supplementary-reading&quot;&gt;Supplementary Reading:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jaynes, E. T. (2003).&lt;/strong&gt; &lt;em&gt;Probability Theory: The Logic of Science&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapters 1-2: Plausible reasoning and quantitative rules&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Bài học tiếp theo: &lt;a href=&quot;/contents/vi/chapter00/00_02_01_bernoulli_binomial/&quot;&gt;0.2 Bernoulli và Binomial&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 7.3: Feature Selection - Choosing Important Predictors</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter07/07_03_feature_selection/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter07/07_03_feature_selection</id>
   <content type="html">&lt;p&gt;When a dataset arrives with 40 candidate predictors, the traditional textbook reflex is &lt;strong&gt;stepwise p-value selection&lt;/strong&gt;—drop whichever column has \(p &amp;gt; 0.05\), refit, and repeat until only “significant” stars remain. Statisticians have proved that stepwise selection is a disaster: it inflates remaining slopes, produces wildly invalid p-values, and picks completely different variable subsets if you remove just 5 rows!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bayesian Feature Selection&lt;/strong&gt; offers a far more principled path: &lt;strong&gt;continuous shrinkage priors (Horseshoe / Laplace)&lt;/strong&gt;, &lt;strong&gt;Posterior Inclusion Probabilities (Spike-and-Slab)&lt;/strong&gt;, and &lt;strong&gt;predictive projection (LOO-CV)&lt;/strong&gt;—separating &lt;em&gt;“which variables improve prediction?”&lt;/em&gt; from &lt;em&gt;“which variables belong in my causal DAG?”&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-four-bayesian-approaches-to-feature-selection&quot;&gt;Key ideas: Four Bayesian Approaches to Feature Selection&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Continuous Shrinkage (Horseshoe / Regularized Horseshoe):&lt;/strong&gt; Keeps all predictors in the model while shrinking irrelevant noise slopes aggressively toward &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;, avoiding brittle discrete include/exclude cliffs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Spike-and-Slab (Posterior Inclusion Probabilities — PIP):&lt;/strong&gt; Places a mixture prior on each \(\beta_j\) (a point-mass “spike” at 0 + a wide “slab”), directly estimating \(P(\beta_j \neq 0 \mid y)\) for every feature!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Predictive Selection (LOO-CV / Projection Predictive):&lt;/strong&gt; Evaluates whether adding feature \(X_j\) genuinely improves out-of-sample &lt;strong&gt;ELPD&lt;/strong&gt; beyond Monte Carlo standard error.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Causal vs. Predictive Selection (Crucial Warning!):&lt;/strong&gt; Never run automated feature selection to build a &lt;em&gt;causal&lt;/em&gt; model—dropping a weak confounder or keeping a strong collider can improve prediction while completely destroying causal accuracy!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After completing this lesson, you will understand &lt;strong&gt;feature selection&lt;/strong&gt; as the problem of determining which predictors truly matter when we have a very large number of candidates. The lesson goes through Bayesian approaches such as Laplace priors, spike-and-slab, and horseshoe priors, while comparing them with familiar frequentist methods such as Lasso or stepwise procedures. The goal is not only to know which tools exist, but to understand what assumption about the sparsity of the model each tool encodes, and when each approach is more reasonable in a high-dimensional data setting.&lt;/p&gt;

&lt;h2 id=&quot;introduction-the-problem-of-many-predictors&quot;&gt;Introduction: The Problem of Many Predictors&lt;/h2&gt;

&lt;p&gt;Consider the situation where you have 100 &lt;strong&gt;potential predictors&lt;/strong&gt; but only about 5 of them truly carry signal. If you keep all the variables, the model easily overfits; if you try every possible combination, the computational cost explodes because the number of models to consider reaches \(2^{100}\); and if you test each variable individually, you face the risk of &lt;strong&gt;false discoveries&lt;/strong&gt; due to multiple testing. Therefore, the goal of feature selection is not simply to “make the model more compact”, but to identify in a principled way the variables that are truly relevant while still controlling uncertainty and modeling cost.&lt;/p&gt;

&lt;h2 id=&quot;1-frequentist-approaches&quot;&gt;1. Frequentist Approaches&lt;/h2&gt;

&lt;h3 id=&quot;11-lasso-l1-regularization&quot;&gt;1.1. Lasso (L1 Regularization)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Lasso&lt;/strong&gt; sets some coefficients &lt;strong&gt;exactly to 0&lt;/strong&gt; → automatic feature selection.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/lasso_feature_selection.png&quot; alt=&quot;Lasso Feature Selection&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The example in the figure uses a dataset with 20 features, of which only the first 5 have truly nonzero coefficients. When \(\alpha\) is still very small, such as 0.001 or 0.01, regularization is too weak so the model still keeps about 13 features, meaning many noise variables slip into the model. When it rises to a moderate level such as 0.1, the coefficients begin to shrink more strongly toward 0 but the number of retained variables is still fairly large. Only when \(\alpha\) is strong enough, for example 0.5, do we clearly see the sparser effect: many coefficients are pushed to 0 and the number of selected features drops. The direct lesson from this example is that Lasso performs feature selection by forcing some coefficients to exactly 0, and the level of &lt;strong&gt;sparsity&lt;/strong&gt; increases as regularization gets stronger.&lt;/p&gt;

&lt;h3 id=&quot;12-cross-validation-to-choose-α&quot;&gt;1.2. Cross-Validation to Choose α&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/lasso_cv_regularization_path.png&quot; alt=&quot;Lasso CV and Regularization Path&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The cross-validation result in this example chooses \(\alpha=1.0\) as the best regularization level by out-of-sample predictive ability. At that level, the model keeps 7 features, slightly more than the 5 truly relevant features, but still fairly close to the true sparse structure of the data. The regularization path in the right panel adds a very important intuition: when \(\alpha\) is small, most coefficients are nonzero and have considerable magnitude; as \(\alpha\) increases, the coefficients shrink to 0 at different rates; and the features carrying real signal usually “hold on” longer than the noise variables. So cross-validation not only helps choose the optimal level of regularization but also gives us a dynamic view of how each variable leaves the model.&lt;/p&gt;

&lt;h2 id=&quot;2-bayesian-approaches&quot;&gt;2. Bayesian Approaches&lt;/h2&gt;

&lt;h3 id=&quot;21-laplace-prior-bayesian-lasso&quot;&gt;2.1. Laplace Prior (Bayesian Lasso)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Laplace prior&lt;/strong&gt; = Bayesian equivalent of Lasso.&lt;/p&gt;

\[\beta_j \sim \text{Laplace}(0, b)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Bayesian Lasso
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bayesian_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Laplace priors
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Laplace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Laplace!
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;trace_lasso&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                           &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Extract coefficients
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_lasso&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Coefficients
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_coef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bayesian Lasso&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
           &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Feature Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BAYESIAN LASSO&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Laplace Prior)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Posterior distributions (first 6 features)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient Value&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR DISTRIBUTIONS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;First 6 features&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;22-horseshoe-prior&quot;&gt;2.2. Horseshoe Prior&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;Horseshoe prior&lt;/strong&gt; is more flexible than the Laplace prior because it both allows some truly large coefficients to survive thanks to its heavy tails, and shrinks small coefficients very strongly toward 0. This ability to both “spare” strong signals and strongly “penalize” weak noise makes the horseshoe an especially attractive prior in sparse-signal problems.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Horseshoe prior
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;horseshoe_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Horseshoe prior
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;tau&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfCauchy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;tau&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Global shrinkage
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;lambda_j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfCauchy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lambda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Local shrinkage
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tau&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;trace_horseshoe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_state&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Extract
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_horseshoe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compare all methods
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;methods&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_coef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lasso (Freq.)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lasso_cv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coef_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bayesian Lasso&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Horseshoe&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;coef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;methods&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;coef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
              &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Feature Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
                                 &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Non-zero: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;FEATURE SELECTION COMPARISON&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True non-zero: 5&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lasso: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lasso_cv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coef_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; selected&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bayesian Lasso: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_lasso&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; selected&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Horseshoe: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; selected&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;experiment-how-gaussian-laplace-and-horseshoe-shrink-differently&quot;&gt;Experiment: how Gaussian, Laplace and Horseshoe shrink differently&lt;/h3&gt;

&lt;p&gt;50 coefficients, only 5 large: compare the posterior mean of each prior and the shrinkage curve.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;horseshoe-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-posterior-inclusion-probabilities&quot;&gt;3. Posterior Inclusion Probabilities&lt;/h2&gt;

&lt;p&gt;An important advantage of the Bayesian approach is that it does not only produce a list of selected variables, but also quantifies the uncertainty of the selection process itself. The &lt;strong&gt;Posterior Inclusion Probability (PIP)&lt;/strong&gt; is understood as the posterior probability that a coefficient is different enough from 0 under a practical criterion, and thanks to this it lets us talk about the degree of certainty of variable importance, instead of only saying “selected” or “not selected”.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Compute PIPs
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples_horseshoe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# PIP = proportion of posterior samples where |β| &amp;gt; threshold
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pips&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# PIPs
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pips&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Threshold = 0.5&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Feature Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior Inclusion Probability&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR INCLUSION PROBABILITIES&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
                 &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;P(|β| &amp;gt; 0.1 &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\\&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mid data)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Coefficient vs PIP
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_samples_horseshoe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pips&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pips&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;va&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior Inclusion Probability&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;COEFFICIENT vs PIP&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Large |β| → High PIP&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;FEATURES WITH HIGH PIP (&amp;gt; 0.5)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;selected&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pips&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Selected features: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;selected&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True relevant: [0, 1, 2, 3, 4]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;→ Bayesian approach quantifies uncertainty!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;4-applied-case-study-phan-3-stability-selection--interpretation-risk&quot;&gt;4. Applied Case Study (Phan 3): Stability selection + interpretation risk&lt;/h2&gt;

&lt;p&gt;In real problems, a feature being selected once is not enough to conclude that it is important. We need to check the &lt;strong&gt;stability of feature selection&lt;/strong&gt; over many resamplings.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;ridge_fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;eye&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;solve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;bootstrap_stability&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_boot&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;picks&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_boot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_boot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;integers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;Xb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;beta_b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;ridge_fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Xb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;picks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;picks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# selection frequency
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;stability&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;bootstrap_stability&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_lambda&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simple rule: choose variables with selection frequency &amp;gt;= 0.7
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stable_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stability&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Stable features (freq &amp;gt;= 0.7):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stable_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;41-uncertainty-aware-thresholds&quot;&gt;4.1. Uncertainty-aware thresholds&lt;/h3&gt;

&lt;p&gt;Instead of a single fixed threshold, report results at several levels:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hot (&amp;gt;= 0.9)&lt;/strong&gt;: very strong evidence, safe to put into the main interpretive model.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Warm (0.7 - 0.9)&lt;/strong&gt;: fairly stable, needs cross-checking with domain knowledge.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Weak (&amp;lt; 0.7)&lt;/strong&gt;: not yet stable, treat as a backup feature.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With Bayesian models, you can also add a PIP threshold (for example PIP &amp;gt;= 0.8) to report selection uncertainty transparently.&lt;/p&gt;

&lt;h3 id=&quot;42-interpretation-risks-in-machine-learning&quot;&gt;4.2. Interpretation risks in machine learning&lt;/h3&gt;

&lt;p&gt;Even when a feature is selected stably, interpretation still carries risks:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Collinearity&lt;/strong&gt;: a selected feature may be a representative of a cluster of correlated variables, not necessarily a direct cause.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Proxy bias&lt;/strong&gt;: a feature may act as a proxy for a sensitive attribute.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Data drift&lt;/strong&gt;: the selection frequency may change over time as the data distribution changes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Actionability gap&lt;/strong&gt;: a feature that is important for prediction is not necessarily useful for operational decisions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Decision checkpoint 3 (end of the case study)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Report jointly: out-of-sample performance + uncertainty (PIP/stability) + interpretation warnings.&lt;/li&gt;
  &lt;li&gt;Only lock the list of “actionable” features after passing the 3 layers of checks above.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you want to reproduce the whole case study presented throughout 7.1 -&amp;gt; 7.3, you can run the script:&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;python img/chapter_img/chapter07/generate_applied_ml_workflow_tradeoffs.py&lt;/code&gt;&lt;/p&gt;

&lt;h2 id=&quot;5-when-to-use-which-method&quot;&gt;5. When to Use Which Method?&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Method&lt;/th&gt;
      &lt;th&gt;Pros&lt;/th&gt;
      &lt;th&gt;Cons&lt;/th&gt;
      &lt;th&gt;When to Use&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Lasso&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Fast, sparse&lt;/td&gt;
      &lt;td&gt;No uncertainty&lt;/td&gt;
      &lt;td&gt;Large n, quick results&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Bayesian Lasso&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Uncertainty, flexible&lt;/td&gt;
      &lt;td&gt;Slower&lt;/td&gt;
      &lt;td&gt;Need uncertainty quantification&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Horseshoe&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Heavy tails, flexible&lt;/td&gt;
      &lt;td&gt;Complex&lt;/td&gt;
      &lt;td&gt;Strong sparsity assumption&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Spike-and-Slab&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Explicit selection&lt;/td&gt;
      &lt;td&gt;Very slow&lt;/td&gt;
      &lt;td&gt;Small p, explicit probabilities&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Feature selection is the problem of choosing the predictors that are truly relevant when the number of candidate variables is large and the risk of overfitting is present. Lasso solves this problem by using an L1 penalty to produce a sparse solution, Bayesian Lasso interprets the same idea through a Laplace prior, and the horseshoe prior brings a more refined shrinkage mechanism, especially useful when we believe that only a few strong signals stand out among a great many weak variables. More importantly, the Bayesian approach also provides &lt;strong&gt;uncertainty quantification&lt;/strong&gt; for the variable choice itself, for example through Posterior Inclusion Probabilities, instead of merely returning a list of seemingly optimal variables.&lt;/p&gt;

&lt;p&gt;The most important point of the lesson is that variable selection should not be understood as a mechanical filtering operation, but as part of the process of inferring the structure of the signal in the data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Chapter 07 Complete!&lt;/strong&gt; Regularization, Bias-Variance, Feature Selection.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-reading-posterior-inclusion-probabilities-pip--credible-intervals&quot;&gt;Worked Numerical Example: Reading Posterior Inclusion Probabilities (PIP) &amp;amp; Credible Intervals&lt;/h3&gt;

&lt;p&gt;Suppose you fit a Bayesian Spike-and-Slab / Horseshoe model on 3 standardized candidate predictors (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;X1&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;X2&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;X3&lt;/code&gt;) for customer churn:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Feature&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Posterior Inclusion Prob (PIP)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Posterior Mean \(\beta_j\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;95% Credible Interval&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Decision&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;X1&lt;/code&gt; (Tenure)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.99\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-0.85\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([-1.08,\; -0.62]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Core predictor&lt;/strong&gt; (keep!)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;X2&lt;/code&gt; (Support Tickets)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.64\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+0.22\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([-0.02,\; +0.48]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Moderate evidence (keep / average)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;X3&lt;/code&gt; (Signup Day)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.07\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+0.01\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([-0.09,\; +0.11]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Pure noise (shrunk to ~0!)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Notice how much richer this is than a binary stepwise cutoff: instead of falsely claiming &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;X2&lt;/code&gt; is “0% important” just because its CI barely touches &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;, Bayesian selection transparently reports 64% inclusion probability and averages over model uncertainty!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-responsible-bayesian-feature-selection&quot;&gt;Explanation: Four Rules for Responsible Bayesian Feature Selection&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Never use stepwise p-value elimination:&lt;/strong&gt; It destroys post-selection uncertainty intervals and overfits heavily when predictors correlate.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Separate your &lt;em&gt;causal&lt;/em&gt; adjustment set from &lt;em&gt;predictive&lt;/em&gt; feature pruning:&lt;/strong&gt; Use a DAG to lock in confounders first; only prune remaining optional predictors for parsimony/cost.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Remember correlated features split their PIPs:&lt;/strong&gt; If &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;X1&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;X1_copy&lt;/code&gt; are 95% correlated, Spike-and-Slab may assign each a PIP of ~50% (choosing one &lt;em&gt;or&lt;/em&gt; the other on every draw)—check joint inclusion \(P(X_1 \text{ or } X_{1,\text{copy}} \mid y) = 99\%\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Measure actual ELPD gain before paying engineering cost for a new feature:&lt;/strong&gt; Even a “real” predictor with \(\beta = 0.05\) may not justify maintaining a complex data pipeline if LOO-CV ELPD barely budges.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If two features &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;B&lt;/code&gt; are almost identical copies of each other and one of them truly causes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Y&lt;/code&gt;, why might a Spike-and-Slab model report &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PIP(A) ≈ 0.50&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PIP(B) ≈ 0.50&lt;/code&gt; instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.99&lt;/code&gt; for both?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NGf0voTMlcs&quot;&gt;Regularization Part 2: Lasso (L1) Regression&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch L1 be able to set some coefficients exactly to zero, exactly the variable-selection direction the lesson contrasts with searching all combinations.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Mv6MSIVKEIc&quot;&gt;Lecture 31 Bayesian Regression and Variable Selection (Part A)&lt;/a&gt; — Nicholas Zabaras, English. Watch Bayesian regression and variable selection in one lecture, supporting the shrinkage priors on coefficients when there are too many predictors.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuhvfvY8ISc&quot;&gt;Regularized Horseshoe - Aki Vehtari&lt;/a&gt; — Stan, English. Watch the regularized horseshoe, used for the part of the lesson on sparse priors on coefficients rather than just a lasso-style penalty.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1&lt;/strong&gt;: Generate sparse data. Compare Lasso, Bayesian Lasso, Horseshoe. Which recovers true features best?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2&lt;/strong&gt;: Compute PIPs. Threshold at 0.5, 0.7, 0.9. How does selection change?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3&lt;/strong&gt;: Regularization path: Plot coefficients vs λ. Observe when features enter/exit.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4&lt;/strong&gt;: Real high-dimensional data. Perform feature selection. Interpret selected features.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5&lt;/strong&gt;: Compare computational time: Lasso vs Bayesian approaches. Trade-offs?&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Carvalho, C. M., et al. (2010).&lt;/strong&gt; “The horseshoe estimator for sparse signals.” &lt;em&gt;Biometrika&lt;/em&gt;, 97(2), 465-480.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Piironen, J., &amp;amp; Vehtari, A. (2017).&lt;/strong&gt; “Sparsity information and regularization in the horseshoe and other shrinkage priors.” &lt;em&gt;Electronic Journal of Statistics&lt;/em&gt;, 11(2), 5018-5051.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., et al. (2020).&lt;/strong&gt; &lt;em&gt;Regression and Other Stories&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 11: Assumptions, diagnostics, and model evaluation&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next chapter: &lt;a href=&quot;/contents/en/chapter08/&quot;&gt;Chapter 08: Model Comparison&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 7.2: Bias-Variance Tradeoff - The Core of Model Selection</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter07/07_02_bias_variance_tradeoff/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter07/07_02_bias_variance_tradeoff</id>
   <content type="html">&lt;p&gt;Give a polynomial regression enough flexibility (degree 9 on 10 data points), and it will wiggle cleanly through &lt;strong&gt;every single training point&lt;/strong&gt; with 0.00 training error—yet predict catastrophic nonsense one millimeter outside the training points! That classic tension between &lt;strong&gt;underfitting&lt;/strong&gt; (too rigid, high bias) and &lt;strong&gt;overfitting&lt;/strong&gt; (memorizing noise, high variance) is the &lt;strong&gt;Bias–Variance Trade-off&lt;/strong&gt;—the compass of all model selection.&lt;/p&gt;

&lt;p&gt;This lesson reframes the Bias–Variance Trade-off in Bayesian terms: showing how &lt;strong&gt;regularizing priors&lt;/strong&gt; and &lt;strong&gt;posterior averaging&lt;/strong&gt; tame variance automatically, and why &lt;strong&gt;out-of-sample predictive accuracy&lt;/strong&gt; is the only honest judge of model complexity.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-complexity-generalization-and-bayesian-averaging&quot;&gt;Key ideas: Complexity, Generalization, and Bayesian Averaging&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Underfitting (High Bias) vs. Overfitting (High Variance):&lt;/strong&gt; Too few parameters miss real curvature (both train and test error stay high); too many unregularized parameters chase random sample noise (train error \(\to 0\), test error explodes!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;In-Sample Deviance Always Improves With Complexity:&lt;/strong&gt; Adding any extra parameter never worsens training fit—which is why comparing models on training \(R^2\) or training log-likelihood guarantees overfitting!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Regularizing Priors Shift the Sweet Spot:&lt;/strong&gt; Tightening the prior on higher-order terms adds tiny bias while slashing variance dramatically, letting richer models generalize cleanly.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior Averaging Reduces Variance Further:&lt;/strong&gt; Integrating predictions over all posterior draws \(\theta^{(s)}\) (instead of plugging in one MLE/MAP point!) acts like an automatic ensemble, softening overconfident out-of-sample predictions.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After completing this lesson, you will have a deep understanding of the &lt;strong&gt;bias-variance tradeoff&lt;/strong&gt;, one of the most fundamental ideas in machine learning and statistics. The lesson explains why a model that is too simple usually has &lt;strong&gt;high bias&lt;/strong&gt;, why a model that is too complex usually has &lt;strong&gt;high variance&lt;/strong&gt;, and why the real goal of model selection is not to push one component as low as possible, but to find the balance point that makes the overall error smallest. This is the direct basis for understanding regularization, overfitting, and even the logic of choosing models.&lt;/p&gt;

&lt;h2 id=&quot;introduction-two-kinds-of-error&quot;&gt;Introduction: Two Kinds of Error&lt;/h2&gt;

&lt;p&gt;When a model predicts wrongly, the error usually does not come from a single cause. Part of the error may come from the model being too simple and therefore missing the true structure of the data; that is &lt;strong&gt;bias&lt;/strong&gt;. Another part may come from the model being too sensitive to the training data, so that changing the sample slightly makes the predictions fluctuate strongly; that is &lt;strong&gt;variance&lt;/strong&gt;. The core point is that these two components usually pull in opposite directions: reducing bias usually increases variance, while pushing variance down too hard usually increases bias.&lt;/p&gt;

&lt;h2 id=&quot;1-bias-and-variance-definitions&quot;&gt;1. Bias and Variance: Definitions&lt;/h2&gt;

&lt;h3 id=&quot;11-mathematical-definitions&quot;&gt;1.1. Mathematical Definitions&lt;/h3&gt;

&lt;p&gt;Suppose we train the model many times on different datasets from the same distribution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bias&lt;/strong&gt;: The deviation between the &lt;strong&gt;average prediction&lt;/strong&gt; and the &lt;strong&gt;true value&lt;/strong&gt;
\(\text{Bias}[\hat{f}(x)] = \mathbb{E}[\hat{f}(x)] - f(x)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variance&lt;/strong&gt;: Variability of predictions across datasets
\(\text{Variance}[\hat{f}(x)] = \mathbb{E}[(\hat{f}(x) - \mathbb{E}[\hat{f}(x)])^2]\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Total Error&lt;/strong&gt;:
\(\mathbb{E}[(y - \hat{f}(x))^2] = \text{Bias}^2 + \text{Variance} + \text{Irreducible Error}\)&lt;/p&gt;

&lt;h3 id=&quot;12-intuitive-understanding&quot;&gt;1.2. Intuitive Understanding&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/bias_variance_demonstration.png&quot; alt=&quot;Bias-Variance Demonstration&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The figure illustrates this intuition very clearly. With a degree-1 model, the fitted lines from many different datasets are fairly close to each other, meaning low variance, but most of them are far off the true pattern, meaning high bias; this is the typical underfitting state. With a degree-3 model, the flexibility is just enough to follow the true pattern more closely without fluctuating too much between samples, so bias decreases while variance is still under control; that is the best balance region of the trade-off. With a degree-10 model, the average curve may already be closer to the true pattern, meaning lower bias, but each individual model fluctuates strongly from one training sample to the next, meaning variance shoots up. Therefore, looking at 50 different training sets as 50 different versions of the same problem is the most intuitive way to understand variance: it measures how much the predictions “shake” when the data changes.&lt;/p&gt;

&lt;h2 id=&quot;2-decomposition-mse--bias--variance--noise&quot;&gt;2. Decomposition: MSE = Bias² + Variance + Noise&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/mse_decomposition.png&quot; alt=&quot;MSE Decomposition&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Looking at the decomposition of the MSE, we see immediately why model choice cannot rest on a single criterion. In the low-complexity region, for example degree 1 or 2, the \(\text{Bias}^2\) component is still large because the model is too simple to describe the data, even though the variance is fairly low then. As complexity increases into the intermediate region, the two components begin to balance better and the total MSE reaches its minimum; that is the true “sweet spot” of the model. But as complexity keeps increasing, bias may decrease a little more while variance rises very sharply, making the MSE rise again. The stacked chart on the right is especially useful because it shows visually that the goal is not to minimize bias alone or variance alone, but to minimize the total prediction error.&lt;/p&gt;

&lt;h3 id=&quot;experiment-bias-variance-and-total-error-by-complexity&quot;&gt;Experiment: bias, variance and total error by complexity&lt;/h3&gt;

&lt;p&gt;Repeat 100 datasets for each polynomial degree; bias² falls, variance rises, the total error is U-shaped; a tight prior (ridge) compresses the variance.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;biasvar-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-regularization-and-bias-variance&quot;&gt;3. Regularization and Bias-Variance&lt;/h2&gt;

&lt;p&gt;Regularization is precisely the knob that controls this trade-off. When regularization is weak, that is \(\lambda\) is small, the model is allowed to be more flexible, so bias tends to be low but variance is high. When regularization is strong, that is \(\lambda\) is large, the model is forced to be simpler, so variance decreases, but bias increases.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/regularization_bias_variance.png&quot; alt=&quot;Regularization Bias-Variance&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The example with a degree-10 polynomial shows this point very clearly. When \(\lambda=0.001\), regularization is too weak so the model fluctuates strongly, shown by a very large variance and clear overfitting. As it increases gradually to \(0.1\) and then \(1\), variance drops considerably and the model enters a better balance region. If it keeps increasing to \(10\) or \(100\), the model starts to be constrained too strongly, the predictions become almost flat, variance is low but bias is high, meaning a return to the underfitting region. The lesson here is that \(\lambda\) is not a parameter where “bigger is safer”; it must be chosen so that bias and variance reach the best balance for the prediction goal.&lt;/p&gt;

&lt;h2 id=&quot;4-bayesian-perspective&quot;&gt;4. Bayesian Perspective&lt;/h2&gt;

&lt;p&gt;In Bayesian statistics, the role of regularization is translated into the role of &lt;strong&gt;prior strength&lt;/strong&gt;. Weak priors let the data decide more, so the model is more flexible but also fluctuates more; strong priors constrain the model more, so variance decreases, but in return bias may increase if the prior is too rigid.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;true_function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x_data_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_data_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Different prior strengths
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior_sds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ravel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_sd&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior_sds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_sd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Varying prior strength
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data_z&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_data_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                         &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Posterior predictions
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;alpha_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Plot
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x_plot_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_plot_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_plot_z&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_plot&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_plot_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.05&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zorder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zorder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_sd&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;title_color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;subtitle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(High Bias)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_sd&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;title_color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;subtitle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(High Variance)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;title_color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;subtitle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Balanced)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Prior SD = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior_sd&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;subtitle&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                       &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title_color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-validation-strategy-and-learning-curves-in-practice&quot;&gt;5. Validation Strategy and Learning Curves in Practice&lt;/h2&gt;

&lt;p&gt;The bias-variance tradeoff becomes a decision-making tool only when we measure it on out-of-sample data.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Train score&lt;/strong&gt; helps monitor the ability to learn from data already seen.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Validation score&lt;/strong&gt; tells the degree of generalization, for tuning complexity/prior scale.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Test score&lt;/strong&gt; is the final report, used only once after the model choice has been locked.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A quick way to read learning curves:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Good train, poor validation and a large gap -&amp;gt; &lt;strong&gt;high variance&lt;/strong&gt; (needs stronger regularization or more data).&lt;/li&gt;
  &lt;li&gt;Poor train and validation both -&amp;gt; &lt;strong&gt;high bias&lt;/strong&gt; (needs a more flexible model, add reasonable features).&lt;/li&gt;
  &lt;li&gt;Validation stable around the best point as regularization increases -&amp;gt; this is the appropriate balance region.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;6-applied-case-study-part-2-tune-complexity-with-validation&quot;&gt;6. Applied Case Study (Part 2): tune complexity with validation&lt;/h2&gt;

&lt;p&gt;Continuing the data setup from Lesson 7.1, we use closed-form ridge to sweep regularization strengths and choose the bias-variance balance using validation RMSE.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;ridge_fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;eye&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;solve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rmse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;lambdas&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;val_scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;coefs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambdas&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;ridge_fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;coefs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rmse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_train_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_train_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rmse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_val_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_val_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;best_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;best_lambda&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambdas&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;best_beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;coefs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_rmse&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rmse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_test_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_test_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Best lambda (validation): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_lambda&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Train RMSE (z-scale): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Validation RMSE (z-scale): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Test RMSE (z-scale): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_rmse&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/applied_ml_workflow_tradeoffs.png&quot; alt=&quot;Applied ML Workflow Tradeoffs&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The figure above summarizes three main decisions in the applied workflow: (1) choose regularization by validation RMSE, (2) check the size of the coefficients after shrinkage, and (3) assess the stability of variable selection through bootstrap frequencies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Decision checkpoint 2&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;If you optimize only the train RMSE, the result usually pushes the model into the overfit region.&lt;/li&gt;
  &lt;li&gt;If you optimize the validation RMSE and keep the test for the final step, you have a trustworthy basis for assessing generalization.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;7-tuning-checklist-from-tradeoff-to-action&quot;&gt;7. Tuning checklist: from tradeoff to action&lt;/h2&gt;

&lt;p&gt;When choosing model complexity in regression/classification problems:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Choose a metric appropriate to the business/problem goal (do not use a metric just to go through the motions).&lt;/li&gt;
  &lt;li&gt;Use a reasonable grid for regularization/prior scale instead of sweeping too wide.&lt;/li&gt;
  &lt;li&gt;Track both the train-validation gap and the stability across folds.&lt;/li&gt;
  &lt;li&gt;Combine out-of-sample performance with posterior predictive checks to detect model misspecification.&lt;/li&gt;
  &lt;li&gt;Settle on a model with reasons that can be explained (not just “the highest score”).&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;The bias-variance tradeoff shows that prediction error cannot be understood by a single simple measure of “fit”. &lt;strong&gt;Bias&lt;/strong&gt; reflects the price of using a model that is too simple, while &lt;strong&gt;variance&lt;/strong&gt; reflects the price of using a model that is too sensitive to the training data. The formula \(\text{MSE}=\text{Bias}^2+\text{Variance}+\text{Irreducible Error}\) reminds us that a good model is one that balances these two opposing forces. Regularization is the practical tool for adjusting that balance point, and in Bayesian statistics, the strength of the prior plays exactly that role.&lt;/p&gt;

&lt;p&gt;The point to remember most is that a model that fits the training data beautifully is not necessarily a good model; a good model is one that generalizes well to new data.&lt;/p&gt;

&lt;p&gt;Next lesson: &lt;strong&gt;Feature Selection&lt;/strong&gt; (completing the case study with stability selection and uncertainty-aware interpretation).&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-watching-train-vs-test-deviance-diverge-across-polynomial-degrees&quot;&gt;Worked Numerical Example: Watching Train vs. Test Deviance Diverge Across Polynomial Degrees&lt;/h3&gt;

&lt;p&gt;Fit polynomial models of degree 1, 2, 5, and 9 (with flat priors) to \(n = 15\) noisy points from a true quadratic curve:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Model Complexity&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Parameters \(p\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;In-Sample Train Deviance&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Out-of-Sample Test Deviance&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Diagnosis&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Degree 1 (Line)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(24.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(26.1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Underfit&lt;/strong&gt; (high bias — misses curve)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Degree 2 (Quadratic)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(8.4\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(9.6\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Sweet spot!&lt;/strong&gt; (lowest test error)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Degree 5&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(6\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(6.1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(15.8\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Starting to chase sample noise&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Degree 9 (Flat Prior)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(10\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(1.2\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(64.0\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Severe Overfit!&lt;/strong&gt; (huge variance!)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Degree 9 (\(\mathcal{N}(0, 0.3)\) Prior)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(10\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(8.9\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(10.2\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Regularizing prior rescues generalization!&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Look at the bottom two rows: the exact same 10-parameter architecture drops out-of-sample deviance from &lt;strong&gt;64.0 down to 10.2&lt;/strong&gt; simply by adding a skeptical Bayesian prior!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-navigating-the-biasvariance-trade-off&quot;&gt;Explanation: Four Rules for Navigating the Bias–Variance Trade-Off&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Never pick a model by training fit alone:&lt;/strong&gt; Always evaluate via cross-validation (LOO-CV / k-fold) or a locked held-out test set.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Plot the &lt;em&gt;gap&lt;/em&gt; between train and test deviance:&lt;/strong&gt; A tiny train error paired with a huge test error is the unmistakable fingerprint of overfitting; both high signals underfitting.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prefer regularizing priors over crude manual dropping of variables:&lt;/strong&gt; Smoothly shrinking weak effects toward zero avoids the abrupt variance spikes of all-or-nothing variable deletion.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;More data cures variance, not structural bias:&lt;/strong&gt; Collecting 10× more samples won’t make a straight line fit a parabola—you must fix underfitting by enriching the model family!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the polynomial table above, why did adding a \(\mathcal{N}(0, 0.3)\) prior to the Degree-9 model make its &lt;em&gt;in-sample training deviance&lt;/em&gt; slightly worse (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.2&lt;/code&gt; \(\to\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;8.9&lt;/code&gt;) while cutting its &lt;em&gt;out-of-sample test deviance&lt;/em&gt; by more than 6× (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;64.0&lt;/code&gt; \(\to\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10.2&lt;/code&gt;)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch a model that is too simple being systematically off and a model that is too flexible fluctuating with the sample, exactly the two kinds of error in the lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qmVT35gFW-Q&quot;&gt;[Proof] MSE = Variance + Bias²&lt;/a&gt; — math et al, English. Watch the identity MSE equals squared bias plus variance, supporting the error decomposition part.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=fSytzGwwBVw&quot;&gt;Machine Learning Fundamentals: Cross Validation&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch cross-validation as a way of looking at out-of-sample error, used for the learning curve and choosing complexity sections.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1&lt;/strong&gt;: Implement bias-variance decomposition from scratch. Verify MSE = Bias² + Variance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2&lt;/strong&gt;: Generate data. Compute bias-variance for models with different complexities. Find optimal.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3&lt;/strong&gt;: Use Ridge with different λ. Plot bias-variance curve. Find optimal λ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4&lt;/strong&gt;: Bayesian models with different prior SDs. Compute posterior variance. Relate to bias-variance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5&lt;/strong&gt;: Real data. Split train/test. Show overfitting with high-degree polynomial. Fix with regularization.&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Hastie, T., Tibshirani, R., &amp;amp; Friedman, J. (2009).&lt;/strong&gt; &lt;em&gt;The Elements of Statistical Learning&lt;/em&gt; (2nd Edition). Springer.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 7: Model Assessment and Selection&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;James, G., et al. (2013).&lt;/strong&gt; &lt;em&gt;An Introduction to Statistical Learning&lt;/em&gt;. Springer.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 2: Statistical Learning&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter07/07_03_feature_selection/&quot;&gt;7.3 Feature Selection&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 7.1: Regularization with Priors - Preventing Overfitting</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter07/07_01_regularization_priors/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter07/07_01_regularization_priors</id>
   <content type="html">&lt;p&gt;Here is one of the most exhilarating unifications in modern statistics and machine learning: &lt;strong&gt;Ridge regression (L2 penalty) and Lasso regression (L1 penalty) are not ad-hoc engineering hacks—they are literally Bayesian MAP estimates under Gaussian and Laplace priors!&lt;/strong&gt; Every time a machine-learning engineer adds &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alpha * sum(w**2)&lt;/code&gt; to prevent overfitting, they are quietly placing a zero-centered Normal prior \(\beta_j \sim \mathcal{N}(0, \tau^2)\) on their slopes!&lt;/p&gt;

&lt;p&gt;This lesson unpacks &lt;strong&gt;regularization as skeptical priors&lt;/strong&gt;: proving the exact equivalence between prior width \(\tau\) and penalty strength \(\lambda\), and showing how Bayesian posteriors go &lt;em&gt;further&lt;/em&gt; than Ridge/Lasso by giving you full uncertainty intervals and adaptive &lt;strong&gt;Horseshoe priors&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-exact-dictionary-between-priors-and-regularization&quot;&gt;Key ideas: The Exact Dictionary Between Priors and Regularization&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gaussian Prior \(\iff\) Ridge (L2) Regularization:&lt;/strong&gt; Taking \(-\log\bigl(p(y\mid\beta)\,p(\beta)\bigr)\) with \(y\mid\beta \sim \mathcal{N}(X\beta, \sigma^2 I)\) and \(\beta_j \sim \mathcal{N}(0, \tau^2)\) produces the exact objective \(\frac{1}{2\sigma^2}\|y - X\beta\|_2^2 + \frac{1}{2\tau^2}\|\beta\|_2^2\)—Ridge with \(\lambda = \sigma^2 / \tau^2\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Laplace (Double-Exponential) Prior \(\iff\) Lasso (L1) Regularization:&lt;/strong&gt; Replacing \(\beta_j^2\) with \(\lvert\beta_j\rvert\) via \(\beta_j \sim \mathrm{Laplace}(0, b)\) yields the exact Lasso MAP objective with \(\lambda = \sigma^2 / b\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Horseshoe &amp;amp; Student-\(t\) Priors (Adaptive Bayesian Shrinkage):&lt;/strong&gt; A pure Gaussian prior shrinks large true signals and small noise equally; a &lt;strong&gt;Horseshoe prior&lt;/strong&gt; has an infinite spike at 0 (crushing noise) &lt;em&gt;and&lt;/em&gt; Cauchy-like heavy tails (leaving big real signals almost untouched!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Full Posterior &amp;gt; Point MAP:&lt;/strong&gt; Unlike frequentist Ridge/Lasso (which output one point vector and struggle with post-selection CIs), Bayesian regularization gives valid credible intervals for every coefficient!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After completing this lesson, you will understand &lt;strong&gt;regularization&lt;/strong&gt; as a core mechanism for preventing &lt;strong&gt;overfitting&lt;/strong&gt;. The lesson clarifies why priors in Bayesian statistics perform regularization naturally, how they relate to Ridge regression and Lasso regression in frequentist language, and in which situations we truly need regularization rather than simply adding complexity to the model. This is an essential skill when modeling with many &lt;strong&gt;predictors&lt;/strong&gt;, especially in problems where the number of variables exceeds what our intuition can control by eye.&lt;/p&gt;

&lt;h2 id=&quot;introduction-the-overfitting-problem&quot;&gt;Introduction: The overfitting problem&lt;/h2&gt;

&lt;p&gt;Imagine you have only 20 data points but want to fit a polynomial regression. A question that seems technical, such as whether to choose degree 1, degree 10, or degree 15, actually leads straight to a very fundamental problem of modern statistics. If the model is too simple, it will &lt;strong&gt;underfit&lt;/strong&gt; and miss important structure; but if the model is too flexible, it can cling tightly even to the random fluctuations of the training data. The model then learns &lt;strong&gt;noise&lt;/strong&gt; instead of &lt;strong&gt;signal&lt;/strong&gt;, and although it seems very good on the training data, it predicts poorly on new data. That is exactly the phenomenon of overfitting.&lt;/p&gt;

&lt;h2 id=&quot;1-demonstrating-overfitting&quot;&gt;1. Demonstrating Overfitting&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/overfitting_demonstration.png&quot; alt=&quot;Overfitting Demonstration&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The figure shows the logic of the problem very clearly. With a degree-1 polynomial, the model is too simple, so both the training error and the test error are high; this is the classic underfit state. With degree 3, the model is flexible enough to capture the main trend of the data without starting to memorize noise, so both the training error and the test error are lower. When we increase to degree 10, we begin to see a model that looks very good on the training data but has a high test error, because it has “memorized” random fluctuations that do not repeat in new data. By degree 15, the phenomenon becomes more extreme: the model almost completely loses its ability to &lt;strong&gt;generalize&lt;/strong&gt;. The important point to keep is that the test error usually rises again when the model is too complex, and that is exactly when regularization becomes necessary.&lt;/p&gt;

&lt;h2 id=&quot;2-regularization-the-solution&quot;&gt;2. Regularization: The Solution&lt;/h2&gt;

&lt;p&gt;The core idea of regularization is not to let the model freely use coefficients that are too large just to follow the training data closely. In other words, we add a mechanism that prefers simpler models by penalizing overly extreme coefficient configurations.&lt;/p&gt;

&lt;h3 id=&quot;21-ridge-regression-l2-regularization&quot;&gt;2.1. Ridge Regression (L2 Regularization)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Objective&lt;/strong&gt;:
\(\min_{\beta} \sum_{i=1}^n (y_i - \hat{y}_i)^2 + \lambda \sum_{j=1}^p \beta_j^2\)&lt;/p&gt;

&lt;p&gt;In this expression, the first term forces the model to fit the data, while the second term penalizes the sum of squares of the coefficients to keep them at a moderate scale. The parameter \(\lambda\) controls the strength of the penalty; the larger \(\lambda\) is, the stronger the regularization and the more the model is pushed toward “gentler” solutions.&lt;/p&gt;

&lt;p&gt;From a Bayesian viewpoint, Ridge regression can be understood as placing a &lt;strong&gt;Normal prior&lt;/strong&gt; on the coefficients.&lt;/p&gt;

\[\beta_j \sim \text{Normal}(0, \sigma^2)\]

&lt;h3 id=&quot;22-lasso-regression-l1-regularization&quot;&gt;2.2. Lasso Regression (L1 Regularization)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Objective&lt;/strong&gt;:
\(\min_{\beta} \sum_{i=1}^n (y_i - \hat{y}_i)^2 + \lambda \sum_{j=1}^p |\beta_j|\)&lt;/p&gt;

&lt;p&gt;In Bayesian language, Lasso corresponds to placing a &lt;strong&gt;Laplace prior&lt;/strong&gt; on the coefficients.&lt;/p&gt;

\[\beta_j \sim \text{Laplace}(0, b)\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter07/regularization_priors.png&quot; alt=&quot;Regularization Priors&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The comparison figure of priors shows that regularization in Bayesian statistics is actually a very concrete modeling choice, not a trick added afterwards. The &lt;strong&gt;Normal prior&lt;/strong&gt; in the left panel is centered at 0 and has smooth tails, so it tends to pull coefficients toward 0 but rarely forces them to be exactly 0; this kind of prior is appropriate when we believe that many predictors each have a small effect. The &lt;strong&gt;Laplace prior&lt;/strong&gt; in the middle panel is sharper at 0 and has heavier tails, so it encourages &lt;strong&gt;sparsity&lt;/strong&gt;, meaning many coefficients are pushed more strongly to 0; it is therefore especially useful for &lt;strong&gt;feature selection&lt;/strong&gt;. The comparison panel on the right emphasizes that choosing a prior is really choosing a “regularization philosophy”: a flat prior barely regularizes, while Normal and Laplace encode different degrees and kinds of shrinkage.&lt;/p&gt;

&lt;h3 id=&quot;experiment-a-normal-prior-shrinks-the-coefficients-ridge&quot;&gt;Experiment: a normal prior shrinks the coefficients (ridge)&lt;/h3&gt;

&lt;p&gt;Decrease τ step by step: the curve gradually smooths, and the test error falls and then rises.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;shrink-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-bayesian-regularization-in-pymc&quot;&gt;3. Bayesian Regularization in PyMC&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate data with many predictors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 20 predictors
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Only first 3 predictors matter
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Standardize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Model 1: Weak priors (no regularization)
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_weak&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Weak!
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Weak!
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;trace_weak&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                          &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Model 2: Strong priors (regularization)
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Strong regularization!
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;trace_reg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                         &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compare coefficients
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_weak&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_weak&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_reg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# True coefficients
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictor Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;TRUE COEFFICIENTS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Only first 3 non-zero&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Weak priors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_weak&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictor Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;WEAK PRIORS (No Regularization)&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
                 &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Many non-zero coefficients&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Strong priors (regularization)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictor Index&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Coefficient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;STRONG PRIORS (Regularization)&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
                 &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shrinkage toward 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;REGULARIZATION EFFECT&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weak priors:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Non-zero coefficients: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_weak&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Max |β|: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_weak&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Strong priors (regularization):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Non-zero coefficients: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Max |β|: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;→ Regularization shrinks coefficients toward 0!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;4-choosing-regularization-strength&quot;&gt;4. Choosing Regularization Strength&lt;/h2&gt;

&lt;p&gt;One of the most practical questions is how strongly to regularize, or in Bayesian language, how narrow the prior should be so as to control overfitting without suffocating the real signal.&lt;/p&gt;

&lt;h3 id=&quot;41-cross-validation&quot;&gt;4.1. Cross-Validation&lt;/h3&gt;

&lt;p&gt;A pragmatic approach is to use cross-validation to choose the prior scale so that the out-of-sample predictive ability is best.&lt;/p&gt;

&lt;h3 id=&quot;42-prior-predictive-checks&quot;&gt;4.2. Prior Predictive Checks&lt;/h3&gt;

&lt;p&gt;An approach with a more Bayesian spirit is to use &lt;strong&gt;prior predictive checks&lt;/strong&gt; to see whether the current prior generates reasonable predictions, even before looking at the data.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Prior predictive check
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_check&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_prior&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Sample from prior
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;prior_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample_prior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_prior_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_prior&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Prior predictions
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_prior_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_prior_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.02&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y (standardized)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PRIOR PREDICTIVE CHECK&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
                 &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Do priors generate reasonable data?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Prior means and SDs
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior_means&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_prior_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;prior_sds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_prior_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prior_means&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prior_sds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed mean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed SD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Prior Predicted Mean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Prior Predicted SD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PRIOR PREDICTIONS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean vs SD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;43-checklist-for-choosing-prior-strength-in-an-ml-workflow&quot;&gt;4.3. Checklist for choosing prior strength in an ML workflow&lt;/h3&gt;

&lt;p&gt;In real machine learning practice, prior strength (or regularization strength) should be chosen following a clear procedure rather than random experimentation:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Define prediction target + metric&lt;/strong&gt;: determine the metric appropriate to the problem (RMSE, MAE, log-loss, calibration…).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Split data from the start&lt;/strong&gt;: separate train/validation/test before tuning any parameter.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Fit preprocessing on train only&lt;/strong&gt;: standardization, imputation, and encoding must be learned on train and applied to validation/test to avoid leakage.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tune prior scale on validation&lt;/strong&gt;: sweep a grid of reasonable prior scales and compare out-of-sample performance.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check the prior predictive&lt;/strong&gt;: eliminate priors that generate absurd predictions before looking at detailed fit results.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lock the model on test once&lt;/strong&gt;: evaluate on test only at the final step to preserve objectivity.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The checklist above connects Bayes directly to the ML training workflow: the prior is not just a “theory” part, but a hyperparameter with modeling meaning.&lt;/p&gt;

&lt;h2 id=&quot;5-applied-case-study-part-1-setup-split-and-leakage-control&quot;&gt;5. Applied Case Study (Part 1): Setup, split, and leakage control&lt;/h2&gt;

&lt;p&gt;We use a simulated high-dimensional regression problem: predicting a continuous value from 25 predictors, of which only a few truly carry signal. The goal of Part 1 is to build the data pipeline correctly.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;180&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sparse ground truth: only 6 variables have signal
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 60/20/20 split
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;permutation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;val_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Preprocessing fit on train only (anti-leakage)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_train_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_val_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_test_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_x&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;mu_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sd_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;y_train_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_y&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_val_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_y&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_test_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sd_y&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Decision checkpoint 1&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;If the data has been split and scaled with a train-only procedure, you can start tuning the prior/regularization.&lt;/li&gt;
  &lt;li&gt;If preprocessing was fit on the full data before the split, the validation results will be falsely optimistic because of leakage.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;6-when-is-regularization-needed&quot;&gt;6. When is Regularization Needed?&lt;/h2&gt;

&lt;p&gt;Regularization is especially necessary when the number of predictors is large relative to the sample size, when predictors are strongly correlated with each other causing &lt;strong&gt;multicollinearity&lt;/strong&gt;, when data is scarce so the model easily swings strongly from sample to sample, or when our goal is to find a sparse solution that keeps only a few important variables. Conversely, if the number of predictors is small, the sample is large, the variables are nearly independent of each other, and we have strong theoretical grounds to keep all variables in the model, regularization can play a more secondary role. The key point is that regularization is not always a “tonic”; it is a deliberate response to the risk that the model is too flexible relative to the amount of information the data actually provides.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Regularization prevents overfitting by controlling the scale of the coefficients instead of letting the model freely chase every fluctuation of the training data. Ridge regression can be understood as placing a Normal prior to shrink all coefficients toward 0, while Lasso corresponds to a Laplace prior and encourages a sparser solution. From the Bayesian viewpoint, regularization is not an auxiliary part outside the model, but precisely the consequence of choosing priors that match our degree of belief about the size and structure of the coefficients. The strength of regularization can be tuned by cross-validation or by prior predictive checks, depending on the analysis goal.&lt;/p&gt;

&lt;p&gt;The most important point of the lesson is to recognize that in Bayesian statistics, saying “regularize” is essentially saying “choose the prior responsibly”.&lt;/p&gt;

&lt;p&gt;Next lesson: &lt;strong&gt;Bias-Variance Tradeoff&lt;/strong&gt; (going deeper into validation strategy and model-complexity tuning within the same case study).&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-converting-prior-sd-tau-directly-into-ridge-penalty-lambda&quot;&gt;Worked Numerical Example: Converting Prior SD \(\tau\) Directly Into Ridge Penalty \(\lambda\)&lt;/h3&gt;

&lt;p&gt;Suppose noise SD is \(\sigma = 2.0\) (\(\sigma^2 = 4.0\)), and you compare three zero-centered Normal priors on standardized slopes \(\beta_j \sim \mathcal{N}(0, \tau^2)\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Prior Belief on \(\beta_j\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Prior SD \(\tau\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Prior Variance \(\tau^2\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Equivalent Ridge Penalty \(\lambda = \sigma^2 / \tau^2\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Regularization Strength&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Very Flat&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\tau = 10.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(100.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(4 / 100 = \mathbf{0.04}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Almost none (near OLS)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Weakly Informative&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\tau = 1.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(4 / 1 = \mathbf{4.00}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Moderate healthy shrinkage&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Strongly Skeptical&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\tau = 0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.25\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(4 / 0.25 = \mathbf{16.00}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Strong shrinkage toward 0&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Notice the crystal-clear intuition: &lt;strong&gt;cutting your prior SD \(\tau\) in half quadruples the L2 regularization penalty \(\lambda\)!&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-using-regularizing-priors-effectively&quot;&gt;Explanation: Four Rules for Using Regularizing Priors Effectively&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always standardize predictors before applying shared regularizing priors:&lt;/strong&gt; Putting a single \(\mathcal{N}(0, 1)\) prior on an unstandardized variable in millimeters vs. kilometers penalizes them unfairly by a factor of \(10^{12}\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Do not shrink the intercept \(\alpha\) toward zero unless \(y\) is centered:&lt;/strong&gt; Shrinkage belongs on &lt;em&gt;slopes&lt;/em&gt; \(\beta_j\) (and group offsets), while the intercept sits near \(\bar{y}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prefer Student-\(t\) or Horseshoe when you expect a few huge signals among many noise variables:&lt;/strong&gt; Gaussian priors over-shrink giant real effects when \(\tau\) is tuned tight enough to kill noise.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Let data choose the shrinkage scale hierarchically:&lt;/strong&gt; Instead of guessing \(\tau\) by hand, put a hyperprior \(\tau \sim \mathrm{HalfNormal}(1)\) so the model learns how sparse the world is directly from the data!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If noise variance is \(\sigma^2 = 9\) and you want an equivalent Ridge penalty of \(\lambda = 1\) on standardized slopes, what prior standard deviation \(\tau\) should you use in \(\beta_j \sim \mathcal{N}(0, \tau^2)\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Q81RR3yKn30&quot;&gt;Regularization Part 1: Ridge (L2) Regression&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the L2 penalty pull coefficients toward zero to reduce variance, exactly the overfitting phenomenon the lesson opens with using a high-degree polynomial.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=W_SjooqeOqM&quot;&gt;Ridge Regression is a Gaussian Prior&lt;/a&gt; — DataMListic, English. Watch ridge as a normal prior on the coefficients, supporting the claim that a Bayesian prior is regularization.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8-_hZD0BRK8&quot;&gt;Lasso Regression is a Laplace Prior&lt;/a&gt; — DataMListic, English. Watch lasso correspond to a Laplace prior, used for the part of the lesson comparing ways of shrinking coefficients.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1&lt;/strong&gt;: Generate high-dimensional data (p &amp;gt; n). Fit with weak and strong priors. Compare.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2&lt;/strong&gt;: Implement Lasso prior (Laplace) in PyMC. Compare with Ridge.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3&lt;/strong&gt;: Use cross-validation to choose optimal prior scale.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4&lt;/strong&gt;: Prior predictive checks with different prior scales. Which is reasonable?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5&lt;/strong&gt;: Real data with many predictors. Apply regularization and interpret results.&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., et al. (2020).&lt;/strong&gt; &lt;em&gt;Regression and Other Stories&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 12: Transformations and regression&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 4: Geocentric Models (Priors as regularization)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter07/07_02_bias_variance_tradeoff/&quot;&gt;7.2 Bias-Variance Tradeoff&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 6.3: Model Evaluation for GLMs</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter06/06_03_model_evaluation_glm/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter06/06_03_model_evaluation_glm</id>
   <content type="html">&lt;p&gt;Once you step outside Normal linear regression into Logistic or Poisson GLMs, familiar metrics like ordinary \(R^2\) and raw residual plots stop working—binary outcomes only ever equal &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;, so &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y - p&lt;/code&gt; is never bell-shaped! Evaluating a Bayesian GLM honestly requires &lt;strong&gt;proper probabilistic scoring rules&lt;/strong&gt; (Log-Loss / Deviance, Brier score), &lt;strong&gt;calibration curves&lt;/strong&gt;, &lt;strong&gt;binned/randomized quantile residuals&lt;/strong&gt;, and &lt;strong&gt;Posterior Predictive Checks&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;This lesson builds a complete GLM diagnostic workflow so you know when a classifier is well-calibrated versus overconfident, and when a count model is missing overdispersion.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-four-diagnostic-tools-for-bayesian-glms&quot;&gt;Key ideas: Four Diagnostic Tools for Bayesian GLMs&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Log-Pointwise Predictive Score &amp;amp; Deviance (\(D = -2\sum \log p(y_i\mid\hat{\theta})\)):&lt;/strong&gt; Generalizes RSS to &lt;em&gt;any&lt;/em&gt; likelihood family (Bernoulli, Poisson, Negative Binomial)—strictly proper and directly connects to WAIC/LOO!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Calibration vs. Discrimination (ROC-AUC vs. Calibration Plot):&lt;/strong&gt; ROC-AUC measures &lt;em&gt;ranking&lt;/em&gt; (does a true 1 score higher than a true 0?); &lt;strong&gt;calibration&lt;/strong&gt; measures whether predicted 70% probabilities actually happen 70% of the time!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Binned &amp;amp; Pearson Residuals:&lt;/strong&gt; For binary GLMs, raw residuals \(y_i - p_i\) lie on two curved stripes; grouping observations into bins of predicted \(p_i\) reveals hidden nonlinearity immediately.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GLM Posterior Predictive Checks:&lt;/strong&gt; Simulate \(y^{\text{rep}} \sim \mathrm{Bernoulli}(p^{(s)})\) or \(\mathrm{Poisson}(\lambda^{(s)})\) and check group calibration, max counts, variance/mean ratio, and zero proportions.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After completing this lesson, you will understand how to evaluate &lt;strong&gt;GLM models&lt;/strong&gt; such as logistic regression and Poisson regression in real-world settings. The focus of the lesson is learning to choose the right evaluation criteria for the right type of outcome, from &lt;strong&gt;classification metrics&lt;/strong&gt; such as accuracy, sensitivity, specificity, and ROC curves, to the &lt;strong&gt;calibration plot&lt;/strong&gt;, &lt;strong&gt;deviance&lt;/strong&gt;, and &lt;strong&gt;posterior predictive checks&lt;/strong&gt;. This is a very important step, because a model has real value only when we clearly understand what it does well, what it does not yet do well, and what deviations remain.&lt;/p&gt;

&lt;h2 id=&quot;introduction-how-evaluating-glms-differs-from-linear-regression&quot;&gt;Introduction: How Evaluating GLMs Differs from Linear Regression&lt;/h2&gt;

&lt;p&gt;With linear regression, we are usually used to metrics such as \(R^2\), RMSE, or residual plots to see how well the model fits the data. However, when we move to GLMs, the evaluation criteria must change with the nature of the outcome. For &lt;strong&gt;binary outcomes&lt;/strong&gt;, we care about the ability to discriminate between classes and the calibration of probabilities, so we commonly use accuracy, ROC, or calibration. For &lt;strong&gt;count outcomes&lt;/strong&gt;, we must check how well the distribution fits, the deviance, and signs of &lt;strong&gt;overdispersion&lt;/strong&gt;. Even so, there is one principle common to every GLM: we always need to use &lt;strong&gt;posterior predictive checks&lt;/strong&gt; to compare the data the model generates with the real data.&lt;/p&gt;

&lt;h2 id=&quot;1-evaluating-logistic-regression&quot;&gt;1. Evaluating Logistic Regression&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/model_evaluation_glm.png&quot; alt=&quot;Model Evaluation for GLM&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;11-confusion-matrix&quot;&gt;1.1. Confusion Matrix&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sklearn.metrics&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;confusion_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;roc_curve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;auc&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate binary data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Fit logistic model
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logistic_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Deterministic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;invlogit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Bernoulli&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Posterior predictions
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Confusion matrices with different thresholds
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;thresholds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;thresh&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;thresholds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Predict
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;thresh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Confusion matrix
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;confusion_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;im&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;imshow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Blues&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vmin&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vmax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xticks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_yticks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xticklabels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pred 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pred 1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_yticklabels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True 1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Threshold = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;thresh&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Confusion Matrix&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                          &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Add text
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;va&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                            &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                            &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;white&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Compute metrics
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ravel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sensitivity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;if &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Recall, TPR
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;specificity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;if &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# TNR
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;precision&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;if &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Metrics text
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;metrics_text&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Accuracy: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Sensitivity: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sensitivity&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Specificity: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;specificity&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Precision: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;precision&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;off&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;metrics_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;va&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;family&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;monospace&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;bbox&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;boxstyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;facecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lightblue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;CLASSIFICATION METRICS&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Confusion Matrix Components:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  TN (True Negative): Correctly predicted 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  FP (False Positive): Incorrectly predicted 1 (Type I error)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  FN (False Negative): Incorrectly predicted 0 (Type II error)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  TP (True Positive): Correctly predicted 1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Metrics:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Accuracy = (TP + TN) / Total&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Sensitivity (Recall) = TP / (TP + FN)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Specificity = TN / (TN + FP)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Precision = TP / (TP + FP)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;111-evaluating-by-decision-rule-instead-of-only-by-the-05-threshold&quot;&gt;1.1.1. Evaluating by decision rule instead of only by the 0.5 threshold&lt;/h3&gt;

&lt;p&gt;In Bayesian classification, the 0.5 threshold is reasonable only when the costs of the two kinds of error are nearly symmetric. If the costs differ, we should choose the threshold according to the expected risk.&lt;/p&gt;

&lt;p&gt;Example with two classes (positive/negative):&lt;/p&gt;

&lt;p&gt;We denote the cost of a &lt;strong&gt;false positive&lt;/strong&gt; as \(C_{FP}\) and the cost of a &lt;strong&gt;false negative&lt;/strong&gt; as \(C_{FN}\).&lt;/p&gt;

&lt;p&gt;The optimal rule (without reject) is to predict positive when:&lt;/p&gt;

\[P(y=1\mid x) &amp;gt; \frac{C_{FP}}{C_{FP}+C_{FN}}.\]

&lt;p&gt;If we add a reject action with cost \(C_R\), we classify only when the risk of the decision is less than \(C_R\).&lt;/p&gt;

&lt;p&gt;An important practical point is that the confusion matrix should not be presented as a context-neutral table of counts. A threshold only has meaning when tied to the cost of each kind of mistake, because in many applied problems, a false negative can be far more serious than a false positive, or vice versa.&lt;/p&gt;

&lt;h3 id=&quot;112-a-concrete-example-the-05-threshold-can-make-us-miss-important-cases&quot;&gt;1.1.2. A concrete example: the 0.5 threshold can make us miss important cases&lt;/h3&gt;

&lt;p&gt;Suppose this is a rare-disease screening problem, in which missing a case is about 9 times worse than a false alarm. Then:&lt;/p&gt;

\[\text{optimal threshold}=\frac{C_{FP}}{C_{FP}+C_{FN}}=\frac{1}{1+9}=0.1\]

&lt;p&gt;This means that as soon as \(P(y=1\mid x)&amp;gt;0.1\), we should lean toward the decision “send for further testing”. If the model returns three probabilities \(0.18\), \(0.32\) and \(0.65\) for three patients, then all three should be placed in the group needing further follow-up. If we mechanically keep the 0.5 threshold, the first two would be classified as negative even though the risk of missing them is very large. This example shows that logistic regression is not only about predicting labels, but also about using the posterior probability in line with the decision costs of the problem.&lt;/p&gt;

&lt;h3 id=&quot;113-the-bayes-factor-as-a-measure-of-evidence-at-the-model-level&quot;&gt;1.1.3. The Bayes factor as a measure of evidence at the model level&lt;/h3&gt;

&lt;p&gt;Besides label-based classification metrics, we can compare the evidence between two models/hypotheses with the Bayes factor:&lt;/p&gt;

\[BF_{10}=\frac{p(D\mid M_1)}{p(D\mid M_0)}.\]

&lt;p&gt;When \(BF_{10}&amp;gt;1\), the data supports \(M_1\) more than \(M_0\); when \(BF_{10}&amp;lt;1\), the evidence leans toward \(M_0\). Bayes factor therefore complements ROC/AUC in a very different way: ROC speaks about the ability to discriminate labels, while the Bayes factor speaks about the level of relative evidence for a model or hypothesis.&lt;/p&gt;

&lt;h3 id=&quot;12-roc-curve&quot;&gt;1.2. ROC Curve&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;ROC curve&lt;/strong&gt; is a plot of &lt;strong&gt;Sensitivity&lt;/strong&gt; against \(1-\text{Specificity}\) as we sweep through every possible classification threshold. Instead of settling early on a specific threshold, the ROC gives us a global view of the tradeoff between catching true positive cases and avoiding false alarms. The &lt;strong&gt;AUC&lt;/strong&gt; (Area Under the Curve) is a summary of that entire curve; a value near 0.5 suggests the model is nearly random, while a value approaching 1 shows very strong discriminating ability.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Compute ROC curve
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;thresholds_roc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;roc_curve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;auc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# ROC curve
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ROC (AUC = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Random (AUC = 0.5)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fill_between&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;False Positive Rate (1 - Specificity)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True Positive Rate (Sensitivity)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ROC CURVE&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Higher AUC = Better Model&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lower right&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Threshold selection
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;thresholds_roc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sensitivity (TPR)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;thresholds_roc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Specificity (TNR)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Threshold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;THRESHOLD SELECTION&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trade-off between Sensitivity &amp;amp; Specificity&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ROC CURVE INTERPRETATION&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;AUC = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Excellent discrimination&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Good discrimination&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;roc_auc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Acceptable discrimination&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Poor discrimination&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;13-calibration-plot&quot;&gt;1.3. Calibration Plot&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Calibration&lt;/strong&gt; answers a different question from the ROC: when the model says the probability is 0.7, do about 70% of such cases really occur in practice? A model can discriminate classes quite well and still be poorly calibrated, meaning the probabilities it reports are too optimistic or too cautious. The calibration plot therefore helps us assess the quality of the predicted probabilities themselves, not only the quality of the final classification decision.&lt;/p&gt;

&lt;h3 id=&quot;131-a-concrete-example-a-good-auc-but-still-skewed-probabilities&quot;&gt;1.3.1. A concrete example: a good AUC but still skewed probabilities&lt;/h3&gt;

&lt;p&gt;Imagine a model that predicts for 10 patients with probabilities around \(0.8\), but in the end only 5 are truly positive. The model can still have a fairly good ROC/AUC if the 5 patients with the disease receive higher probabilities than most of those without it. However, in terms of calibration the model is overconfident: it says “80%” but in reality it happens only about “50%” of the time.&lt;/p&gt;

&lt;p&gt;Similarly, if another group is predicted around \(0.2\) but in reality as many as \(0.35\) of the cases occur, the model is underestimating the risk. The core point is that ROC answers the question “does the model rank higher-risk people correctly?”, while calibration answers the question “is the probability number the model gives trustworthy as a real probability?”.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Calibration plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_bins&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_bins&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;bin_centers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;observed_freq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;predicted_prob&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_bins&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;observed_freq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;predicted_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Calibration plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predicted_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed_freq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;150&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Binned data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Perfect calibration&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted Probability&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed Frequency&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;CALIBRATION PLOT&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Do predictions match reality?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Histogram of predicted probabilities
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted Probability&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Frequency&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DISTRIBUTION OF PREDICTIONS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Well-spread or concentrated?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;2-evaluating-poisson-regression&quot;&gt;2. Evaluating Poisson Regression&lt;/h2&gt;

&lt;h3 id=&quot;21-deviance&quot;&gt;2.1. Deviance&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Deviance&lt;/strong&gt; is a measure of model fit within the GLM family, and intuitively it can be understood as the distance between the model under consideration and a saturated model that can fit the data perfectly. The smaller the deviance, the closer the model is to that ideal fit.&lt;/p&gt;

\[D = -2 \log \frac{L(\text{model})}{L(\text{saturated})}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Generate count data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;150&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Fit Poisson model
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_count_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_count_z&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambda_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Deterministic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lambda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trace_poisson&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                             &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Posterior predictions
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lambda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compute deviance
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy.stats&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_dist&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;log_lik_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_dist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logpmf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;log_lik_saturated&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_dist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logpmf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Perfect fit
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deviance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_lik_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_lik_saturated&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POISSON REGRESSION EVALUATION&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Deviance: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deviance&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (Lower = better fit)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Check overdispersion
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Overdispersion check:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Observed mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Observed variance: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Variance/Mean ratio: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Overdispersion detected!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → Poisson assumption reasonable&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;211-a-concrete-example-the-mean-fits-but-the-variance-still-raises-an-alarm&quot;&gt;2.1.1. A concrete example: the mean fits but the variance still raises an alarm&lt;/h3&gt;

&lt;p&gt;Suppose the number of support calls over 7 consecutive days is: \(2, 3, 4, 2, 3, 4, 18\). The average of this series is about \(5.1\), so a Poisson model with \(\lambda\) around 5 might look “not bad” at a glance. But intuition already shows that something is unusual: the first six days are fairly low, and one day jumps to 18.&lt;/p&gt;

&lt;p&gt;In such a situation, the mean alone is not enough to conclude that the model is good. If the posterior predictive distribution produces datasets with a mean near 5 but with a variance and maximum value much smaller than the real data, then the deviance, residual plots, and PPC will all point in the same direction: the model is too narrow relative to the data. This is a very typical sign of overdispersion or of an unmodeled source of variation.&lt;/p&gt;

&lt;h3 id=&quot;22-residual-plots&quot;&gt;2.2. Residual Plots&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Residuals
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;residuals&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;residuals&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Raw residuals
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted λ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Raw Residuals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RAW RESIDUALS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Should be random around 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Pearson residuals
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted λ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pearson Residuals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PEARSON RESIDUALS&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Standardized (should be in [-2, 2])&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# QQ plot
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy_stats&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;scipy_stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;probplot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dist&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Q-Q PLOT&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Check normality of residuals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Histogram of residuals
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pearson_residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy_stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Standard Normal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pearson Residuals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RESIDUAL DISTRIBUTION&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Compare to Normal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;3-posterior-predictive-checks-for-glms&quot;&gt;3. Posterior Predictive Checks for GLMs&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# PPC for Poisson
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ppc_poisson&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample_posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ppc_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Distribution comparison
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                   &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.02&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Count&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PPC: DISTRIBUTION&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed vs Predicted&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Mean check
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pred_means&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred_means&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_mean&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean of Predicted Data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PPC: MEAN&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Does model capture mean?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Variance check
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pred_vars&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred_vars&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_var&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Variance of Predicted Data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PPC: VARIANCE&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Does model capture variance?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Max check
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pred_maxs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred_maxs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;obs_max&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Max of Predicted Data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PPC: MAXIMUM&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Does model capture extremes?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;experiment-posterior-predictive-check-for-glms&quot;&gt;Experiment: posterior predictive check for GLMs&lt;/h3&gt;

&lt;p&gt;Group calibration for logistic and the zero-share statistic for Poisson; compare a correct model with a misspecified one.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;glmppc-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;logistic&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;GLM evaluation cannot simply reuse the whole toolkit of linear regression. For logistic regression, we need to think at the same time about the confusion matrix, classification measures such as sensitivity or specificity, overall discriminating ability through ROC/AUC, and the quality of predicted probabilities through the calibration plot. For Poisson regression, the focus shifts to deviance, signs of overdispersion, and residual plots to see whether the model is missing some structure in the data. And for every GLM, &lt;strong&gt;posterior predictive checks&lt;/strong&gt; remain the final and most important layer of checking, because they let us ask directly whether the data the model generates resembles the real data in the important features.&lt;/p&gt;

&lt;p&gt;The point to keep is that each type of outcome requires its own evaluation standard, and no single metric is enough to conclude that a model is “good” or “bad”. The right habit is to always combine specialized metrics with posterior checks to look at the model from several angles.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Chapter 06 Complete!&lt;/strong&gt; GLMs: Logistic, Poisson, Evaluation.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-computing-exact-bernoulli-log-loss--deviance-on-3-observations&quot;&gt;Worked Numerical Example: Computing Exact Bernoulli Log-Loss &amp;amp; Deviance on 3 Observations&lt;/h3&gt;

&lt;p&gt;Compare Model A vs. Model B predicting 3 binary outcomes \(y = [1,\; 0,\; 1]\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Model A:&lt;/strong&gt; \(p_A = [0.80,\; 0.20,\; 0.70]\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Model B:&lt;/strong&gt; \(p_B = [0.95,\; 0.80,\; 0.90]\) (confidently wrong on observation 2!)&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Obs \(i\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Truth \(y_i\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Model A \(-\ln p(y_i)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Model B \(-\ln p(y_i)\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-\ln(0.80) = 0.223\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-\ln(0.95) = 0.051\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-\ln(0.80) = 0.223\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-\ln(0.20) = \mathbf{1.609}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-\ln(0.70) = 0.357\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-\ln(0.90) = 0.105\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Total NLL&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;—&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.803\)&lt;/strong&gt; (Deviance \(= 1.606\))&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(1.765\)&lt;/strong&gt; (Deviance \(= 3.530\))&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Model A achieves &lt;strong&gt;less than half the deviance&lt;/strong&gt; of Model B because proper log scoring heavily punishes confident mistakes!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-evaluating-bayesian-glms&quot;&gt;Explanation: Four Rules for Evaluating Bayesian GLMs&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Never rely on 0.5-threshold accuracy for imbalanced binary data:&lt;/strong&gt; Use Log-Loss, Brier score, calibration plots, and PR-AUC.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check dispersion (Pearson \(\chi^2 / df\)) on every Poisson GLM:&lt;/strong&gt; A ratio near \(1.0\) supports Poisson; a ratio \(&amp;gt; 1.5\text{–}2.0\) screams overdispersion \(\to\) switch to Negative Binomial!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate out-of-sample (LOO-CV / held-out test set), not just in-sample deviance:&lt;/strong&gt; Adding predictors always lowers in-sample deviance even when hurting real predictions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Inspect subgroup calibration:&lt;/strong&gt; A model calibrated globally at 50% can still overpredict Group A by +15% and underpredict Group B by -15%—a sure sign of a missing group intercept or interaction!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the 3-observation table above, if a model assigns probability &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p = 0.00&lt;/code&gt; to an event that actually happens (\(y = 1\)), what happens to its Log-Loss \(-\ln(p)\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Kdsp6soqA7o&quot;&gt;Machine Learning Fundamentals: The Confusion Matrix&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the confusion matrix before computing accuracy, exactly the part of the lesson that changes the criteria when the outcome is binary.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=AunotauS5yI&quot;&gt;Probability Calibration : Data Science Concepts&lt;/a&gt; — ritvikmath, English. Watch probability calibration, supporting the argument that a correct classification score does not yet tell whether the probability is trustworthy.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JC56jS2gVUE&quot;&gt;Deviance Residuals&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch deviance residuals, used when the lesson evaluates count or logistic GLMs beyond the classification metrics.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1&lt;/strong&gt;: Fit logistic regression. Compute ROC, AUC. Interpret.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2&lt;/strong&gt;: Create calibration plot. Is model well-calibrated?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3&lt;/strong&gt;: Fit Poisson regression. Check for overdispersion. If present, what to do?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4&lt;/strong&gt;: Perform comprehensive PPC for GLM. Check mean, variance, max, distribution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5&lt;/strong&gt;: Compare two logistic models using ROC curves. Which is better?&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., et al. (2020).&lt;/strong&gt; &lt;em&gt;Regression and Other Stories&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 11: Assumptions, diagnostics, and model evaluation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 7: Ulysses’ Compass (Model Comparison)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next chapter: &lt;a href=&quot;/contents/en/chapter07/&quot;&gt;Chapter 07: Regularization&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 6.2: Poisson Regression - Count Data</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter06/06_02_poisson_regression/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter06/06_02_poisson_regression</id>
   <content type="html">&lt;p&gt;Counts—hospital ER visits, daily bug reports, species sightings, website clicks—are strictly non-negative integers whose variance naturally grows with their mean. &lt;strong&gt;Bayesian Poisson Regression&lt;/strong&gt; handles count data cleanly via the &lt;strong&gt;log link&lt;/strong&gt; \(\ln \lambda_i = \alpha + \beta x_i \iff \lambda_i = e^{\alpha + \beta x_i}\), guaranteeing positive rates everywhere and turning additive linear effects into &lt;strong&gt;multiplicative rate ratios&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;This lesson builds complete mastery over log-link Poisson GLMs, &lt;strong&gt;exposure offsets&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+ log(exposure)&lt;/code&gt;), and diagnosing &lt;strong&gt;overdispersion&lt;/strong&gt; (when you must upgrade from Poisson to Negative Binomial).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-log-links-exposure-offsets-and-overdispersion&quot;&gt;Key ideas: Log Links, Exposure Offsets, and Overdispersion&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Log Link Guarantees \(\lambda_i &amp;gt; 0\):&lt;/strong&gt; Writing \(\lambda_i = \exp(\alpha + \beta x_i)\) makes +1 unit of \(x\) multiply the expected count by \(e^\beta\) (Incidence Rate Ratio — IRR).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why Priors Must Be Tight on the Log Scale:&lt;/strong&gt; Because \(e^{10} \approx 22{,}026\) and \(e^{20} \approx 4.85\times 10^8\), a careless \(\beta \sim \mathcal{N}(0, 10^2)\) prior predicts billions of events per second! Weakly informative priors like \(\beta \sim \mathcal{N}(0, 0.5)\) keep prior predictive counts realistic.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exposure Offsets (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ln(T_i)&lt;/code&gt;):&lt;/strong&gt; When observations cover different time spans or populations (e.g., 7 days vs. 30 days), model the &lt;em&gt;rate&lt;/em&gt; \(\lambda_i / T_i = e^{\alpha + \beta x_i} \iff \ln\lambda_i = \ln(T_i) + \alpha + \beta x_i\)—adding \(\ln(T_i)\) with a fixed coefficient of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Overdispersion \(\to\) Gamma–Poisson (Negative Binomial):&lt;/strong&gt; Poisson enforces \(\mathrm{Var}(Y_i) = \lambda_i\); if real counts show extra variance, switch to Negative Binomial (\(\mathrm{Var} = \lambda + \lambda^2/\phi\)) so credible intervals aren’t falsely narrow!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After completing this lesson, you will understand &lt;strong&gt;Poisson Regression&lt;/strong&gt; as the standard model for &lt;strong&gt;count data&lt;/strong&gt;, that is, data recording the number of times an event occurs. You will see why linear regression is not suitable when the outcome takes only non-negative integers, why the &lt;strong&gt;log link function&lt;/strong&gt; helps the model produce valid predictions, and why the model’s coefficients should be interpreted through the &lt;strong&gt;rate ratio&lt;/strong&gt; rather than a simple additive difference. This is the second important GLM after logistic regression.&lt;/p&gt;

&lt;h2 id=&quot;introduction-count-data-everywhere&quot;&gt;Introduction: Count Data Everywhere&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Count data&lt;/strong&gt; appears in many real-world settings, such as the number of customers arriving at a store per hour, the number of emails received per day, the number of accidents on a highway per month, the number of goals in a football match, or the number of mutations in a DNA segment. What these variables have in common is \(y \in \{0,1,2,3,\ldots\}\), that is, they are non-negative integers, usually with no clear upper bound, and their variance usually grows as the mean grows. This leads to the familiar question: can we use linear regression for this kind of data?&lt;/p&gt;

&lt;h2 id=&quot;1-the-problem-of-linear-regression-for-count-data&quot;&gt;1. The Problem of Linear Regression for Count Data&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/poisson_regression_basics.png&quot; alt=&quot;Poisson Regression Basics&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The basic difficulty of linear regression in this setting is that a linear model can produce negative predictions, while the number of occurrences of an event cannot be less than 0. The figure shows that in the left panel, the linear regression line can enter the region of negative values, while in the right panel, Poisson regression uses the &lt;strong&gt;log link&lt;/strong&gt; to ensure that the intensity parameter \(\lambda\) is always positive. In other words, instead of predicting the count directly, we model the log of the expected rate, so the output is always consistent with the nature of the data.&lt;/p&gt;

&lt;h2 id=&quot;2-poisson-regression-generative-model&quot;&gt;2. Poisson Regression: Generative Model&lt;/h2&gt;

&lt;h3 id=&quot;21-log-link-function&quot;&gt;2.1. Log Link Function&lt;/h3&gt;

&lt;p&gt;The core idea of Poisson regression is to keep the linear part inside, but use the &lt;strong&gt;log link function&lt;/strong&gt; to ensure that the final quantity, the expected rate \(\lambda\), is always greater than 0.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Log link&lt;/strong&gt;:
\(\log(\lambda) = \alpha + \beta x\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Inverse&lt;/strong&gt; (exponential):
\(\lambda = e^{\alpha + \beta x}\)&lt;/p&gt;

&lt;h3 id=&quot;22-generative-story&quot;&gt;2.2. Generative Story&lt;/h3&gt;

&lt;p&gt;In the language of the &lt;strong&gt;generative story&lt;/strong&gt;, the model is read as follows. From the predictor \(x\), we create a linear quantity \(\eta=\alpha+\beta x\). This quantity is then passed through the exponential function to produce the expected rate \(\lambda=\exp(\eta)\). Finally, the observed count is generated from a Poisson distribution, that is \(y\sim\text{Poisson}(\lambda)\). Separating these three steps clearly helps us see that the model both keeps the linear part that is convenient for inference and respects the specific probabilistic structure of count data.&lt;/p&gt;

&lt;p&gt;The Poisson distribution has the form:
\(P(y = k \mid \lambda) = \frac{\lambda^k e^{-\lambda}}{k!}\)&lt;/p&gt;

&lt;p&gt;A distinctive feature of this distribution is that the mean and the variance are both equal to \(\lambda\); this property is often called &lt;strong&gt;equidispersion&lt;/strong&gt; (meaning the mean equals the variance).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/exponential_function_parameters.png&quot; alt=&quot;Exponential Function Parameters&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The figure helps us read the exponential function more intuitively. In the left panel, the basic function \(\lambda=e^\eta\) is always positive and passes through the point \(\lambda=1\) when \(\eta=0\), so it can be seen as the baseline rate level. In the middle panel, changing \(\alpha\), the &lt;strong&gt;intercept&lt;/strong&gt;, mainly shifts the whole curve up or down, thereby changing the baseline level of the rate. In the right panel, changing \(\beta\), the &lt;strong&gt;slope&lt;/strong&gt;, makes the rate increase faster or slower with \(x\), so it reflects the strength of the relationship between the predictor and the intensity of the event.&lt;/p&gt;

&lt;h2 id=&quot;3-bayesian-poisson-regression-in-pymc&quot;&gt;3. Bayesian Poisson Regression in PyMC&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;150&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Standardize predictor
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Bayesian Poisson regression
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Priors
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# log(λ) ~ 2 → λ ~ 7
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Linear predictor
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Exponential transformation
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;lambda_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Deterministic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lambda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Likelihood
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Poisson&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Sample
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Summary
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR SUMMARY&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize posteriors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot_posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;suptitle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior Distributions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.05&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Trace plots
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;compact&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
             &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;suptitle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trace Plots (Check Convergence)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;experiment-the-poisson-regression-posterior-and-the-rate-ratio&quot;&gt;Experiment: the Poisson regression posterior and the rate ratio&lt;/h3&gt;

&lt;p&gt;Add count data points one at a time; the bundle of λ(x) curves and the rate ratio exp(b) gradually narrow.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;glm-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;poisson&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-interpretation-rate-ratios&quot;&gt;4. Interpretation: Rate Ratios&lt;/h2&gt;

&lt;h3 id=&quot;41-rate-ratio&quot;&gt;4.1. Rate Ratio&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;On log scale&lt;/strong&gt;:
\(\log(\lambda) = \alpha + \beta x\)&lt;/p&gt;

&lt;p&gt;On the log scale, each time \(x\) increases by 1 unit, the log of the expected rate increases by \(\beta\) units.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;On rate scale&lt;/strong&gt;:
\(\lambda = e^{\alpha + \beta x}\)&lt;/p&gt;

&lt;p&gt;When returning to the original scale, this means the expected rate is multiplied by \(e^\beta\). This quantity \(e^\beta\) is the &lt;strong&gt;rate ratio&lt;/strong&gt;, and it is the most natural way to interpret a coefficient of Poisson regression.&lt;/p&gt;

&lt;h3 id=&quot;42-a-concrete-example-how-visits-to-a-shop-increase&quot;&gt;4.2. A concrete example: how visits to a shop increase&lt;/h3&gt;

&lt;p&gt;Suppose the posterior mean of the model is:&lt;/p&gt;

\[\log(\lambda)=2.30 + 0.25x\]

&lt;p&gt;where \(x\) is the number of advertising campaigns running in the week. Then:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;If \(x=0\) then \(\lambda=e^{2.30}\approx 10\), meaning the shop expects about 10 visits per day.&lt;/li&gt;
  &lt;li&gt;If \(x=1\) then \(\lambda=e^{2.55}\approx 12.8\).&lt;/li&gt;
  &lt;li&gt;If \(x=2\) then \(\lambda=e^{2.80}\approx 16.4\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here \(e^{0.25}\approx 1.28\), so each time one more advertising campaign is added, the expected number of visits is multiplied by about 1.28, that is, an increase of nearly 28%. This does not mean it always increases by a fixed 0.25 visits or always by exactly 2.8 visits. Because the effect in Poisson regression is &lt;strong&gt;multiplicative&lt;/strong&gt; rather than &lt;strong&gt;additive&lt;/strong&gt;, the absolute increase depends on the starting baseline: from 10 to 12.8 is an increase of about 2.8 visits, while from 12.8 to 16.4 is an increase of about 3.6 visits.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Compute rate ratios
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RATE RATIO INTERPRETATION&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β (log scale): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Rate Ratio (e^β): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;95% CI: [&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
      &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;97.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Interpretation:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  1 SD increase in x → rate multiply by &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% increase in rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% decrease in rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Beta (log scale)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;skyblue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β (log scale)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;COEFFICIENT β&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Log Scale)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Rate ratio
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lightgreen&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rate_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Rate Ratio (e^β)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RATE RATIO&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Multiplicative Effect)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-posterior-predictive-checks&quot;&gt;5. Posterior Predictive Checks&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Posterior predictive
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;poisson_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ppc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample_posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Predicted rates
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lambda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_lower&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lambda_upper&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;97.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argsort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;40&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior mean λ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fill_between&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_lower&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_upper&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;95% CI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y (counts)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PREDICTED RATES&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;with Uncertainty&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Observed vs Predicted
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ppc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_pred_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Perfect prediction&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted E[y]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR PREDICTIVE CHECK&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed vs Predicted&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Distribution comparison
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                   &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y (counts)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DISTRIBUTION CHECK&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed vs PPC samples&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Residuals
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;residuals&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;residuals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted λ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Residuals (y - λ)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RESIDUAL PLOT&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Check for patterns&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;6-overdispersion-when-variance--mean&quot;&gt;6. Overdispersion: When Variance &amp;gt; Mean&lt;/h2&gt;

&lt;p&gt;A central assumption of Poisson regression is that the variance equals the mean. In real data, this assumption is often broken because the variance is larger than the mean, a phenomenon called &lt;strong&gt;overdispersion&lt;/strong&gt;. When that happens, the Poisson model tends to be overconfident and underestimate uncertainty. Two common remedies are to use &lt;strong&gt;Negative Binomial regression&lt;/strong&gt; when we need to let the variance exceed the mean flexibly, or to use &lt;strong&gt;Zero-Inflated Poisson&lt;/strong&gt; if the data has more zeros than ordinary Poisson can explain.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Check overdispersion
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;OVERDISPERSION CHECK&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed data:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Variance: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Variance/Mean ratio: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;→ Overdispersion detected!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Consider Negative Binomial or Zero-Inflated models&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;→ Poisson assumption reasonable&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;experiment-poisson-or-negative-binomial&quot;&gt;Experiment: Poisson or Negative Binomial?&lt;/h3&gt;

&lt;p&gt;From var/mean to the posterior predictive check: Poisson is rejected, and Negative Binomial can describe the dispersion.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;overdisp-explainer&quot; data-lang=&quot;en&quot; data-data=&quot;nb&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Poisson regression is the natural model for count data because it addresses exactly the weakness of linear regression: the prediction of a linear model can be negative, while count data cannot. By using the &lt;strong&gt;log link&lt;/strong&gt;, modeling \(\log(\lambda)=\alpha+\beta x\) and then deriving \(\lambda\) on the original scale, Poisson regression ensures that the expected rate is always positive. The model’s coefficients are best understood through the &lt;strong&gt;rate ratio&lt;/strong&gt; \(e^\beta\), and the most important assumption that always needs checking is whether the variance is approximately equal to the mean. If the data is overdispersed, we must think of more flexible models.&lt;/p&gt;

&lt;p&gt;The core point to remember is that the log link function is not just a mathematical trick, but the mechanism that makes the linear part of the model compatible with the nature of count data and rate data.&lt;/p&gt;

&lt;p&gt;Next lesson: &lt;strong&gt;Model Evaluation for GLMs&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-computing-multiplicative-rates--exposure-offsets-by-hand&quot;&gt;Worked Numerical Example: Computing Multiplicative Rates &amp;amp; Exposure Offsets by Hand&lt;/h3&gt;

&lt;p&gt;Suppose a website’s daily bug count follows \(\ln\lambda = 1.0 + 0.5 x + \ln(T)\) where \(x\) is code-complexity score and \(T\) is observation window in days:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;For \(T = 1\) day (\(\ln 1 = 0\)):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;At \(x = 0\): \(\lambda = e^{1.0} \approx \mathbf{2.72}\) bugs/day.&lt;/li&gt;
      &lt;li&gt;At \(x = 1\): \(\lambda = e^{1.5} \approx \mathbf{4.48}\) bugs/day (multiplied by \(e^{0.5} \approx \mathbf{1.649\times}\), i.e., &lt;strong&gt;+64.9%&lt;/strong&gt;!).&lt;/li&gt;
      &lt;li&gt;At \(x = 2\): \(\lambda = e^{2.0} \approx \mathbf{7.39}\) bugs/day (multiplied by \(1.649\times\) again!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;For \(T = 7\) days at \(x = 0\):&lt;/strong&gt; Adding offset \(\ln(7)\) gives \(\lambda = e^{1.0 + \ln 7} = 7 \times 2.72 = \mathbf{19.03}\) bugs/week—scaling linearly with exposure time!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-bayesian-count-regression&quot;&gt;Explanation: Four Rules for Bayesian Count Regression&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check prior predictive counts &lt;em&gt;before&lt;/em&gt; running MCMC:&lt;/strong&gt; An exponential link explodes fast—verify your prior doesn’t simulate \(10^{12}\) events!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never divide counts by exposure and feed the ratio into Poisson:&lt;/strong&gt; Poisson requires &lt;em&gt;integer&lt;/em&gt; counts; keep raw integer \(y_i\) as the outcome and put &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.log(exposure)&lt;/code&gt; on the right-hand side as an offset!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always check for overdispersion and excess zeros via PPC:&lt;/strong&gt; Compare observed variance-to-mean ratio and observed zero fraction against replicated Poisson draws—upgrade to Negative Binomial or Zero-Inflated Poisson if Poisson fails!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Watch extreme leverage points:&lt;/strong&gt; Because \(\exp(\beta x)\) curves steeply upward, a single high-\(x\) observation carries huge influence in Poisson GLMs.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In a Poisson regression with log link, if a predictor has slope \(\beta = -0.20\), by roughly what percentage does the expected count &lt;em&gt;decrease&lt;/em&gt; for each +1 unit increase in that predictor? &lt;em&gt;(Hint: compute \(e^{-0.20} \approx 0.819\).)&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Obpz_Uvo2rQ&quot;&gt;Poisson regression - clearly explained&lt;/a&gt; — TileStats, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch Poisson regression for count data and why a straight line cannot keep counts non-negative.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=uGKnoAw-PFQ&quot;&gt;Regression with Count Data: Poisson and Negative Binomial&lt;/a&gt; — Matthew E. Clapham, English. Watch the Poisson count model next to the Negative Binomial, supporting the part of the lesson where the variance exceeds the mean.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jokxu18egu0&quot;&gt;Statistical Rethinking 2023 - 10 - Counts &amp;amp; Hidden Confounds&lt;/a&gt; — Richard McElreath, English. Watch count models together with hidden confounds, used for the passage that writes Poisson as a Bayesian GLM.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1&lt;/strong&gt;: Generate count data. Fit Poisson regression. Interpret rate ratio.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2&lt;/strong&gt;: Compare linear vs Poisson predictions. Visualize differences.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3&lt;/strong&gt;: Multiple predictors Poisson regression. Interpret each coefficient.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4&lt;/strong&gt;: Real data - predict number of customer visits from time/weather features.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5&lt;/strong&gt;: Check for overdispersion. If present, try Negative Binomial model.&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., &amp;amp; Hill, J. (2006).&lt;/strong&gt; &lt;em&gt;Data Analysis Using Regression and Multilevel/Hierarchical Models&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 6: Generalized linear models&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 11: God Spiked the Integers&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter06/06_03_model_evaluation_glm/&quot;&gt;6.3 Model Evaluation for GLMs&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 6.1: Logistic Regression - Binary Outcomes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter06/06_01_logistic_regression/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter06/06_01_logistic_regression</id>
   <content type="html">&lt;p&gt;Linear regression happily predicts probabilities of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.42&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-0.18&lt;/code&gt; when fed binary outcomes like &lt;em&gt;survived/died&lt;/em&gt; or &lt;em&gt;clicked/ignored&lt;/em&gt;. &lt;strong&gt;Bayesian Logistic Regression&lt;/strong&gt; fixes that cleanly by modeling the &lt;strong&gt;log-odds (logit)&lt;/strong&gt; linearly—\(\ln\frac{p_i}{1-p_i} = \alpha + \beta x_i\)—and passing it through the inverse-logit (sigmoid) curve \(p_i = \frac{1}{1+e^{-\eta_i}} \in (0, 1)\).&lt;/p&gt;

&lt;p&gt;Because the sigmoid is nonlinear, every Bayesian logistic model holds a crucial surprise: &lt;strong&gt;a constant change in log-odds produces a &lt;em&gt;different&lt;/em&gt; jump in probability depending on where you start on the S-curve!&lt;/strong&gt; This lesson masters link functions, odds ratios, and sensible log-odds priors.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-link-functions-odds-ratios-and-log-odds-priors&quot;&gt;Key ideas: Link Functions, Odds Ratios, and Log-Odds Priors&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bernoulli/Binomial Likelihood + Logit Link:&lt;/strong&gt; Connects an unconstrained linear predictor \(\eta_i \in (-\infty, \infty)\) to a valid probability \(p_i = \sigma(\eta_i) \in (0,1)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multiplicative Odds Ratios (\(e^\beta\)):&lt;/strong&gt; Increasing \(x\) by +1 adds \(\beta\) to log-odds, which &lt;strong&gt;multiplies odds&lt;/strong&gt; \(\frac{p}{1-p}\) by \(e^\beta\)—regardless of the baseline probability!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why Priors Must Be Narrower on the Logit Scale:&lt;/strong&gt; Because \(\sigma(+5) = 0.993\) and \(\sigma(-5) = 0.007\), a seemingly “vague” Normal prior \(\alpha \sim \mathcal{N}(0, 10^2)\) piles nearly all prior probability onto the extreme walls &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;! Weakly informative priors like \(\alpha \sim \mathcal{N}(0, 1.5),\; \beta \sim \mathcal{N}(0, 1.0)\) keep prior predictive probabilities sensible!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Divide-by-4 Rule (Gelman):&lt;/strong&gt; Near \(p = 0.5\) (steepest point of the sigmoid, where \(\sigma&apos;(0) = 0.25\)), a +1 unit change in \(x\) changes probability by &lt;strong&gt;at most \(\beta / 4\)&lt;/strong&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After completing this lesson, you will understand &lt;strong&gt;Logistic Regression&lt;/strong&gt; as a foundational model for &lt;strong&gt;binary outcomes&lt;/strong&gt; such as yes/no, success/failure, or 0/1. The focus of the lesson is not merely to swap in another regression formula, but to understand why linear regression is not suitable for binary data, why we need a &lt;strong&gt;link function&lt;/strong&gt;, and why the model’s coefficients must be interpreted through the &lt;strong&gt;odds ratio&lt;/strong&gt; rather than with ordinary linear intuition. This is also the first doorway into the family of &lt;strong&gt;Generalized Linear Models (GLMs)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;introduction-the-problem-of-linear-regression-for-binary-data&quot;&gt;Introduction: The Problem of Linear Regression for Binary Data&lt;/h2&gt;

&lt;p&gt;Suppose we want to predict whether a person will buy a product, pass an exam, or have a disease. In all of these examples, the &lt;strong&gt;outcome&lt;/strong&gt; takes only two values, that is \(y \in \{0,1\}\). The natural question is whether we can simply use the familiar linear regression.&lt;/p&gt;

\[y = \alpha + \beta x + \epsilon\]

&lt;p&gt;The problem appears immediately: linear regression can predict any value on the real line, from negative infinity to positive infinity, while a probability must lie in the interval \([0,1]\). This shows that we need a model that keeps a linear predictive part inside, but has a mechanism for transforming the final result into a valid probability.&lt;/p&gt;

&lt;h2 id=&quot;1-why-linear-regression-does-not-work&quot;&gt;1. Why Linear Regression Does Not Work&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/logistic_regression_basics.png&quot; alt=&quot;Logistic Regression Basics&quot; /&gt;&lt;/p&gt;

&lt;p&gt;For binary data, the core difficulty of linear regression is that the model does not know that our output must be a probability. In the left panel, the linear regression line can produce predictions below 0 or above 1, which are meaningless values if we interpret them as probabilities. In the right panel, logistic regression fixes this by using the &lt;strong&gt;logistic function&lt;/strong&gt; to turn a &lt;strong&gt;linear predictor&lt;/strong&gt; into a valid probability, so that every prediction always lies within \([0,1]\).&lt;/p&gt;

&lt;h2 id=&quot;2-logistic-regression-generative-model&quot;&gt;2. Logistic Regression: Generative Model&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/link_functions_comparison.png&quot; alt=&quot;Link Functions Comparison&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;21-link-function&quot;&gt;2.1. Link Function&lt;/h3&gt;

&lt;p&gt;The central idea of logistic regression is still to build a linear expression at the inner level, but then pass it through a &lt;strong&gt;link function&lt;/strong&gt; to ensure the final output is a probability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Logit link function&lt;/strong&gt;:
\(\text{logit}(p) = \log\left(\frac{p}{1-p}\right) = \alpha + \beta x\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Inverse&lt;/strong&gt; (logistic function):
\(p = \frac{1}{1 + e^{-(\alpha + \beta x)}} = \frac{e^{\alpha + \beta x}}{1 + e^{\alpha + \beta x}}\)&lt;/p&gt;

&lt;h3 id=&quot;22-generative-story&quot;&gt;2.2. Generative Story&lt;/h3&gt;

&lt;p&gt;We can read the model in the spirit of a &lt;strong&gt;generative story&lt;/strong&gt; as follows. First, from the predictor \(x\) we create a linear quantity \(\eta=\alpha+\beta x\). Next, this quantity is transformed through the logistic function to produce the probability \(p=\text{logistic}(\eta)\). Finally, the binary observation is generated from a Bernoulli distribution, that is \(y\sim\text{Bernoulli}(p)\). Writing it this way helps us see that logistic regression is not a “formula-transformation trick”, but a complete probabilistic model.&lt;/p&gt;

&lt;h3 id=&quot;23-the-bayes-classification-rule-from-prior-likelihood-posterior&quot;&gt;2.3. The Bayes classification rule from prior-likelihood-posterior&lt;/h3&gt;

&lt;p&gt;For class \(c_i\) and feature \(x\), the class posterior probability has the form:&lt;/p&gt;

\[P(c_i\mid x)=\frac{P(x\mid c_i)P(c_i)}{\sum_j P(x\mid c_j)P(c_j)}
\propto P(x\mid c_i)P(c_i).\]

&lt;p&gt;With 0-1 loss, the optimal classification rule is to choose the class with the largest posterior:&lt;/p&gt;

\[\hat c(x)=\arg\max_i\;P(c_i\mid x).\]

&lt;p&gt;This point is a direct bridge from Bayes theorem (Chapters 1-2) to the classification problem of Session 8.&lt;/p&gt;

&lt;h3 id=&quot;24-session-8-example-prior-shift-in-fruit-classification&quot;&gt;2.4. Session 8 example: prior shift in fruit classification&lt;/h3&gt;

&lt;p&gt;Suppose there are 2 classes: Apple (\(c_1\)) and Orange (\(c_2\)). The same feature \(x\) gives the likelihood ratio:&lt;/p&gt;

\[\frac{P(x\mid c_1)}{P(x\mid c_2)}=2.\]

&lt;p&gt;&lt;strong&gt;Context A&lt;/strong&gt; (a temperate-zone supermarket): \(P(c_1)=0.8,\;P(c_2)=0.2\).&lt;/p&gt;

&lt;p&gt;Then the posterior odds:&lt;/p&gt;

\[\frac{P(c_1\mid x)}{P(c_2\mid x)}=2\times\frac{0.8}{0.2}=8.\]

&lt;p&gt;&lt;strong&gt;Context B&lt;/strong&gt; (a tropical-zone market): \(P(c_1)=0.2,\;P(c_2)=0.8\).&lt;/p&gt;

&lt;p&gt;Then:&lt;/p&gt;

\[\frac{P(c_1\mid x)}{P(c_2\mid x)}=2\times\frac{0.2}{0.8}=0.5.\]

&lt;p&gt;Conclusion: with the same sensor evidence \(x\), changing the class prior can reverse the classification decision.&lt;/p&gt;

&lt;h3 id=&quot;25-from-posterior-to-a-minimum-risk-decision-rule&quot;&gt;2.5. From posterior to a minimum-risk decision rule&lt;/h3&gt;

&lt;p&gt;When the costs of errors differ, a fixed threshold of 0.5 should not be used. With the action set \(a\), choose:&lt;/p&gt;

\[a^*(x)=\arg\min_a\sum_i L(a,c_i)P(c_i\mid x).\]

&lt;h4 id=&quot;example-two-classes-three-actions-with-reject&quot;&gt;Example: two classes, three actions (with reject)&lt;/h4&gt;

&lt;p&gt;Two true states: \(c_1, c_2\). Three actions: choose \(c_1\), choose \(c_2\), or &lt;strong&gt;reject&lt;/strong&gt; (defer to measure more).&lt;/p&gt;

&lt;p&gt;In this illustrative example, we assume the &lt;strong&gt;loss matrix&lt;/strong&gt; is chosen in a very simple way: a correct prediction costs 0, a wrong prediction costs 10, and the decision to &lt;strong&gt;reject&lt;/strong&gt; costs 3 because we must measure more or wait for more information.&lt;/p&gt;

&lt;p&gt;Suppose the posterior at a point \(x\) is \(P(c_1\mid x)=0.55,\;P(c_2\mid x)=0.45\).&lt;/p&gt;

&lt;p&gt;Then:&lt;/p&gt;

\[R(a=c_1\mid x)=10\cdot 0.45=4.5,\]

\[R(a=c_2\mid x)=10\cdot 0.55=5.5,\]

\[R(a=\text{reject}\mid x)=3.\]

&lt;p&gt;So the optimal action is to reject because it has the lowest expected risk. This is the standard “two-class/three-action” example of Session 8.&lt;/p&gt;

&lt;h3 id=&quot;26-the-discriminant-and-log-discriminant-forms&quot;&gt;2.6. The discriminant and log-discriminant forms&lt;/h3&gt;

&lt;p&gt;In practice, we often compare the discriminants directly:&lt;/p&gt;

\[g_i(x)=\log P(x\mid c_i)+\log P(c_i),\]

&lt;p&gt;and choose the class with the largest \(g_i(x)\).&lt;/p&gt;

&lt;p&gt;Because the log is a monotonic transformation, maximizing the posterior is equivalent to maximizing the log-discriminant, and it is also numerically more stable when probabilities are very small.&lt;/p&gt;

&lt;h3 id=&quot;27-the-gaussian-case-linear-or-quadratic-boundary&quot;&gt;2.7. The Gaussian case: linear or quadratic boundary&lt;/h3&gt;

&lt;p&gt;If \(P(x\mid c_i)\) is multivariate Gaussian, then the shape of the decision boundary depends on the covariance structure. When the classes use a &lt;strong&gt;shared covariance&lt;/strong&gt; with \(\Sigma_i=\Sigma\), the decision boundary is linear, close to the intuition of LDA. Conversely, when each class has its own covariance, that is \(\Sigma_i\) differs, the decision boundary usually becomes quadratic, close to the intuition of QDA. This view is especially useful because it connects the posterior rule at the probability level with the geometry of the classification boundary in feature space.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/logistic_function_parameters.png&quot; alt=&quot;Logistic Function Parameters&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This figure helps us read the logistic function more intuitively. In the left panel, the function \(p=\frac{1}{1+e^{-\eta}}\) has the familiar S shape, passing through \(p=0.5\) when \(\eta=0\) and asymptotically approaching 0 and 1 at the two ends. In the middle panel, changing \(\alpha\), the &lt;strong&gt;intercept&lt;/strong&gt;, mainly shifts the curve to the left or right, so it can be understood as changing the baseline probability level. In the right panel, changing \(\beta\), the &lt;strong&gt;slope&lt;/strong&gt;, makes the curve flatter or steeper, thereby reflecting the strength of the relationship between the predictor and the probability of the outcome.&lt;/p&gt;

&lt;h2 id=&quot;3-bayesian-logistic-regression-in-pymc&quot;&gt;3. Bayesian Logistic Regression in PyMC&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Standardize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Bayesian logistic regression
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logistic_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Priors
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Weakly informative
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Linear predictor
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Logistic transformation
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Deterministic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;invlogit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Likelihood
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Bernoulli&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Sample
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                              &lt;span class=&quot;n&quot;&gt;return_inferencedata&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Summary
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR SUMMARY&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize posteriors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot_posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ref_val&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;suptitle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior Distributions&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(True: α=1, β=0.8)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.05&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Trace plots
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;compact&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
             &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;suptitle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trace Plots (Check Convergence)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;experiment-the-logistic-regression-posterior-is-a-whole-family-of-curves&quot;&gt;Experiment: the logistic regression posterior is a whole family of curves&lt;/h3&gt;

&lt;p&gt;Add data points one at a time; the posterior is computed exactly on the (a, b) grid, from which we read the odds ratio exp(b) with its 95% interval.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;glm-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;logistic&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-interpretation-odds-ratios&quot;&gt;4. Interpretation: Odds Ratios&lt;/h2&gt;

&lt;h3 id=&quot;41-odds-vs-probability&quot;&gt;4.1. Odds vs Probability&lt;/h3&gt;

&lt;p&gt;To interpret logistic regression correctly, we need to distinguish &lt;strong&gt;probability&lt;/strong&gt; from &lt;strong&gt;odds&lt;/strong&gt;. Probability is written \(p=P(y=1)\), while odds is defined by \(\text{odds}=\frac{p}{1-p}\). When \(p=0.5\) the odds equal 1, meaning the two possibilities are balanced; when \(p=0.8\) the odds equal 4, meaning the event is four times as likely to occur as not; and when \(p=0.2\) the odds are only 0.25, meaning it is much more likely that the event does not occur.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter06/odds_probability_relationship.png&quot; alt=&quot;Odds vs Probability&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The figure shows the relationship between probability, odds, and &lt;strong&gt;log-odds&lt;/strong&gt; (the log of the odds). In the left panel, as the probability rises from 0.2 to 0.5 and then 0.8, the odds change nonlinearly from 0.25 to 1 and then 4. This reminds us that odds below 1 correspond to an event that is less likely to occur, while odds above 1 correspond to an event that is more likely to occur. In the right panel, when we take the log of the odds, the point \(p=0.5\) becomes 0, probabilities below 0.5 give negative log-odds, and probabilities above 0.5 give positive log-odds. It is on this log-odds scale that logistic regression returns to the familiar linear form: \(\text{logit}(p)=\alpha+\beta x\).&lt;/p&gt;

&lt;h3 id=&quot;42-interpreting-β&quot;&gt;4.2. Interpreting β&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;On log-odds scale&lt;/strong&gt;:
\(\log\left(\frac{p}{1-p}\right) = \alpha + \beta x\)&lt;/p&gt;

&lt;p&gt;Therefore, on the log-odds scale, each time \(x\) increases by 1 unit, the log-odds increases by \(\beta\) units.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;On odds scale&lt;/strong&gt;:
\(\text{odds} = e^{\alpha + \beta x}\)&lt;/p&gt;

&lt;p&gt;Going back to the odds scale, we see that each time \(x\) increases by 1 unit, the odds are multiplied by \(e^\beta\). This is the &lt;strong&gt;odds ratio&lt;/strong&gt;, and it is also the most practical way to interpret the coefficient of logistic regression.&lt;/p&gt;

&lt;h3 id=&quot;43-a-concrete-example-from-log-odds-to-predicted-probability&quot;&gt;4.3. A concrete example: from log-odds to predicted probability&lt;/h3&gt;

&lt;p&gt;Suppose the posterior mean of the model gives us the equation:&lt;/p&gt;

\[\log\left(\frac{p}{1-p}\right) = -0.4 + 1.1x\]

&lt;p&gt;where \(x\) is a standardized rating score. We can read the model step by step:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;If \(x=0\) then the log-odds equals \(-0.4\), so the odds are \(e^{-0.4}\approx 0.67\), and the probability is \(p=\frac{0.67}{1+0.67}\approx 0.40\).&lt;/li&gt;
  &lt;li&gt;If \(x=1\) then the log-odds equals \(0.7\), so the odds are \(e^{0.7}\approx 2.01\), and the probability rises to about \(0.67\).&lt;/li&gt;
  &lt;li&gt;If \(x=2\) then the log-odds equals \(1.8\), so the odds are \(e^{1.8}\approx 6.05\), and the probability rises to about \(0.86\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A very commonly misread point is that the coefficient \(\beta=1.1\) does not mean that the probability rises by a fixed 1.1 units or by 110 percentage points. The correct meaning is: each time \(x\) increases by 1 unit, the &lt;strong&gt;odds&lt;/strong&gt; are multiplied by \(e^{1.1}\approx 3\). Because logistic regression is linear on the log-odds scale but nonlinear on the probability scale, the same 1-unit increase in \(x\) can make the probability jump by different amounts depending on the starting point: from \(0.40\) to \(0.67\) is an increase of about 27 percentage points, while from \(0.67\) to \(0.86\) is an increase of about 19 percentage points.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Compute odds ratios
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ODDS RATIO INTERPRETATION&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β (log-odds scale): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Odds Ratio (e^β): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;95% CI: [&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
      &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;97.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Interpretation:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  1 SD increase in x → odds multiply by &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% increase in odds&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% decrease in odds&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Beta (log-odds scale)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;skyblue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β (log-odds scale)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;COEFFICIENT β&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Log-Odds Scale)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Odds ratio
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lightgreen&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;odds_ratio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Odds Ratio (e^β)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ODDS RATIO&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Multiplicative Effect)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-posterior-predictive-checks&quot;&gt;5. Posterior Predictive Checks&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Posterior predictive
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logistic_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ppc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample_posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Predicted probabilities
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_lower&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;p_upper&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;percentile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;97.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sort by x for plotting
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argsort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Posterior mean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fill_between&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_lower&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_upper&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sort_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                     &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;95% CI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;P(y=1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PREDICTED PROBABILITIES&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;with Uncertainty&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# PPC: Compare observed vs predicted
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ppc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_predictive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_pred_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Perfect prediction&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted P(y=1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;POSTERIOR PREDICTIVE CHECK&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observed vs Predicted&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Logistic regression is the natural answer when the outcome has only two states. The problem it solves is that linear regression cannot guarantee predictions lying in \([0,1]\), and its solution is to use the &lt;strong&gt;logit link&lt;/strong&gt; to connect an inner linear structure with a valid probability at the output. The core model has the form \(\log\left(\frac{p}{1-p}\right)=\alpha+\beta x\), and the coefficient should be read through the &lt;strong&gt;odds ratio&lt;/strong&gt; \(e^\beta\) rather than with the intuition of “how many units \(y\) increases” as in linear regression. In PyMC, this is implemented very directly with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.Bernoulli&lt;/code&gt; distribution combined with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.math.invlogit&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The most important point to keep is the GLM way of thinking: we still start with a linear part, but use an appropriate link function to handle outcomes that no longer follow the familiar Gaussian model.&lt;/p&gt;

&lt;p&gt;Next lesson: &lt;strong&gt;Poisson Regression&lt;/strong&gt; for count data.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-tracing-non-constant-probability-jumps-along-eta---15--08x&quot;&gt;Worked Numerical Example: Tracing Non-Constant Probability Jumps Along \(\eta = -1.5 + 0.8x\)&lt;/h3&gt;

&lt;p&gt;Suppose a Bayesian logistic regression has posterior mean \(\eta(x) = -1.5 + 0.8x\) (odds ratio per +1 unit of \(x\) is \(e^{0.8} \approx \mathbf{2.226\times}\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(x\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Log-Odds \(\eta = -1.5 + 0.8x\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Odds \(e^\eta\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Probability \(p = \frac{1}{1+e^{-\eta}}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Step Jump \(\Delta p\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-1.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.223\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(18.2\%\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;—&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-0.7\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.497\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(33.2\%\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+15.0\%\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+0.1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1.105\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(52.5\%\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(+19.3\%\)&lt;/strong&gt; (near \(\beta/4 = 20\%\)!)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+0.9\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2.460\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(71.1\%\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+18.6\%\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Look at the columns: every step multiplies &lt;strong&gt;Odds&lt;/strong&gt; by the exact same \(2.226\times\), yet &lt;strong&gt;\(\Delta p\)&lt;/strong&gt; peaks right around \(50\%\) (\(+19.3\%\), matching Gelman’s \(\beta/4 = 0.8/4 = 20\%\) ceiling!) and flattens near the extremes!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-bayesian-logistic-regression&quot;&gt;Explanation: Four Rules for Bayesian Logistic Regression&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check prior predictive probabilities on the \([0,1]\) scale:&lt;/strong&gt; Plot histograms of \(\sigma(\alpha + \beta x)\) drawn from your prior—if it looks like a U-shape piled at 0 and 1, tighten your log-odds priors!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Present results on the &lt;em&gt;probability&lt;/em&gt; scale for stakeholders:&lt;/strong&gt; Saying &lt;em&gt;“probability rises from 18% to 33% (95% CI: 26%–41%)”&lt;/em&gt; communicates far more clearly than &lt;em&gt;“log-odds increase by 0.8.”&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian priors cure Complete Separation automatically:&lt;/strong&gt; When a predictor perfectly separates 0s and 1s, frequentist MLE blows up to \(\beta = \pm\infty\); a \(\mathcal{N}(0, 2.5)\) prior keeps the posterior finite and well-behaved!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Even without an explicit \(x_1 x_2\) product, logistic predictors &lt;em&gt;interact&lt;/em&gt; on the probability scale&lt;/strong&gt; because of the curved sigmoid boundary!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Using Gelman’s divide-by-4 rule, if a standardized predictor has logistic slope \(\beta = 0.60\), what is the &lt;em&gt;maximum&lt;/em&gt; possible probability change \(\Delta p\) from a +1 SD increase in that predictor?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yIYKR4sgzI8&quot;&gt;StatQuest: Logistic Regression&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch logistic regression predict the probability of a binary outcome, exactly the 0/1 output variable of the lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ARfXDSkQf1Y&quot;&gt;Odds and Log(Odds), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch odds and log-odds, supporting the part on reading coefficients on the logit scale rather than the probability scale.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=F0N4b7K_iYQ&quot;&gt;Statistical Rethinking 2023 - 04 - Categories &amp;amp; Curves&lt;/a&gt; — Richard McElreath, English. Watch the logistic curve placed inside a Bayesian model, connecting the lesson’s formula with the generative story.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1&lt;/strong&gt;: Generate binary data. Fit logistic regression. Interpret odds ratio.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2&lt;/strong&gt;: Compare predictions of linear vs logistic regression. Visualize differences.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3&lt;/strong&gt;: Multiple predictors logistic regression. Interpret each coefficient.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4&lt;/strong&gt;: Real data - predict customer churn (0/1) from usage features.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5&lt;/strong&gt;: Posterior predictive checks. Compare accuracy, sensitivity, specificity.&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., &amp;amp; Hill, J. (2006).&lt;/strong&gt; &lt;em&gt;Data Analysis Using Regression and Multilevel/Hierarchical Models&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 5: Logistic regression&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 10: Big Entropy and the Generalized Linear Model&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter06/06_02_poisson_regression/&quot;&gt;6.2 Poisson Regression&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 5.4: Interaction Effects - When Effects Depend on Each Other</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter05/05_04_interaction_effects/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter05/05_04_interaction_effects</id>
   <content type="html">&lt;p&gt;Does rugged terrain hurt a country’s GDP? Across Europe and Asia, the answer is clearly &lt;strong&gt;yes&lt;/strong&gt;—mountains make trade expensive. Yet in Africa, economists found the exact &lt;em&gt;opposite&lt;/em&gt; slope: rugged terrain was &lt;strong&gt;positively&lt;/strong&gt; associated with higher GDP (because mountains historically shielded communities from the slave trade!). An additive regression &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;GDP ~ ruggedness + continent&lt;/code&gt; is mathematically blind to that sign flip—it forces one single slope everywhere! Only an &lt;strong&gt;interaction term&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ruggedness × continent&lt;/code&gt;) lets the effect of one predictor depend on the level of another.&lt;/p&gt;

&lt;p&gt;This lesson makes &lt;strong&gt;interaction effects&lt;/strong&gt; effortless to specify, compute, and visualize in Bayesian regression—showing why &lt;strong&gt;centering predictors&lt;/strong&gt; is essential before interpreting main effects.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-conditional-slopes-and-interaction-geometry&quot;&gt;Key ideas: Conditional Slopes and Interaction Geometry&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Additive vs. Interactive Linear Models:&lt;/strong&gt; Adding \(\beta_{12} X_1 X_2\) to \(\mu = \alpha + \beta_1 X_1 + \beta_2 X_2\) lets the slope of \(X_1\) vary linearly with \(X_2\): \(\frac{\partial \mu}{\partial X_1} = \beta_1 + \beta_{12} X_2\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Main Effects Become Conditional Effects:&lt;/strong&gt; Once \(\beta_{12} X_1 X_2\) is in the model, \(\beta_1\) is &lt;strong&gt;NO LONGER&lt;/strong&gt; the overall average effect of \(X_1\)—it is specifically the slope of \(X_1\) &lt;em&gt;when \(X_2 = 0\)&lt;/em&gt;! Centering \(X_2\) at its mean makes \(\beta_1\) immediately interpretable again.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Symmetry of Interactions:&lt;/strong&gt; Algebraically, \(\beta_{12} X_1 X_2\) equally means the slope of \(X_1\) depends on \(X_2\) &lt;em&gt;and&lt;/em&gt; the slope of \(X_2\) depends on \(X_1\)—the data alone doesn’t label one as “moderator.”&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Triptych / Counterfactual Plotting:&lt;/strong&gt; Never interpret interactions from a raw coefficient table alone—plot predicted curves of \(Y\) vs. \(X_1\) at three slices of \(X_2\) (low, medium, high) with posterior uncertainty bands!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to understand what an interaction effect is and why many real phenomena cannot be described by a simple additive model. You also need to know how to read an interaction in the style of “the effect of one variable changes with the context of another variable” instead of trying to force every coefficient into a fixed effect.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; A test-prep program may help decent students improve very quickly, but for students who lack fundamentals, the effect is smaller if no supplementary materials are available. The effect of study hours is then not fixed for everyone, but depends on entry level.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If the effect of one predictor changes with the level of another predictor, what will a simple additive model miss?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;1-the-real-world-is-rarely-just-adding-up&quot;&gt;1. The real world is rarely just “adding up”&lt;/h2&gt;

&lt;p&gt;In simple additive regression, we write:&lt;/p&gt;

\[y = \alpha + \beta_1 x_1 + \beta_2 x_2 + \epsilon\]

&lt;p&gt;This model says that the effect of \(x_1\) is the same at every level of \(x_2\), and the effect of \(x_2\) is also the same at every level of \(x_1\). But in practice, many phenomena do not work this way: the effectiveness of advertising depends on product quality, the effect of diet depends on activity level, the effect of study hours depends on background knowledge, and the effect of a drug depends on age or underlying conditions.&lt;/p&gt;

&lt;p&gt;In that case we need an interaction.&lt;/p&gt;

&lt;h2 id=&quot;2-what-is-an-interaction-effect&quot;&gt;2. What is an interaction effect?&lt;/h2&gt;

&lt;p&gt;An interaction occurs when the effect of one predictor on the outcome &lt;strong&gt;changes with the value of another predictor&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;A model with an interaction between \(x_1\) and \(x_2\) is usually written:&lt;/p&gt;

\[y = \alpha + \beta_1 x_1 + \beta_2 x_2 + \beta_3 (x_1 x_2) + \epsilon\]

&lt;p&gt;The new component \(\beta_3 (x_1 x_2)\) is the interaction term. If \(\beta_3\) is significantly different from 0, it suggests that the slope of \(x_1\) changes when \(x_2\) changes, or, looking the other way, the slope of \(x_2\) changes when \(x_1\) changes.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_no_interaction_parallel_lines.png&quot; alt=&quot;No interaction: the lines are nearly parallel&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_with_interaction_different_slopes.png&quot; alt=&quot;With interaction: the slope changes by group&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_interaction_model_comparison.png&quot; alt=&quot;Comparison of models with and without interaction&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-seeing-it-in-a-picture-is-easier-than-seeing-it-in-a-formula&quot;&gt;3. Seeing it in a picture is easier than seeing it in a formula&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_additive_model_demo.png&quot; alt=&quot;Additive model with nearly parallel lines&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_interactive_model_demo.png&quot; alt=&quot;Interactive model with different slopes&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Let us compare the two situations:&lt;/p&gt;

&lt;h3 id=&quot;additive-model&quot;&gt;Additive model&lt;/h3&gt;

&lt;p&gt;In the additive model, the lines are nearly parallel. This means that different groups may have different baseline levels, but the effect of \(x_1\) on \(y\) is nearly the same across groups.&lt;/p&gt;

&lt;h3 id=&quot;model-with-interaction&quot;&gt;Model with interaction&lt;/h3&gt;

&lt;p&gt;In the model with interaction, the lines have clearly different slopes. This means that for the same one-unit increase in \(x_1\), the outcome rises strongly or weakly depending on the level of \(x_2\).&lt;/p&gt;

&lt;p&gt;This is the core intuition of interaction.&lt;/p&gt;

&lt;h2 id=&quot;4-real-examples-to-see-interaction-more-clearly&quot;&gt;4. Real examples to see interaction more clearly&lt;/h2&gt;

&lt;h3 id=&quot;example-1-study-time-and-entry-level&quot;&gt;Example 1: study time and entry level&lt;/h3&gt;

&lt;p&gt;The outcome here is the final exam score, while the predictors are weekly study hours and entry level.&lt;/p&gt;

&lt;p&gt;If a student already has a good foundation, one more hour of study can raise the score quite noticeably. But for a student who lacks fundamentals, one more hour of study does not necessarily make a big difference if the basic knowledge gaps have not been filled.&lt;/p&gt;

&lt;p&gt;The effect of study hours then depends on entry level, so an interaction is reasonable.&lt;/p&gt;

&lt;h3 id=&quot;example-2-advertising-and-product-quality&quot;&gt;Example 2: advertising and product quality&lt;/h3&gt;

&lt;p&gt;Advertising can be much more effective when the product is already good. If the product is poor, increasing advertising may only help people learn about it faster without producing lasting conversion.&lt;/p&gt;

&lt;p&gt;In other words, the effect of the advertising budget depends on product quality.&lt;/p&gt;

&lt;h3 id=&quot;example-3-treatment-and-severity-of-illness&quot;&gt;Example 3: treatment and severity of illness&lt;/h3&gt;

&lt;p&gt;A treatment protocol may be very effective for mild cases but less effective for very severe cases, or the other way around. The effect of the treatment then changes with severity.&lt;/p&gt;

&lt;h3 id=&quot;experiment-from-an-additive-model-to-a-model-with-interaction&quot;&gt;Experiment: from an additive model to a model with interaction&lt;/h3&gt;

&lt;p&gt;One common line → two parallel lines → two lines with different slopes; watch how the RSS falls.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;confound-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;interaction&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;5-how-to-read-an-interaction-correctly&quot;&gt;5. How to read an interaction correctly&lt;/h2&gt;

&lt;p&gt;The most common mistake is to read \(\beta_1\) as a fixed common effect even though the model already has an interaction.&lt;/p&gt;

&lt;p&gt;When there is an interaction:&lt;/p&gt;

\[\frac{\partial y}{\partial x_1} = \beta_1 + \beta_3 x_2\]

&lt;p&gt;This says that the effect of \(x_1\) is &lt;strong&gt;no longer a single number&lt;/strong&gt;. It depends on \(x_2\).&lt;/p&gt;

&lt;h3 id=&quot;example-with-a-binary-variable&quot;&gt;Example with a binary variable&lt;/h3&gt;

&lt;p&gt;If \(x_2\) is a group variable, where \(x_2 = 0\) is the control group and \(x_2 = 1\) is the intervention group, then in the control group the effect of \(x_1\) is \(\beta_1\), while in the intervention group the effect of \(x_1\) is \(\beta_1 + \beta_3\).&lt;/p&gt;

&lt;p&gt;This means the interaction tells us the extent to which the intervention strengthens or weakens the effect of \(x_1\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_conditional_effects_by_group.png&quot; alt=&quot;Conditional effects of x₁ by each x₂ group&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_interaction_difference_distribution.png&quot; alt=&quot;Interaction as the difference between two conditional effects&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;51-a-numerical-example-for-reading-an-interaction-without-getting-lost&quot;&gt;5.1. A numerical example for reading an interaction without getting lost&lt;/h3&gt;

&lt;p&gt;Suppose we model the final exam score as follows:&lt;/p&gt;

\[\text{Score} = 4 + 0.2 \cdot \text{Study hours} + 1.0 \cdot \text{Good background} + 0.25 \cdot (\text{Study hours} \times \text{Good background}).\]

&lt;p&gt;Where:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Good background = 0&lt;/code&gt; is the group lacking fundamentals,&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Good background = 1&lt;/code&gt; is the group with solid background knowledge.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;for the group lacking fundamentals, one more study hour raises the score on average by about &lt;strong&gt;0.2 points&lt;/strong&gt;,&lt;/li&gt;
  &lt;li&gt;for the group with a good background, one more study hour raises the score on average by about&lt;br /&gt;
\(0.2 + 0.25 = 0.45\) points.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We can see this more clearly through a few concrete predictions:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;a student lacking fundamentals studying 2 hours:&lt;br /&gt;
\(4 + 0.2 \times 2 = 4.4\)&lt;/li&gt;
  &lt;li&gt;a student with a good background studying 2 hours:&lt;br /&gt;
\(4 + 0.2 \times 2 + 1 + 0.25 \times 2 = 5.9\)&lt;/li&gt;
  &lt;li&gt;a student lacking fundamentals studying 6 hours:&lt;br /&gt;
\(4 + 0.2 \times 6 = 5.2\)&lt;/li&gt;
  &lt;li&gt;a student with a good background studying 6 hours:&lt;br /&gt;
\(4 + 0.2 \times 6 + 1 + 0.25 \times 6 = 7.7\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The key point is that the difference between 2 hours and 6 hours of study is not the same across the two groups. That is exactly the interaction, written as numbers instead of just words.&lt;/p&gt;

&lt;h2 id=&quot;6-interactions-are-not-only-for-binary-variables&quot;&gt;6. Interactions are not only for binary variables&lt;/h2&gt;

&lt;p&gt;Interactions are also very common between two continuous variables.&lt;/p&gt;

&lt;p&gt;For example, temperature and humidity jointly affect electricity consumption, income and age jointly affect spending behavior, and study time and sleep quality jointly affect exam scores.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_interaction_continuous_lines.png&quot; alt=&quot;Effect lines when both variables are continuous&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_continuous_interaction_3d.png&quot; alt=&quot;3D view of the interaction between two continuous variables&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_continuous_interaction_contour.png&quot; alt=&quot;Contour plot of the interaction between two continuous variables&quot; /&gt;&lt;/p&gt;

&lt;p&gt;In the continuous x continuous case, images such as a contour plot or surface plot are usually far more intuitive than a table of coefficients. Interaction is therefore a topic where &lt;strong&gt;visualization is almost mandatory&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;7-when-should-we-think-of-an-interaction&quot;&gt;7. When should we think of an interaction?&lt;/h2&gt;

&lt;h3 id=&quot;71-when-domain-theory-suggests-it&quot;&gt;7.1. When domain theory suggests it&lt;/h3&gt;

&lt;p&gt;If domain knowledge says that the effect changes with context, an interaction should be considered. Familiar examples are drug and age, training and background level, or price and customer segment.&lt;/p&gt;

&lt;h3 id=&quot;72-when-plots-suggest-different-slopes&quot;&gt;7.2. When plots suggest different slopes&lt;/h3&gt;

&lt;p&gt;If you plot the data by group and see that the lines are not parallel, that is a very clear signal.&lt;/p&gt;

&lt;h3 id=&quot;73-when-a-simple-additive-model-leaves-structured-residuals&quot;&gt;7.3. When a simple additive model leaves structured residuals&lt;/h3&gt;

&lt;p&gt;Some residual patterns can show that the model is missing dependence between predictors.&lt;/p&gt;

&lt;h2 id=&quot;8-what-beginners-often-misunderstand&quot;&gt;8. What beginners often misunderstand&lt;/h2&gt;

&lt;h3 id=&quot;misconception-1-the-main-effect-no-longer-has-meaning&quot;&gt;Misconception 1: “The main effect no longer has meaning”&lt;/h3&gt;

&lt;p&gt;Not exactly. The main effect still has meaning, but its meaning depends on how you code and center the variables. If a continuous variable is centered around its mean, then the main effect is usually the effect of the predictor at the average level of the other variable.&lt;/p&gt;

&lt;p&gt;This is why standardizing or centering predictors is often very useful before interpreting an interaction.&lt;/p&gt;

&lt;h3 id=&quot;misconception-2-if-there-is-an-interaction-we-must-drop-the-main-effects&quot;&gt;Misconception 2: “If there is an interaction, we must drop the main effects”&lt;/h3&gt;

&lt;p&gt;Usually we should not do this. An interaction usually goes together with the main effects so that the model keeps its basic interpretive meaning.&lt;/p&gt;

&lt;h3 id=&quot;misconception-3-looking-at-the-p-value-or-interval-of-the-interaction-is-enough&quot;&gt;Misconception 3: “Looking at the p-value or interval of the interaction is enough”&lt;/h3&gt;

&lt;p&gt;Not enough. With interactions, plots and conditional effects are as important as, or more important than, the summary number.&lt;/p&gt;

&lt;h2 id=&quot;9-a-familiar-example-exercise-and-diet&quot;&gt;9. A familiar example: exercise and diet&lt;/h2&gt;

&lt;p&gt;Suppose the outcome is the kilograms lost in 8 weeks, while the predictors are the number of workouts per week and the level of diet adherence.&lt;/p&gt;

&lt;p&gt;If the diet is very poor, adding 1 more workout may improve things only slightly. But if the diet is kept good, that same extra workout may make a larger difference.&lt;/p&gt;

&lt;p&gt;This is the kind of situation where the additive model:&lt;/p&gt;

\[\text{Weight loss} = \alpha + \beta_1 \cdot \text{Exercise} + \beta_2 \cdot \text{Diet} + \epsilon\]

&lt;p&gt;may miss an important part of the story.&lt;/p&gt;

&lt;p&gt;The model with interaction would be more reasonable:&lt;/p&gt;

\[\text{Weight loss} = \alpha + \beta_1 \cdot \text{Exercise} + \beta_2 \cdot \text{Diet} + \beta_3 \cdot (\text{Exercise} \times \text{Diet}) + \epsilon\]

&lt;p&gt;If \(\beta_3 &amp;gt; 0\), it means that for the same 1 additional workout, a person who adheres well to the diet benefits more. If \(\beta_3 &amp;lt; 0\), we would read it the other way: the effect of increasing exercise weakens when the diet is already at a very good level or when the two factors partly substitute for each other. The sign of the interaction therefore helps us understand whether the two factors are &lt;strong&gt;amplifying&lt;/strong&gt; or &lt;strong&gt;offsetting&lt;/strong&gt; each other.&lt;/p&gt;

&lt;h2 id=&quot;10-how-to-report-an-interaction-to-a-non-specialist&quot;&gt;10. How to report an interaction to a non-specialist&lt;/h2&gt;

&lt;p&gt;Do not start with:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;the interaction coefficient is 0.63.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Start with the language of the situation:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The effect of study hours is not the same for every student. In the group with a good background, additional study time goes with a clearly larger increase in score than in the group with a weak background.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Only then give the number if needed.&lt;/p&gt;

&lt;p&gt;This kind of interpretation helps the reader understand the nature of the phenomenon first, and then look at the quantitative part.&lt;/p&gt;

&lt;h2 id=&quot;11-chapter-5-closes-here&quot;&gt;11. Chapter 5 closes here&lt;/h2&gt;

&lt;p&gt;By the end of this chapter, you have a very important toolkit for reading regression correctly, including multiple predictors at once, confounding and causal structure, multicollinearity, and interaction effects. This is the moment when regression stops being “drawing a straight line” and becomes a way of thinking about the mechanism that generates data.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; An interaction occurs when the effect of one predictor changes with the level of another predictor, so the effect cannot always be interpreted as a fixed number for all cases; when a model has an interaction, the best way to read it is through conditional effects and to use plots instead of looking only at the coefficient table; and interactions are very common in real life because the effectiveness of an intervention, behavior, or conditions are rarely the same in every context.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-computing-a-sign-flipping-conditional-slope-by-hand&quot;&gt;Worked Numerical Example: Computing a Sign-Flipping Conditional Slope by Hand&lt;/h3&gt;

&lt;p&gt;Suppose crop yield \(\mu\) depends on &lt;strong&gt;Water (\(x_1\))&lt;/strong&gt;, &lt;strong&gt;Shade (\(x_2 \in \{0=\text{Sun},\; 1=\text{Shade}\}\))&lt;/strong&gt;:&lt;/p&gt;

\[\mu = 10 + 3x_1 + 2x_2 - 5(x_1 x_2).\]

&lt;p&gt;Compute the exact effect of adding +1 unit of Water (\(\frac{\partial\mu}{\partial x_1} = 3 - 5x_2\)) in both conditions:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;In Full Sun (\(x_2 = 0\)):&lt;/strong&gt; \(\mu = 10 + 3x_1 \implies\) slope is &lt;strong&gt;\(+3\)&lt;/strong&gt; (more water strongly boosts yield!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;In Full Shade (\(x_2 = 1\)):&lt;/strong&gt; \(\mu = (10 + 2) + (3 - 5)x_1 = 12 - 2x_1 \implies\) slope flips to &lt;strong&gt;\(-2\)&lt;/strong&gt; (extra water in shade rots the roots!).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Notice that looking only at the main-effect coefficient \(\beta_1 = +3\) tells you &lt;em&gt;only&lt;/em&gt; about Full Sun and completely misses the negative slope in Shade!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-modeling-interactions-safely&quot;&gt;Explanation: Four Rules for Modeling Interactions Safely&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always include both lower-order main effects when adding \(X_1 X_2\):&lt;/strong&gt; Dropping \(X_1\) or \(X_2\) forces all interaction lines to cross artificially at the origin &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(0, 0)&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Center continuous predictors before multiplying them:&lt;/strong&gt; Without centering, \(X_1\) and \(X_1 X_2\) become strongly collinear, inflating posterior uncertainty and slowing MCMC.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use regularizing priors on interaction terms:&lt;/strong&gt; With \(p = 10\) predictors, there are \(\binom{10}{2} = 45\) possible pairwise interactions—without shrinkage priors (e.g., \(\beta_{12} \sim \mathcal{N}(0, 0.5)\)), interactions overfit noise rapidly!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always compute posterior uncertainty on the &lt;em&gt;combined&lt;/em&gt; conditional slope:&lt;/strong&gt; Draw \(\beta_1^{(s)} + \beta_{12}^{(s)} x_2\) across posterior samples rather than testing \(\beta_1\) and \(\beta_{12}\) separately.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the crop-yield equation \(\mu = 10 + 3x_1 + 2x_2 - 5x_1 x_2\), what is the predicted yield at \(x_1 = 2, x_2 = 1\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=3CCkeFShB3U&quot;&gt;GLM Part 6: Interaction effects: How to interpret and identify them&lt;/a&gt; — Simplistics (QuantPsych), English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the effect of one variable change with the level of the other, exactly the definition of interaction the lesson contrasts with the additive model.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=J8IHdu-oM64&quot;&gt;How to Interpret a Regression with an Interaction Term&lt;/a&gt; — Econometrics, Causality, and Coding with Dr. HK, English. Watch how to read the main coefficients and the interaction coefficient in a regression table.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=F0N4b7K_iYQ&quot;&gt;Statistical Rethinking 2023 - 04 - Categories &amp;amp; Curves&lt;/a&gt; — Richard McElreath, English. Watch curves and group differences written as a model, supporting the part where the interaction is more than just an added term.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Give an example from everyday life where the effect of one variable clearly depends on another variable.&lt;/li&gt;
  &lt;li&gt;Why are non-parallel lines on a group plot a sign of a possible interaction?&lt;/li&gt;
  &lt;li&gt;In the example of study hours and entry level, what does the interaction help describe that the additive model misses?&lt;/li&gt;
  &lt;li&gt;If a continuous variable is not centered, what can be difficult about interpreting the main effects in a model with an interaction?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., &amp;amp; Hill, J. (2006).&lt;/strong&gt; &lt;em&gt;Data Analysis Using Regression and Multilevel/Hierarchical Models&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next chapter: &lt;a href=&quot;/contents/en/chapter06/&quot;&gt;Chapter 6: Bayesian Generalized Linear Models (GLMs)&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 5.3: Multicollinearity - When Predictors Are Correlated</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter05/05_03_multicollinearity/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter05/05_03_multicollinearity</id>
   <content type="html">&lt;p&gt;Try predicting a person’s height from &lt;strong&gt;both&lt;/strong&gt; their left leg length and their right leg length in the same regression. Individually, each leg is an extraordinary predictor of height (slope \(\approx 2.0\)). Put &lt;em&gt;both&lt;/em&gt; legs into the same model, and suddenly the posterior intervals for both slopes explode to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[-3.0, +7.0]&lt;/code&gt;—making it look as if &lt;em&gt;neither&lt;/em&gt; leg predicts height! Nothing is broken in Bayes’ theorem; the model is honestly telling you: &lt;strong&gt;because left and right legs are 99% correlated, infinitely many pairs \((\beta_L, \beta_R)\) with \(\beta_L + \beta_R \approx 2.0\) explain the data equally well!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This lesson demystifies &lt;strong&gt;multicollinearity&lt;/strong&gt; from a Bayesian perspective: why predictions stay accurate while individual slopes become non-identifiable, how posterior pair plots reveal the exact diagonal ridge, and how weakly informative priors stabilize inference.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-non-identifiability-ridges-under-multicollinearity&quot;&gt;Key ideas: Non-Identifiability Ridges Under Multicollinearity&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;The Posterior Ridge Geometry:&lt;/strong&gt; When \(X_1 \approx X_2\), the linear predictor \(\beta_1 X_1 + \beta_2 X_2 \approx (\beta_1 + \beta_2)X_1\) depends only on the &lt;strong&gt;sum&lt;/strong&gt; \(\beta_1 + \beta_2\). The joint posterior stretches into a long, narrow diagonal ridge with strong negative correlation \(\rho(\beta_1, \beta_2) \approx -0.99\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Individual Slopes Fail, Predictions Succeed:&lt;/strong&gt; Even when marginal CIs for \(\beta_1\) and \(\beta_2\) look wildly uncertain, their sum \(\beta_1 + \beta_2\)—and therefore out-of-sample predictions \(\hat{y}\)—remain razor-sharp!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Weakly Informative Priors Break Exact Flatness:&lt;/strong&gt; While OLS explodes to \(\pm\infty\) under perfect collinearity, a Bayesian prior \(\beta_j \sim \mathcal{N}(0, 1)\) smoothly anchors the ridge around balanced weights \((\beta_1 \approx \beta_2 \approx 1.0)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Detection (VIF &amp;amp; Posterior Pair Plots):&lt;/strong&gt; Variance Inflation Factor \(\mathrm{VIF}_j = \frac{1}{1 - R_j^2}\) and inspecting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;az.plot_pair&lt;/code&gt; immediately expose collinear parameter pairs.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to understand what multicollinearity is, why it makes interpreting coefficients difficult, and when it is truly worrying. You also need to clearly distinguish two different goals of regression: &lt;strong&gt;prediction&lt;/strong&gt; and &lt;strong&gt;interpretation&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; You predict house prices using floor area and the number of bedrooms. These two variables usually go together: larger houses usually also have more rooms. The model can then predict price quite well, but becomes awkward when it must answer exactly “holding everything else fixed, how much does one more bedroom raise the price?”.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If two predictors measure nearly the same thing, what difficulty will the model have in separating the effect of each variable?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;1-what-is-multicollinearity&quot;&gt;1. What is multicollinearity?&lt;/h2&gt;

&lt;p&gt;Multicollinearity occurs when two or more predictors in the same model are highly correlated with each other. Put more simply, they usually move together, carry substantially overlapping information, and so the model has difficulty knowing which variable to “give credit” to. Very typical examples are height in centimeters and height in inches, house area and number of bedrooms in an apartment complex with fairly similar designs, or study hours and the number of completed assignments in a highly disciplined class.&lt;/p&gt;

&lt;p&gt;The problem is not wrong data. The problem is that the predictors are too similar in terms of information.&lt;/p&gt;

&lt;p&gt;The three views below summarize the most basic intuition of multicollinearity.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_multicollinearity_predictor_correlation.png&quot; alt=&quot;Very high correlation between two predictors&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_multicollinearity_both_predict_y.png&quot; alt=&quot;Both predictors are strongly related to the outcome&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_multicollinearity_problem_summary.png&quot; alt=&quot;Summary of why multicollinearity makes interpretation hard&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The figures above show a very typical situation: both predictors are related to the outcome, but they are also so similar that the model has difficulty separating who contributes how much.&lt;/p&gt;

&lt;h2 id=&quot;2-why-does-multicollinearity-make-coefficients-hard-to-read&quot;&gt;2. Why does multicollinearity make coefficients hard to read?&lt;/h2&gt;

&lt;p&gt;Let us return to the principle of multiple regression:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;each coefficient is understood as the effect of one variable when the other variables are held fixed.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The problem is that if two variables usually rise and fall together, the condition “hold the other variable fixed” becomes rather foreign to the real data.&lt;/p&gt;

&lt;h3 id=&quot;example-floor-area-and-number-of-bedrooms&quot;&gt;Example: floor area and number of bedrooms&lt;/h3&gt;

&lt;p&gt;In practice, a house with a large area usually has more bedrooms, while a small house usually has fewer bedrooms.&lt;/p&gt;

&lt;p&gt;If we ask:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;between two houses with the same area but differing by 1 bedroom, how much does the price differ?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;that is a reasonable question. But if your data rarely contains such pairs of houses, the model will not have much information to answer with confidence.&lt;/p&gt;

&lt;p&gt;The result is usually wider credible intervals for the coefficients, coefficient signs that can unexpectedly flip, and coefficients that become very sensitive to adding or removing just a few observations.&lt;/p&gt;

&lt;p&gt;The comparison below shows the difference between a context with weakly correlated predictors and one with nearly duplicated predictors.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_low_predictor_correlation.png&quot; alt=&quot;Case where predictors are only slightly correlated&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_high_predictor_correlation.png&quot; alt=&quot;Case where predictors are very highly correlated&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_low_correlation_posterior.png&quot; alt=&quot;Posterior when predictors are weakly correlated&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_high_correlation_posterior.png&quot; alt=&quot;Posterior when predictors are highly correlated&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;21-a-numerical-example-the-overall-model-is-fine-but-the-individual-coefficients-are-awkward&quot;&gt;2.1. A numerical example: the overall model is fine but the individual coefficients are awkward&lt;/h3&gt;

&lt;p&gt;Suppose we predict house prices using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;area&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number of bedrooms&lt;/code&gt;, and these two variables are very highly correlated, say about \(0.92\).&lt;/p&gt;

&lt;p&gt;If we fit each simple model separately, we may see:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the model with only &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;area&lt;/code&gt;: 1 more m² goes with an increase of about &lt;strong&gt;35 million VND&lt;/strong&gt;,&lt;/li&gt;
  &lt;li&gt;the model with only &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number of bedrooms&lt;/code&gt;: 1 more bedroom goes with an increase of about &lt;strong&gt;700 million VND&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both results sound reasonable because each variable represents nearly the same package of information about the “size of the house”.&lt;/p&gt;

&lt;p&gt;But when both are put into the same model, the result may turn into:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;area&lt;/code&gt;: about &lt;strong&gt;32 million VND/m²&lt;/strong&gt; with a fairly stable interval,&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number of bedrooms&lt;/code&gt;: about &lt;strong&gt;40 million VND/bedroom&lt;/strong&gt; but with a very wide interval, for example from &lt;strong&gt;-180&lt;/strong&gt; to &lt;strong&gt;260 million&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here the model does not necessarily predict badly. What it is saying is: “I still know that bigger houses are usually more expensive, but this data is not enough to clearly separate the individual value of the number of bedrooms once the area has been held fixed”.&lt;/p&gt;

&lt;p&gt;This is a very typical multicollinearity situation: the overall information about the group of variables is still useful, but splitting the credit among individual variables becomes unstable.&lt;/p&gt;

&lt;h2 id=&quot;3-signs-to-recognize-it-in-practice&quot;&gt;3. Signs to recognize it in practice&lt;/h2&gt;

&lt;p&gt;When working with data, you can suspect multicollinearity if you see predictors that are highly correlated on a scatter plot or in the correlation matrix, if the coefficient of each variable “jumps around” when a new predictor is added, if the intervals of the coefficients are wide even though the overall model still fits fairly well, or if the sign of a coefficient contradicts domain intuition. For instance, in a revenue prediction model, advertising budgets for Facebook and Instagram can be very similar because a company usually raises and lowers them at the same time; the consequence is that the model has difficulty saying which channel is more effective, even though the total advertising budget still predicts revenue well overall.&lt;/p&gt;

&lt;h2 id=&quot;4-is-multicollinearity-always-bad&quot;&gt;4. Is multicollinearity always bad?&lt;/h2&gt;

&lt;p&gt;No.&lt;/p&gt;

&lt;p&gt;This is a very important point.&lt;/p&gt;

&lt;h3 id=&quot;41-if-the-goal-is-prediction&quot;&gt;4.1. If the goal is prediction&lt;/h3&gt;

&lt;p&gt;If the main goal is prediction, multicollinearity is often not too frightening, because the model can still predict the outcome well, the total information from that group of predictors is still useful, and what you mainly need is accurate forecasting rather than explaining each coefficient individually. For example, a credit risk model can use many fairly similar financial indicators and still give acceptable forecasts.&lt;/p&gt;

&lt;h3 id=&quot;42-if-the-goal-is-interpretation&quot;&gt;4.2. If the goal is interpretation&lt;/h3&gt;

&lt;p&gt;If the goal is interpretation, multicollinearity becomes a much bigger problem, because now you really care about which variable is important, how large the individual effect of each variable is, and whether the sign and size of the coefficients are stable. When the predictors overlap too much, all of that interpretive power weakens markedly.&lt;/p&gt;

&lt;h2 id=&quot;5-an-everyday-example-salary-and-education&quot;&gt;5. An everyday example: salary and education&lt;/h2&gt;

&lt;p&gt;Suppose you want to explain salary using years of schooling, highest degree, and a tested professional skill.&lt;/p&gt;

&lt;p&gt;These three variables are quite strongly related to each other.&lt;/p&gt;

&lt;p&gt;What can happen is that the overall model still predicts salary fairly well, but it is very hard to say exactly how much the degree alone contributes if skills and years of schooling also rise along with it.&lt;/p&gt;

&lt;p&gt;In that case, the more honest answer would be:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The set of variables on academic and professional background is strongly related to salary, but the current data is not enough to clearly separate the individual contribution of each component.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is a more mature kind of interpretation than trying to force each coefficient into a “certain truth”.&lt;/p&gt;

&lt;h3 id=&quot;51-a-very-common-bayesian-sign-posteriors-stretched-into-a-diagonal-band&quot;&gt;5.1. A very common Bayesian sign: posteriors stretched into a diagonal band&lt;/h3&gt;

&lt;p&gt;If you plot the joint posterior of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;years of schooling&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;professional skill score&lt;/code&gt;, you may see that the samples do not form a neat round cloud but a diagonal band sloping downward.&lt;/p&gt;

&lt;p&gt;This usually means:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;when the posterior assigns a larger effect to education, it will assign a smaller effect to skill,&lt;/li&gt;
  &lt;li&gt;and conversely, many different combinations still explain the data about equally well.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So what should be read first is not only the posterior mean of each coefficient, but also the &lt;strong&gt;dependence structure between the coefficients&lt;/strong&gt; in the joint posterior.&lt;/p&gt;

&lt;h2 id=&quot;6-why-are-the-posteriors-of-the-coefficients-often-tightly-stuck-together&quot;&gt;6. Why are the posteriors of the coefficients often tightly stuck together?&lt;/h2&gt;

&lt;p&gt;In a Bayesian setting, multicollinearity often shows up in the joint posterior of the coefficients: when one coefficient increases, the other tends to decrease, because many different combinations can still produce nearly the same predictions.&lt;/p&gt;

&lt;p&gt;We can imagine the model saying:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;I know the total contribution of this group of variables is quite important, but I am not really sure how to split the credit among the individual variables.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is why we often see the posterior of the coefficients stretched along a diagonal direction instead of being round and neat.&lt;/p&gt;

&lt;h3 id=&quot;experiment-raise-the-correlation-and-the-posterior-becomes-a-diagonal-band&quot;&gt;Experiment: raise the correlation and the posterior becomes a diagonal band&lt;/h3&gt;

&lt;p&gt;Raise ρ between the two predictors: sd(b₁) grows with √VIF, b₁ and b₂ are negatively correlated, but the sum b₁ + b₂ stays stable.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;collinear-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;7-how-should-we-handle-multicollinearity&quot;&gt;7. How should we handle multicollinearity?&lt;/h2&gt;

&lt;p&gt;There is no single answer for every case. We choose the way to handle it according to the goal of the analysis.&lt;/p&gt;

&lt;h3 id=&quot;71-keep-one-representative-variable&quot;&gt;7.1. Keep one representative variable&lt;/h3&gt;

&lt;p&gt;If two variables measure nearly the same thing, sometimes the simplest approach is to keep only one. For example, we can keep area and drop the number of bedrooms if in the current dataset they nearly repeat the same information.&lt;/p&gt;

&lt;h3 id=&quot;72-combine-into-a-composite-index&quot;&gt;7.2. Combine into a composite index&lt;/h3&gt;

&lt;p&gt;If several variables describe the same concept, we can create a composite score. For example, many variables on household economic conditions can be combined into a socioeconomic index.&lt;/p&gt;

&lt;h3 id=&quot;73-collect-more-diverse-data&quot;&gt;7.3. Collect more diverse data&lt;/h3&gt;

&lt;p&gt;This is a very effective approach but often forgotten.&lt;/p&gt;

&lt;p&gt;If the data comes from only a too-homogeneous context, predictors will easily go together. Broadening the range of the data can help separate the signals better.&lt;/p&gt;

&lt;h3 id=&quot;74-use-a-regularizing-prior&quot;&gt;7.4. Use a regularizing prior&lt;/h3&gt;

&lt;p&gt;In Bayesian statistics, a reasonable prior can help stabilize estimation when the data is not strong enough to separate each effect. The later chapters will return to regularization in more detail.&lt;/p&gt;

&lt;h3 id=&quot;75-accept-the-limits-of-interpretation&quot;&gt;7.5. Accept the limits of interpretation&lt;/h3&gt;

&lt;p&gt;Sometimes the most correct thing is to admit:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;this data is better suited for prediction than for interpreting each coefficient individually.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That is not a failure. It is an honest scientific conclusion.&lt;/p&gt;

&lt;h2 id=&quot;8-a-very-practical-checklist&quot;&gt;8. A very practical checklist&lt;/h2&gt;

&lt;p&gt;When you suspect multicollinearity, you can ask yourself a series of very practical questions: is my goal prediction or interpretation, which predictors are overlapping in information, if I drop one variable does predictive ability fall much, if I keep both can I still interpret the coefficients with confidence, and should I combine them into a broader concept.&lt;/p&gt;

&lt;h2 id=&quot;9-what-learners-often-misunderstand&quot;&gt;9. What learners often misunderstand&lt;/h2&gt;

&lt;h3 id=&quot;misconception-1-if-a-coefficient-has-the-wrong-sign-the-model-must-be-wrong&quot;&gt;Misconception 1: “If a coefficient has the wrong sign, the model must be wrong”&lt;/h3&gt;

&lt;p&gt;Not necessarily. The model may be trying to split credit between predictors that are too similar.&lt;/p&gt;

&lt;h3 id=&quot;misconception-2-correlation-between-predictors-is-forbidden&quot;&gt;Misconception 2: “Correlation between predictors is forbidden”&lt;/h3&gt;

&lt;p&gt;Not true. Real-world data very often has correlated predictors. What matters is understanding the consequences.&lt;/p&gt;

&lt;h3 id=&quot;misconception-3-adding-variables-is-always-good&quot;&gt;Misconception 3: “Adding variables is always good”&lt;/h3&gt;

&lt;p&gt;If a new variable only repeats old information, you can make the model harder to interpret without gaining much value.&lt;/p&gt;

&lt;h2 id=&quot;10-connecting-to-interaction-effects&quot;&gt;10. Connecting to interaction effects&lt;/h2&gt;

&lt;p&gt;Multicollinearity asks:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;are the predictors too similar?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Interaction effects in the next lesson ask:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;does the effect of one predictor change with another predictor?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;One is a problem of &lt;strong&gt;overlapping information&lt;/strong&gt;, the other a problem of &lt;strong&gt;mutual dependence of effects&lt;/strong&gt;. Being able to tell these two apart will help you read multiple regression much more accurately.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; Multicollinearity occurs when predictors carry information that is too similar, making it hard for the model to separate the effect of each variable; this is an especially serious problem when the goal is interpreting coefficients, but may be less serious if the goal is only prediction; and the way to handle it always depends on the goal, from dropping variables, combining variables, using a more stabilizing prior, collecting more diverse data, to accepting the limits of interpretation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-left-leg--right-leg-posterior-ridge&quot;&gt;Worked Numerical Example: Left Leg + Right Leg Posterior Ridge&lt;/h3&gt;

&lt;p&gt;Suppose true height is \(H_i = 2.0 \cdot \text{Leg}_i + \varepsilon_i\) and left/right leg lengths correlate at \(r = 0.99\) (\(\mathrm{VIF} = \frac{1}{1 - 0.99^2} \approx \mathbf{50.3}\)!). Compare the posterior summaries of a two-leg Bayesian regression:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Quantity&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Posterior Mean&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Posterior SD&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;95% Credible Interval&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Interpretation&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(\beta_{\text{left}}\) alone&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+1.10\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2.45\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([-3.70,\; +5.90]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Looks “uncertain” marginally!&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(\beta_{\text{right}}\) alone&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+0.90\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2.45\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([-3.90,\; +5.70]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Looks “uncertain” marginally!&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Sum \(\beta_{\text{left}} + \beta_{\text{right}}\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(+2.00\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.08\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\([+1.84,\; +2.16]\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Pinned down with 30× higher precision!&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;explanation-four-rules-for-handling-multicollinearity-in-bayes&quot;&gt;Explanation: Four Rules for Handling Multicollinearity in Bayes&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check posterior correlation before declaring a predictor “unimportant”:&lt;/strong&gt; A wide marginal CI straddling zero may simply mean another predictor in the model is measuring the exact same underlying construct!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Distinguish prediction goals from causal goals:&lt;/strong&gt; For pure prediction, collinearity rarely hurts (especially with regularizing priors); for causal estimation, consult your DAG before dropping or combining predictors.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Combine redundant measurements cleanly:&lt;/strong&gt; Averaging &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(left_leg + right_leg)/2&lt;/code&gt; or using a latent factor model eliminates redundancy and cuts measurement noise in half.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Watch HMC sampling speed:&lt;/strong&gt; Extreme posterior ridges force tiny HMC step sizes; standardizing or dropping exact duplicates speeds up NUTS by 5–10×.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If predictor \(X_1\) has \(R_1^2 = 0.95\) when regressed on the other predictors in your model, what is its Variance Inflation Factor \(\mathrm{VIF}_1 = \frac{1}{1 - R_1^2}\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=G1WX5GiFSWQ&quot;&gt;Multicollinearity (in Regression Analysis)&lt;/a&gt; — numiqo, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch multicollinearity make it hard to separate each variable’s share of the signal, exactly the phenomenon the lesson defines.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=O4jDva9B3fw&quot;&gt;Multicollinearity&lt;/a&gt; — Ben Lambert, English. Watch multicollinearity in regression interpretation, supporting the part that distinguishes prediction from reading coefficients.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=0SBIXgPVex8&quot;&gt;Variance Inflation Factors: testing for multicollinearity&lt;/a&gt; — Ben Lambert, English. Watch variance inflation factors, used where the lesson needs a diagnostic sign that predictors go together.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why do floor area and number of bedrooms easily create multicollinearity?&lt;/li&gt;
  &lt;li&gt;Give an example from your own work where prediction is still fine even though the coefficients are hard to interpret.&lt;/li&gt;
  &lt;li&gt;If two variables nearly duplicate information, would you consider keeping one variable or combining the two? Why?&lt;/li&gt;
  &lt;li&gt;In a salary study, why can education and professional skill make it difficult to interpret each coefficient individually?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Hill, J., &amp;amp; Vehtari, A. (2020).&lt;/strong&gt; &lt;em&gt;Regression and Other Stories&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter05/05_04_interaction_effects/&quot;&gt;5.4 Interaction Effects&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 5.2: Confounding and DAGs - Causal Inference Basics</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter05/05_02_confounding_dags/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter05/05_02_confounding_dags</id>
   <content type="html">&lt;p&gt;Here is one of the most famous traps in data science: a hospital records data on mild and severe patients and discovers that &lt;strong&gt;patients who receive Treatment T have &lt;em&gt;lower&lt;/em&gt; survival rates than untreated patients&lt;/strong&gt;—yet when you stratify by disease severity, Treatment T &lt;em&gt;improves&lt;/em&gt; survival in both mild and severe patients! Worse still, in a different causal structure (a &lt;strong&gt;collider&lt;/strong&gt;), throwing &lt;em&gt;every&lt;/em&gt; available column into your regression can manufacture a completely fake causal effect even when the true effect is zero!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Directed Acyclic Graphs (DAGs)&lt;/strong&gt;—pioneered by Judea Pearl and popularized in Bayesian data analysis by Richard McElreath—give you a crystal-clear graphical grammar for causal inference: &lt;strong&gt;forks&lt;/strong&gt; (confounders you &lt;em&gt;must&lt;/em&gt; control for), &lt;strong&gt;pipes&lt;/strong&gt; (mediators), and &lt;strong&gt;colliders&lt;/strong&gt; (traps you must &lt;em&gt;never&lt;/em&gt; condition on!).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-four-elemental-causal-structures-in-dags&quot;&gt;Key ideas: The Four Elemental Causal Structures in DAGs&lt;/h2&gt;

&lt;p&gt;Every complex causal web reduces to combinations of four 3-node junctions:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;The Fork (Confounder: \(X \leftarrow Z \rightarrow Y\)):&lt;/strong&gt; Common cause \(Z\) creates a non-causal “backdoor” path between \(X\) and \(Y\). &lt;strong&gt;Rule:&lt;/strong&gt; Conditioning on \(Z\) &lt;em&gt;closes&lt;/em&gt; the backdoor and removes confounding bias!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Pipe (Mediator: \(X \rightarrow Z \rightarrow Y\)):&lt;/strong&gt; \(X\) causes \(Y\) &lt;em&gt;through&lt;/em&gt; \(Z\). &lt;strong&gt;Rule:&lt;/strong&gt; Conditioning on \(Z\) blocks the causal path—do &lt;em&gt;not&lt;/em&gt; control for a post-treatment mediator if you want the &lt;strong&gt;total&lt;/strong&gt; causal effect of \(X\) on \(Y\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Collider (Common Effect: \(X \rightarrow Z \leftarrow Y\)):&lt;/strong&gt; \(X\) and \(Y\) are initially independent, yet both cause \(Z\). &lt;strong&gt;Rule:&lt;/strong&gt; Conditioning on \(Z\) &lt;em&gt;opens&lt;/em&gt; a spurious path (&lt;strong&gt;collider / Berkson’s bias&lt;/strong&gt;) — &lt;strong&gt;NEVER&lt;/strong&gt; control for a collider!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Backdoor Criterion:&lt;/strong&gt; To identify the causal effect of \(X\) on \(Y\) from observational data, choose an adjustment set \(S\) that blocks every backdoor path into \(X\) while containing no descendants of \(X\).&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to understand what confounding is and why it makes us misread data. You also need to know that a DAG is a tool for thinking about causal relationships, from which you decide when to adjust for a variable and when not to. This is the foundation of causal inference.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; A hospital sees that patients given stronger treatment have a lower recovery rate. The conclusion “stronger treatment makes everything worse” sounds very plausible, but it can be completely wrong if severe cases were already given stronger treatment to begin with. The severity of the illness at admission may be the confounding variable.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If a variable affects both the treatment and the outcome, what can happen if we ignore it?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;1-how-does-correlation-differ-from-causation&quot;&gt;1. How does correlation differ from causation?&lt;/h2&gt;

&lt;p&gt;In real data, two variables going together do not necessarily have a direct causal relationship.&lt;/p&gt;

&lt;p&gt;A very famous example is that ice cream sales rise in summer, and the number of drowning incidents also rises in summer. This does not mean ice cream causes drowning; both rise because of &lt;strong&gt;hot weather&lt;/strong&gt;. The problem here is that we see a correlation but do not see the structure that produces it.&lt;/p&gt;

&lt;p&gt;Confounding is one of the most common reasons we mistake correlation for causation.&lt;/p&gt;

&lt;h2 id=&quot;2-what-is-a-confounder&quot;&gt;2. What is a confounder?&lt;/h2&gt;

&lt;p&gt;A variable is called a &lt;strong&gt;confounder&lt;/strong&gt; if it affects the predictor or treatment \(X\), and also affects the outcome \(Y\), but does not lie on the causal path from \(X\) to \(Y\).&lt;/p&gt;

&lt;h3 id=&quot;example-1-coffee-and-heart-disease&quot;&gt;Example 1: coffee and heart disease&lt;/h3&gt;

&lt;p&gt;Suppose we observe that people who drink a lot of coffee have a higher risk of heart disease. We might hastily conclude that coffee is the culprit. But if more stressed people both drink more coffee and have a higher cardiovascular risk, then &lt;strong&gt;stress&lt;/strong&gt; may be the confounder.&lt;/p&gt;

&lt;h3 id=&quot;example-2-extra-tutoring-and-exam-scores&quot;&gt;Example 2: extra tutoring and exam scores&lt;/h3&gt;

&lt;p&gt;If weak students tend to attend more tutoring, while exam results depend strongly on initial ability, then &lt;strong&gt;entry level&lt;/strong&gt; is a confounder when we study the effectiveness of tutoring.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_confounding_dag_overview.png&quot; alt=&quot;Confounding overview diagram&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The key point is that confounding creates an extra line of association between \(X\) and \(Y\). If it is not handled, we easily attribute the confounder’s effect to the treatment’s effect.&lt;/p&gt;

&lt;h2 id=&quot;3-what-is-a-dag-and-why-is-it-useful&quot;&gt;3. What is a DAG and why is it useful?&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;DAG&lt;/strong&gt; stands for &lt;em&gt;Directed Acyclic Graph&lt;/em&gt;, which can be understood as a directed graph with no cycles. More specifically, &lt;em&gt;Directed&lt;/em&gt; means the arrows have direction, &lt;em&gt;Acyclic&lt;/em&gt; means there are no closed loops, and &lt;em&gt;Graph&lt;/em&gt; means a diagram representing relationships between variables.&lt;/p&gt;

&lt;p&gt;A DAG helps us answer a very practical question:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;In this causal question, which variables should go into the model, and which should not?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Instead of rushing into running a regression, we draw the story first.&lt;/p&gt;

&lt;h2 id=&quot;4-three-basic-structures-to-remember&quot;&gt;4. Three basic structures to remember&lt;/h2&gt;

&lt;p&gt;Most complex DAGs are assembled from the following three basic structures.&lt;/p&gt;

&lt;h3 id=&quot;41-fork-a-common-cause&quot;&gt;4.1. Fork: a common cause&lt;/h3&gt;

\[Z \rightarrow X,\quad Z \rightarrow Y\]

&lt;p&gt;This is the structure of confounding.&lt;/p&gt;

&lt;p&gt;For example, age affects the level of exercise and also affects blood pressure. If we want to study how exercise affects blood pressure, &lt;strong&gt;age&lt;/strong&gt; is a variable that should be adjusted for.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_fork_structure.png&quot; alt=&quot;Fork structure: a common cause creating confounding&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;42-chain-a-mediating-variable&quot;&gt;4.2. Chain: a mediating variable&lt;/h3&gt;

\[X \rightarrow M \rightarrow Y\]

&lt;p&gt;This is a mediator. For example, exercise lowers weight, and weight loss in turn helps improve blood sugar.&lt;/p&gt;

&lt;p&gt;If we want to measure the &lt;strong&gt;total effect&lt;/strong&gt; of exercise on blood sugar, we should not adjust for weight, because that blocks part of the true pathway of influence.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_chain_structure.png&quot; alt=&quot;Chain structure: the mediator lies on the path of influence&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_mediation_overview.png&quot; alt=&quot;Overview of mediation in a causal story&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;43-collider-two-arrows-pointing-into-one-node&quot;&gt;4.3. Collider: two arrows pointing into one node&lt;/h3&gt;

\[X \rightarrow C \leftarrow Y\]

&lt;p&gt;A collider is dangerous because when we condition on it, we can create a spurious correlation.&lt;/p&gt;

&lt;p&gt;For example, ability and luck both affect being hired; if we look only at the group that was hired, we may see that people who are “less lucky” are often “very good”, and vice versa.&lt;/p&gt;

&lt;p&gt;That is not a true law of the whole population, but a consequence of looking only at the collider.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_collider_structure.png&quot; alt=&quot;Collider structure: conditioning can open up a spurious correlation&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_collider_bias_overview.png&quot; alt=&quot;Overview of collider bias in a causal diagram&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;experiment-a-confounder-biases-the-coefficient-and-adjusting-for-z-fixes-it&quot;&gt;Experiment: a confounder biases the coefficient and adjusting for Z fixes it&lt;/h3&gt;

&lt;p&gt;Simulate the fork Z → X, Z → Y: the naive estimate, stratification (Simpson’s paradox), then regression with Z.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;confound-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;fork&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;5-practical-rule-should-we-control-or-not&quot;&gt;5. Practical rule: should we control or not?&lt;/h2&gt;

&lt;p&gt;A short memory aid is: &lt;strong&gt;do control for confounders&lt;/strong&gt;, &lt;strong&gt;do not control for mediators if the goal is the total effect&lt;/strong&gt;, and &lt;strong&gt;do not control for colliders&lt;/strong&gt;. This rule sounds simple, but applying it correctly requires a sufficiently clear causal diagram.&lt;/p&gt;

&lt;h2 id=&quot;6-simpsons-paradox-an-example-that-makes-many-people-change-how-they-think&quot;&gt;6. Simpson’s Paradox: an example that makes many people change how they think&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_simpsons_paradox_overview.png&quot; alt=&quot;Quick illustration of Simpson&apos;s Paradox&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_simpsons_aggregate_bias.png&quot; alt=&quot;Aggregated data produces a wrong conclusion about the treatment&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_simpsons_stratified_effect.png&quot; alt=&quot;Splitting by severity shows the true effect of the treatment&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Simpson’s Paradox occurs when looking at the whole data shows one trend, but when split by an important group that trend reverses. For example in medicine, looking at the whole, the group given aggressive treatment seems to recover worse, but when patients are split by severity, within each severity group aggressive treatment is better. The reason is that severe cases were given stronger treatment, while those same severe cases were also harder to recover to begin with.&lt;/p&gt;

&lt;p&gt;The variable “severity” distorted the treatment-outcome relationship when it was ignored.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_simpsons_dag_unadjusted.png&quot; alt=&quot;DAG of Simpson&apos;s Paradox before adjusting for the confounder&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_simpsons_dag_adjusted.png&quot; alt=&quot;DAG after adjusting for severity to reveal the causal effect&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This is a very good example to remind ourselves that:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;aggregated data can tell a wrong story if we do not separate the right structure.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;61-a-very-short-table-to-see-this-paradox&quot;&gt;6.1. A very short table to see this paradox&lt;/h3&gt;

&lt;p&gt;Suppose a hospital has two treatment levels, &lt;strong&gt;aggressive treatment&lt;/strong&gt; and &lt;strong&gt;standard treatment&lt;/strong&gt;, and patients are divided into two groups, &lt;strong&gt;severe cases&lt;/strong&gt; and &lt;strong&gt;mild cases&lt;/strong&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Patient group&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Aggressive treatment&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Standard treatment&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Severe cases&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;24/80 recovered = 30%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6/30 recovered = 20%&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mild cases&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;54/60 recovered = 90%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;144/180 recovered = 80%&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Within &lt;strong&gt;each severity group&lt;/strong&gt;, aggressive treatment is better.&lt;/p&gt;

&lt;p&gt;But if we pool all patients together:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;aggressive treatment: \(78/140 \approx 55.7\%\) recovered,&lt;/li&gt;
  &lt;li&gt;standard treatment: \(150/210 \approx 71.4\%\) recovered.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Looking at the whole, aggressive treatment seems worse. The reason is not that the treatment harms patients, but that the aggressive-treatment group contains a larger share of severe cases. This is a very intuitive way to see how confounding can reverse the story.&lt;/p&gt;

&lt;h2 id=&quot;7-what-is-a-backdoor-path&quot;&gt;7. What is a backdoor path?&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;backdoor path&lt;/strong&gt; can be understood as a non-causal path linking the treatment \(X\) to the outcome \(Y\) through common causes. The goal of adjustment is to block the backdoor paths that need blocking, but not to block the true causal path of influence from \(X\) to \(Y\).&lt;/p&gt;

&lt;p&gt;The examples below show that a backdoor path can be simple, have multiple branches, be blocked already by a collider, or be opened by mistake through M-bias.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_backdoor_simple.png&quot; alt=&quot;Simple backdoor path example&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_backdoor_multiple.png&quot; alt=&quot;Example with multiple backdoor paths that must be blocked at the same time&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_backdoor_blocked_by_collider.png&quot; alt=&quot;Backdoor path naturally blocked by a collider&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_backdoor_m_bias.png&quot; alt=&quot;M-bias: wrong adjustment can open a backdoor path&quot; /&gt;&lt;/p&gt;

&lt;p&gt;For example, if we want to know how extra tutoring \(X\) affects exam scores \(Y\), while initial ability \(Z\) affects both attending tutoring and exam scores, then the path \(X \leftarrow Z \rightarrow Y\) is a backdoor path. Adjusting for \(Z\) helps block this path.&lt;/p&gt;

&lt;h2 id=&quot;8-how-do-sufficient-adjustment-and-wrong-adjustment-differ&quot;&gt;8. How do sufficient adjustment and wrong adjustment differ?&lt;/h2&gt;

&lt;p&gt;Comparing the four adjustment set choices below will help clearly show the difference between sufficient adjustment, adjustment that loses mediation, adjusting for a collider, and not adjusting at all.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_adjustment_valid_z1_z2.png&quot; alt=&quot;Valid adjustment set blocks the backdoor paths that need blocking&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_adjustment_valid_but_mediator.png&quot; alt=&quot;Valid adjustment set but only the direct effect remains&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_adjustment_invalid_collider.png&quot; alt=&quot;Wrong adjustment set because it adjusts for a collider&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_adjustment_invalid_none.png&quot; alt=&quot;No adjustment leaves the backdoor paths open&quot; /&gt;&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;valid adjustment set&lt;/strong&gt; is a set of variables that blocks all the backdoor paths that need blocking, does not open new wrong paths, and does not accidentally block the part of the effect that we want to measure. Therefore, we do not need to adjust for “as many as possible”; what matters is to adjust for the &lt;strong&gt;right variables&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;a-real-world-example&quot;&gt;A real-world example&lt;/h3&gt;

&lt;p&gt;In a study of the effect of exercise on cardiovascular health, &lt;strong&gt;age&lt;/strong&gt; and &lt;strong&gt;eating habits&lt;/strong&gt; may be confounders, &lt;strong&gt;current weight&lt;/strong&gt; may be a mediator, and the &lt;strong&gt;number of hospital admissions&lt;/strong&gt; may be a collider if it is both influenced by health and related to the likelihood of being medically monitored. If we stuff everything into one model without thinking, we can easily create bias ourselves.&lt;/p&gt;

&lt;p&gt;A more practical way to put it is:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;if the goal is the &lt;strong&gt;total effect&lt;/strong&gt; of exercise on cardiovascular health, we usually want to adjust for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;age&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eating habits&lt;/code&gt;,&lt;/li&gt;
  &lt;li&gt;but we should not rush to adjust for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;current weight&lt;/code&gt; if weight is itself part of the pathway through which exercise has its effect,&lt;/li&gt;
  &lt;li&gt;and we certainly should not add &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number of hospital admissions&lt;/code&gt; just because “the data is there”, if this variable plays the role of a collider.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The important point is that a good adjustment set must come from the causal story, not from the habit of stuffing every data column into the model.&lt;/p&gt;

&lt;h2 id=&quot;9-collider-bias-a-very-common-mistake-when-controlling-for-everything&quot;&gt;9. Collider bias: a very common mistake when “controlling for everything”&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_collider_general_population.png&quot; alt=&quot;In the general population, the two causes of a collider can be independent&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_collider_conditioned_sample.png&quot; alt=&quot;When conditioning on the collider, a spurious correlation appears&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Collider bias often appears when we look only at a selected group.&lt;/p&gt;

&lt;p&gt;For example, ability and luck both affect being admitted to a highly competitive company. In the general population, ability and luck may be unrelated, but in the group that was admitted, less lucky people usually have to be better to still get in.&lt;/p&gt;

&lt;p&gt;The result is that we see a spurious negative correlation between ability and luck in the selected group.&lt;/p&gt;

&lt;p&gt;A very important lesson:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Adding any variable to the model does not necessarily make the analysis better.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;experiment-conditioning-on-a-collider-creates-a-spurious-correlation&quot;&gt;Experiment: conditioning on a collider creates a spurious correlation&lt;/h3&gt;

&lt;p&gt;X and Y are independent but both point into C; just filtering on C makes them negatively correlated.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;confound-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;collider&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;10-a-very-practical-dag-workflow&quot;&gt;10. A very practical DAG workflow&lt;/h2&gt;

&lt;p&gt;When facing a causal question, you can follow the four fairly practical steps below.&lt;/p&gt;

&lt;h3 id=&quot;step-1-define-the-question&quot;&gt;Step 1. Define the question&lt;/h3&gt;

&lt;p&gt;First, determine whether you are asking about the effect of \(X\) on \(Y\), or simply want to predict \(Y\). If the goal is causal, the DAG becomes especially important.&lt;/p&gt;

&lt;h3 id=&quot;step-2-list-the-relevant-variables&quot;&gt;Step 2. List the relevant variables&lt;/h3&gt;

&lt;p&gt;At the variable-listing step, think in everyday language: what affects the treatment, what affects the outcome, what lies between the treatment and the outcome, and what is the common result of two different things.&lt;/p&gt;

&lt;h3 id=&quot;step-3-draw-the-arrows-according-to-the-real-story&quot;&gt;Step 3. Draw the arrows according to the real story&lt;/h3&gt;

&lt;p&gt;There is no need to draw beautifully from the start. What matters is to draw the correct domain intuition.&lt;/p&gt;

&lt;h3 id=&quot;step-4-decide-the-adjustment-set&quot;&gt;Step 4. Decide the adjustment set&lt;/h3&gt;

&lt;p&gt;At the final step, ask yourself which variables need to be adjusted for to block backdoor paths, and which must not be adjusted for because they are actually mediators or colliders.&lt;/p&gt;

&lt;h2 id=&quot;11-an-interactive-tool-for-practicing-dags&quot;&gt;11. An interactive tool for practicing DAGs&lt;/h2&gt;

&lt;p&gt;You can use the website’s DAG Explorer tool to draw the situations in this lesson yourself:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;/tools/dag-explorer/standalone.html&quot; target=&quot;_blank&quot;&gt;Open the Interactive DAG Explorer&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A suggestion is to draw the ice cream and drowning example, the extra tutoring and exam scores example, the exercise - weight loss - health example, and then try changing one variable from confounder to collider to see how the logic changes.&lt;/p&gt;

&lt;h2 id=&quot;12-the-most-important-point-of-this-lesson&quot;&gt;12. The most important point of this lesson&lt;/h2&gt;

&lt;p&gt;Confounding is not a minor technical error. It is the central problem of every analysis that wants to talk about causes.&lt;/p&gt;

&lt;p&gt;If we do not think causally first, the regression can run beautifully, the interval can look very convincing, but the final conclusion is still wrong.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; A confounder is a variable that affects both the treatment and the outcome, so if we ignore it we easily misestimate the effect we care about; a DAG is a tool for drawing the causal structure before running the model, so that we can decide which variables should and should not be adjusted for; and we should not “control for everything”, because confounders usually need adjustment, while mediators and colliders must be handled carefully depending on the question.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-seeing-collider-bias-appear-out-of-thin-air-4-actors&quot;&gt;Worked Numerical Example: Seeing Collider Bias Appear Out of Thin Air (4 Actors)&lt;/h3&gt;

&lt;p&gt;Suppose &lt;strong&gt;Acting Talent (\(X \in \{0,1\}\))&lt;/strong&gt; and &lt;strong&gt;Looks (\(Y \in \{0,1\}\))&lt;/strong&gt; are completely &lt;strong&gt;independent&lt;/strong&gt; in the general population (each 50%, so 4 equally likely combinations of 25% each), and Hollywood casts anyone with &lt;em&gt;either&lt;/em&gt; high talent &lt;em&gt;or&lt;/em&gt; great looks (&lt;strong&gt;Fame \(Z = 1 \iff X=1 \text{ or } Y=1\)&lt;/strong&gt;):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Talent (\(X\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Looks (\(Y\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Population Share&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Famous (\(Z=1\))?&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\) (High)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\) (High)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(25\%\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Yes&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\) (High)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\) (Low)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(25\%\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Yes&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\) (Low)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\) (High)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(25\%\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Yes&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\) (Low)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\) (Low)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(25\%\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;No (excluded!)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;In the full population (unconditioned):&lt;/strong&gt; \(P(X=1 \mid Y=1) = 50\% = P(X=1)\) (zero correlation!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Conditioned on being Famous (\(Z = 1\), the top 3 rows):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;If a famous actor has High Looks (\(Y=1\), rows 1 &amp;amp; 3): \(P(X=1 \mid Y=1, Z=1) = \mathbf{50\%}\).&lt;/li&gt;
      &lt;li&gt;If a famous actor has Low Looks (\(Y=0\), row 2 only!): \(P(X=1 \mid Y=0, Z=1) = \mathbf{100\%}\)!
Conditioning on the collider \(Z\) created a &lt;strong&gt;strong negative correlation&lt;/strong&gt; between Talent and Looks where none existed in reality!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-causal-rules-before-running-any-observational-regression&quot;&gt;Explanation: Four Causal Rules Before Running Any Observational Regression&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Draw the DAG &lt;em&gt;before&lt;/em&gt; choosing regression predictors:&lt;/strong&gt; Data alone cannot tell a Fork from a Pipe or a Collider—causal structure comes from domain science!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stop calling every regression coefficient a “causal effect”:&lt;/strong&gt; Only variables whose backdoor paths are properly closed have causal interpretations (avoid the &lt;em&gt;Table 2 Fallacy&lt;/em&gt; of reading all covariates in one model as causal!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never throw “all available columns” into a causal regression (“causal salad”):&lt;/strong&gt; Including a collider or post-treatment variable actively &lt;em&gt;destroys&lt;/em&gt; causal identification.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dagitty&lt;/code&gt; or the backdoor rule to verify your adjustment set:&lt;/strong&gt; Even a 5-node DAG can hide subtle backdoor paths that human intuition misses.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; You want to estimate the &lt;strong&gt;total&lt;/strong&gt; causal effect of a new fertilizer (\(X\)) on crop yield (\(Y\)), and you also measured mid-season fungus levels (\(Z\)), which the fertilizer &lt;em&gt;reduces&lt;/em&gt; (\(X \rightarrow Z \rightarrow Y\)). Should you include mid-season fungus \(Z\) as a predictor in your regression—and why?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mBEA7PKDmiY&quot;&gt;Statistical Rethinking 2023 - 05 - Elemental Confounds&lt;/a&gt; — Richard McElreath, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch confounding drawn as shared arrows, exactly the part of the lesson that separates correlation from direct causal relationship.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=uanZZLlzKHw&quot;&gt;Statistical Rethinking 2023 - 06 - Good &amp;amp; Bad Controls&lt;/a&gt; — Richard McElreath, English. Watch correct and incorrect controls, supporting the decision of when to adjust for a variable.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=U1S8Rq8IcrY&quot;&gt;4.6 - The Backdoor Adjustment&lt;/a&gt; — Brady Neal - Causal Inference, English. Watch the backdoor adjustment, used where the lesson turns a DAG into a rule of adjusting or not.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;In a study of the effect of tutoring on exam scores, which variable could be a confounder?&lt;/li&gt;
  &lt;li&gt;Why shouldn’t a mediator always be controlled for?&lt;/li&gt;
  &lt;li&gt;Think of a collider example in your own life or work.&lt;/li&gt;
  &lt;li&gt;What does Simpson’s Paradox teach us about reading aggregated data?&lt;/li&gt;
  &lt;li&gt;Try drawing a simple DAG for the question: “Does exercise help you sleep better?”&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Pearl, J. (2009).&lt;/strong&gt; &lt;em&gt;Causality: Models, Reasoning, and Inference&lt;/em&gt; (2nd Edition). Cambridge University Press.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hernan, M. A., &amp;amp; Robins, J. M. (2020).&lt;/strong&gt; &lt;em&gt;Causal Inference: What If&lt;/em&gt;. Chapman &amp;amp; Hall/CRC.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter05/05_03_multicollinearity/&quot;&gt;5.3 Multicollinearity&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 5.1: Multiple Regression - From One to Many Predictors</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter05/05_01_multiple_predictors/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter05/05_01_multiple_predictors</id>
   <content type="html">&lt;p&gt;Adding a second predictor to a regression can do something that feels like black magic: a variable that looked &lt;strong&gt;positively&lt;/strong&gt; correlated with your outcome when analyzed alone can flip to &lt;strong&gt;negative&lt;/strong&gt; (or drop to exact zero!) the moment you control for a second variable! Understanding &lt;em&gt;why&lt;/em&gt; that happens—&lt;strong&gt;partial (conditional) effects&lt;/strong&gt;—is the gateway from simple curve fitting to real-world Bayesian multiple regression.&lt;/p&gt;

&lt;p&gt;This lesson extends single-predictor Bayesian regression to multiple predictors \(\mu_i = \alpha + \beta_1 x_{1i} + \cdots + \beta_p x_{pi}\), explains why &lt;strong&gt;standardizing predictors&lt;/strong&gt; makes priors and MCMC geometry vastly cleaner, and teaches you to read partial slopes accurately.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-partial-effects-standardization-and-posterior-geometry&quot;&gt;Key ideas: Partial Effects, Standardization, and Posterior Geometry&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Conditional (“Holding Other Predictors Constant”) Interpretation:&lt;/strong&gt; In multiple regression, \(\beta_1\) answers &lt;em&gt;“what is the expected change in \(Y\) for a 1-unit increase in \(X_1\) among observations with the &lt;strong&gt;exact same&lt;/strong&gt; value of \(X_2\)?”&lt;/em&gt;—not the raw marginal correlation!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why Standardizing Predictors (\(z = (x - \bar{x})/s_x\)) Is a Bayesian Superpower:&lt;/strong&gt; Removes arbitrary unit scales (mm vs. km), centers the intercept \(\alpha\) at the mean outcome (breaking correlation between \(\alpha\) and slopes \(\beta_j\)), and lets you apply clean weakly informative priors like \(\beta_j \sim \mathcal{N}(0, 1)\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Spurious vs. Masked Relationships:&lt;/strong&gt; Controlling for a second predictor can &lt;em&gt;reveal&lt;/em&gt; a spurious correlation (when \(X_2\) causes both \(X_1\) and \(Y\)) OR &lt;em&gt;unmask&lt;/em&gt; a real relationship that was previously hidden by two opposing effects!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior Uncertainty Reflects Shared Information:&lt;/strong&gt; When predictors share variance, Bayesian multiple regression automatically widens the marginal posterior intervals of \(\beta_1, \beta_2\) to honestly reflect what the data cannot separate.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to understand why many real problems cannot use just one predictor. You also need to grasp the most important meaning of multiple regression: each coefficient should be read only as the effect of one variable when the other variables are held fixed. This is the foundation for reading regression results correctly in later lessons.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; A company wants to predict employees’ salaries. If we look only at years of experience, we will miss degree, job position, and region of residence. Multiple regression lets us include many factors at once so that the picture is fairer and closer to reality.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If two people have the same years of experience but different education, can a model with only one predictor describe the salary difference between them?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;1-why-is-one-predictor-often-not-enough&quot;&gt;1. Why is one predictor often not enough?&lt;/h2&gt;

&lt;p&gt;In Chapter 4, we learned the simple linear regression model:&lt;/p&gt;

\[y = \alpha + \beta x + \epsilon\]

&lt;p&gt;This model is very useful for building intuition, but the real world is rarely that simple. An exam score, for instance, depends not only on study hours but also on background knowledge, sleep quality, and the difficulty of the exam; a house price depends not only on floor area but also on location, the age of the house, the number of bedrooms, and the surrounding infrastructure; and weight is related not only to height but also to age, sex, activity level, and diet. If we try to force a many-cause problem into a one-variable model, we very easily both miss important information and misinterpret the meaning of the coefficient.&lt;/p&gt;

&lt;p&gt;Multiple regression was created to handle exactly this situation.&lt;/p&gt;

&lt;h2 id=&quot;2-what-does-a-model-with-many-predictors-look-like&quot;&gt;2. What does a model with many predictors look like?&lt;/h2&gt;

&lt;p&gt;The general model is:&lt;/p&gt;

\[y = \alpha + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_k x_k + \epsilon\]

&lt;p&gt;Here, \(y\) is the outcome, \(x_1, x_2, \ldots, x_k\) are the predictors, \(\alpha\) is the intercept, and each \(\beta_j\) is the coefficient of the \(j\)-th predictor. The idea of this model is very natural: we add up the contribution of each predictor and then add a noise term \(\epsilon\), because real data always fluctuates around the average trend and never lies exactly on a rigid formula.&lt;/p&gt;

&lt;p&gt;The three views below show that the same outcome can be seen as several two-dimensional slices or as a multidimensional surface.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_weight_vs_height_colored_by_age.png&quot; alt=&quot;Weight by height, colored by age&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_weight_vs_age_colored_by_height.png&quot; alt=&quot;Weight by age, colored by height&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter05/chapter05_weight_height_age_3d.png&quot; alt=&quot;3D view of weight by height and age&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The three figures above help us see that an outcome can change along &lt;strong&gt;many dimensions at once&lt;/strong&gt;. When we look at each two-dimensional plot separately, we see only one slice of the problem. Multiple regression tries to stitch those slices together into one joint model.&lt;/p&gt;

&lt;h2 id=&quot;3-the-most-important-meaning-holding-the-other-variables-fixed&quot;&gt;3. The most important meaning: “holding the other variables fixed”&lt;/h2&gt;

&lt;p&gt;This is the hardest idea but also the most important idea of this whole chapter.&lt;/p&gt;

&lt;p&gt;In multiple regression, the coefficient \(\beta_1\) no longer means:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;whenever \(x_1\) increases by one unit, \(y\) increases by \(\beta_1\) units.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The correct meaning is:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;when the other predictors are held fixed, if \(x_1\) increases by one unit, then \(y\) changes on average by about \(\beta_1\) units.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It may sound like only a few extra words, but the meaning changes a lot.&lt;/p&gt;

&lt;h3 id=&quot;example-1-salary-experience-and-education&quot;&gt;Example 1: salary, experience, and education&lt;/h3&gt;

&lt;p&gt;Suppose we have the model:&lt;/p&gt;

\[\text{Salary} = \alpha + \beta_1 \cdot \text{Experience} + \beta_2 \cdot \text{Education} + \epsilon\]

&lt;p&gt;Then, \(\beta_1\) must be read as the expected salary difference between two people with the &lt;strong&gt;same education&lt;/strong&gt; who differ by one year of experience, while \(\beta_2\) is the expected salary difference between two people with the &lt;strong&gt;same years of experience&lt;/strong&gt; who differ by one education level. This is a far more realistic reading than mixing all the differences into a single coefficient.&lt;/p&gt;

&lt;h3 id=&quot;example-2-weight-height-and-age&quot;&gt;Example 2: weight, height, and age&lt;/h3&gt;

&lt;p&gt;If the model is:&lt;/p&gt;

\[\text{Weight} = \alpha + \beta_1 \cdot \text{Height} + \beta_2 \cdot \text{Age} + \epsilon\]

&lt;p&gt;then \(\beta_1\) speaks about the effect of height among people of the same age, while \(\beta_2\) speaks about the effect of age among people of the same height. In short, multiple regression always compares in the style of “&lt;strong&gt;everything else equal, only one variable changes&lt;/strong&gt;”.&lt;/p&gt;

&lt;h3 id=&quot;31-a-numerical-example-for-reading-coefficients-correctly&quot;&gt;3.1. A numerical example for reading coefficients correctly&lt;/h3&gt;

&lt;p&gt;Suppose we fit a salary model on experience and education as follows:&lt;/p&gt;

\[\text{Salary} = 8 + 0.6 \cdot \text{Experience} + 2.5 \cdot \text{Postgraduate}.\]

&lt;p&gt;Here:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Experience&lt;/code&gt; is measured in years,&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Postgraduate = 1&lt;/code&gt; if the person has a postgraduate degree, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;= 0&lt;/code&gt; otherwise,&lt;/li&gt;
  &lt;li&gt;salary is measured in millions of VND per month.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;if two people have the &lt;strong&gt;same education&lt;/strong&gt;, the person with 1 more year of experience has an expected salary higher by about &lt;strong&gt;0.6 million/month&lt;/strong&gt;,&lt;/li&gt;
  &lt;li&gt;if two people have the &lt;strong&gt;same years of experience&lt;/strong&gt;, the person with a postgraduate degree has an expected salary higher by about &lt;strong&gt;2.5 million/month&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A concrete example:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Person A: 5 years of experience, no postgraduate degree&lt;br /&gt;
\(8 + 0.6 \times 5 + 2.5 \times 0 = 11\)&lt;/li&gt;
  &lt;li&gt;Person B: 6 years of experience, no postgraduate degree&lt;br /&gt;
\(8 + 0.6 \times 6 + 2.5 \times 0 = 11.6\)&lt;/li&gt;
  &lt;li&gt;Person C: 5 years of experience, with a postgraduate degree&lt;br /&gt;
\(8 + 0.6 \times 5 + 2.5 \times 1 = 13.5\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Comparing A with B gives us the reading of the experience coefficient. Comparing A with C gives us the reading of the education coefficient. This is exactly the “hold the other variables fixed” logic written out as numbers.&lt;/p&gt;

&lt;h2 id=&quot;4-why-can-the-coefficients-in-simple-regression-and-multiple-regression-differ&quot;&gt;4. Why can the coefficients in simple regression and multiple regression differ?&lt;/h2&gt;

&lt;p&gt;This is something that confuses many beginners.&lt;/p&gt;

&lt;p&gt;A predictor in simple regression can carry the influence of variables not yet put into the model.&lt;/p&gt;

&lt;p&gt;The salary example shows this very clearly: if more educated people usually also have more experience, then a model using only education may “absorb” part of the effect of experience into the education coefficient.&lt;/p&gt;

&lt;p&gt;When experience is added to the model, the education coefficient may decrease. This does not mean the new model is worse. On the contrary, it usually means the new model is separating the sources of influence more clearly.&lt;/p&gt;

&lt;h3 id=&quot;an-intuitive-way-of-thinking&quot;&gt;An intuitive way of thinking&lt;/h3&gt;

&lt;p&gt;Simple regression answers:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;looking at the whole picture, how does this variable go along with the outcome?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Multiple regression answers:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;if we try to hold the other factors stable, how is this variable still related to the outcome?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Hence these two questions are different, so it is normal for the answers to differ.&lt;/p&gt;

&lt;h2 id=&quot;5-a-real-example-predicting-house-prices&quot;&gt;5. A real example: predicting house prices&lt;/h2&gt;

&lt;p&gt;Suppose we want to predict house prices from three variables: floor area, number of bedrooms, and distance to the center.&lt;/p&gt;

&lt;p&gt;A reasonable model is:&lt;/p&gt;

\[\text{House price} = \alpha + \beta_1 \cdot \text{Area} + \beta_2 \cdot \text{Bedrooms} + \beta_3 \cdot \text{Distance} + \epsilon\]

&lt;p&gt;The correct interpretation here is: \(\beta_1\) tells us, between two houses with the same number of bedrooms and the same distance to the center, how much the expected price differs for a house with 1 more square meter; \(\beta_2\) tells us, between two houses with the same area and location, how the expected price changes when adding 1 bedroom; and \(\beta_3\) tells us, between two houses with the same area and number of rooms, how much the expected price differs for a house 1 km farther from the center.&lt;/p&gt;

&lt;p&gt;If we do not say clearly “holding the other variables fixed”, the reader can easily misunderstand the coefficient.&lt;/p&gt;

&lt;h3 id=&quot;51-why-doesnt-adding-1-bedroom-always-raise-the-price-by-the-same-amount&quot;&gt;5.1. Why doesn’t adding 1 bedroom always raise the price by the same amount?&lt;/h3&gt;

&lt;p&gt;Suppose the estimated model is:&lt;/p&gt;

\[\text{House price} = 1.2 + 0.035 \cdot \text{Area} + 0.18 \cdot \text{Bedrooms} - 0.25 \cdot \text{Distance},\]

&lt;p&gt;where price is measured in &lt;strong&gt;billions of VND&lt;/strong&gt;, area in &lt;strong&gt;m²&lt;/strong&gt;, and distance to the center in &lt;strong&gt;km&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Then, comparing two houses with the same number of bedrooms and the same location, a house 10 m² larger will have an expected price higher by about:&lt;/p&gt;

\[0.035 \times 10 = 0.35\ \text{billion VND}.\]

&lt;p&gt;If we compare two houses with the same area and the same location, a house with 1 more bedroom will have an expected price higher by about:&lt;/p&gt;

\[0.18\ \text{billion VND}.\]

&lt;p&gt;But note: this coefficient &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.18&lt;/code&gt; does not mean that “in every circumstance, adding 1 bedroom raises the price by 180 million”. It is correct only for comparisons between houses &lt;strong&gt;with area and location held fixed&lt;/strong&gt;. In real data, an extra bedroom usually also comes with a larger house, so if we forget this condition we will misread the coefficient very quickly.&lt;/p&gt;

&lt;h2 id=&quot;6-what-does-multiple-regression-do-for-us&quot;&gt;6. What does multiple regression do for us?&lt;/h2&gt;

&lt;h3 id=&quot;61-better-prediction&quot;&gt;6.1. Better prediction&lt;/h3&gt;

&lt;p&gt;When the outcome truly depends on many factors, adding appropriate predictors usually helps predict more closely. For example, predicting an exam score from study hours alone is usually worse than predicting from study hours combined with the background score and the attendance rate.&lt;/p&gt;

&lt;h3 id=&quot;62-fairer-explanation&quot;&gt;6.2. Fairer explanation&lt;/h3&gt;

&lt;p&gt;We can separate the influence of each variable instead of dumping everything on a single predictor. For example, to evaluate the effectiveness of a course, we should consider study time, level of participation, and entry level at the same time instead of looking at one single measure.&lt;/p&gt;

&lt;h3 id=&quot;63-preparing-for-causal-thinking&quot;&gt;6.3. Preparing for causal thinking&lt;/h3&gt;

&lt;p&gt;Multiple regression does not automatically create causation, but it is a first step toward learning how to adjust for related variables, make fairer comparisons between groups, and think seriously about confounding in the next lesson.&lt;/p&gt;

&lt;h2 id=&quot;7-what-should-we-be-careful-about-when-using-many-predictors&quot;&gt;7. What should we be careful about when using many predictors?&lt;/h2&gt;

&lt;p&gt;Adding more variables is not always good. There are at least three situations where we need to be especially careful.&lt;/p&gt;

&lt;h3 id=&quot;71-omitting-an-important-variable&quot;&gt;7.1. Omitting an important variable&lt;/h3&gt;

&lt;p&gt;If an important variable is left out, the remaining coefficients can be distorted.&lt;/p&gt;

&lt;h3 id=&quot;72-predictors-that-are-too-similar&quot;&gt;7.2. Predictors that are too similar&lt;/h3&gt;

&lt;p&gt;If two variables measure nearly the same thing, the model will have difficulty separating the effect of each. This is the topic of Lesson 5.3 on multicollinearity.&lt;/p&gt;

&lt;h3 id=&quot;73-adding-variables-without-thinking&quot;&gt;7.3. Adding variables without thinking&lt;/h3&gt;

&lt;p&gt;It is not true that “controlling for everything” is always good. Some variables should be included, but others should not. This is the content of Lesson 5.2 on confounding and DAGs.&lt;/p&gt;

&lt;h2 id=&quot;8-seeing-multiple-regression-as-a-data-generating-story&quot;&gt;8. Seeing multiple regression as a data-generating story&lt;/h2&gt;

&lt;p&gt;A Bayesian way of understanding is to see the model as a story in which each subject has different features, each feature contributes a part to the outcome, and the rest is fluctuation that the model cannot fully explain. For exam scores, this means each student has different study hours, entry scores, and attendance rates; these factors combine to produce an expected score; and the real result still fluctuates further because of health, exam-room psychology, and other random factors.&lt;/p&gt;

&lt;p&gt;When we think this way, the formula is no longer dry notation, but a summary of a real process.&lt;/p&gt;

&lt;h2 id=&quot;9-when-reporting-results-how-should-we-interpret-them&quot;&gt;9. When reporting results, how should we interpret them?&lt;/h2&gt;

&lt;p&gt;A good interpretation usually has three connected parts: name the predictor clearly, state the condition “holding the other variables fixed”, and then tie the result to real units instead of leaving behind an abstract coefficient.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Holding education and job position constant, each additional year of experience is associated with an expected salary higher by about X million VND.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This kind of interpretation is much clearer than just saying:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;\(\beta_1 = 0.42\).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;10-connecting-to-the-next-lessons&quot;&gt;10. Connecting to the next lessons&lt;/h2&gt;

&lt;p&gt;Multiple regression is the doorway to three very practical questions: whether any variable is distorting the relationship we care about, whether the predictors are too similar to each other, and whether the effect of one variable depends on another. Understanding this lesson firmly will help you not feel “overwhelmed” when moving on to confounding, multicollinearity, and interaction in the next three lessons.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; Multiple regression lets us describe an outcome with many predictors at once, so it fits real problems better; each coefficient in multiple regression must always be read together with the condition “holding the other variables fixed”; and when a coefficient changes after adding a new predictor, that is usually a sign that the model is separating the influences better, not a sign that the model is wrong.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-watching-a-partial-slope-flip-from-spurious-to-zero&quot;&gt;Worked Numerical Example: Watching a Partial Slope Flip From Spurious to Zero&lt;/h3&gt;

&lt;p&gt;Suppose ice-cream sales (\(X_1\)) and shark attacks (\(Y\)) both depend on summer temperature (\(X_2\), standardized):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bivariate regression&lt;/strong&gt; (\(Y \sim X_1\) alone): yields posterior \(\beta_1 \approx +0.78 \pm 0.12\) (strong positive association!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multiple regression&lt;/strong&gt; (\(Y \sim X_1 + X_2\)): holding temperature \(X_2\) constant, suppose the fitted posterior gives:
\(\mu_i = 5.0 + \underbrace{0.02}_{\beta_1 \text{ (SD } 0.15\text{)}} X_{1i} + \underbrace{0.85}_{\beta_2 \text{ (SD } 0.14\text{)}} X_{2i}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;95% Credible Interval for \(\beta_1\):&lt;/strong&gt; \(0.02 \pm 1.96(0.15) = [-0.27,\; +0.31]\) (straddling zero cleanly!), while \(\beta_2\) sits cleanly at \([+0.58,\; +1.12]\)! Once you know temperature, knowing ice-cream sales adds &lt;strong&gt;zero&lt;/strong&gt; predictive information about shark attacks!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-rules-for-bayesian-multiple-regression&quot;&gt;Explanation: Four Rules for Bayesian Multiple Regression&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always plot counterfactual / predictor-residual plots:&lt;/strong&gt; Don’t just stare at a table of 8 regression coefficients—plot predicted \(Y\) as \(X_1\) varies while holding \(X_2\) fixed at its mean.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adding more predictors is NOT always better:&lt;/strong&gt; As the very next lesson (DAGs &amp;amp; Confounding) proves, controlling for the &lt;em&gt;wrong&lt;/em&gt; variable (a collider or post-treatment mediator!) can actually &lt;em&gt;create&lt;/em&gt; bias out of thin air!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check correlation among posterior slopes (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pair_plot&lt;/code&gt;):&lt;/strong&gt; A strong negative diagonal band between \(\beta_1\) and \(\beta_2\) warns you that the data pins down their &lt;em&gt;sum&lt;/em&gt; well, even if each individual slope looks wide.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use posterior predictive plots to verify fit across all predictors:&lt;/strong&gt; Plot residuals against every \(X_j\) to catch missed curvature or interactions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In a standardized multiple regression where \(X_1, X_2\) have mean 0 and SD 1, what is the concrete meaning of the intercept \(\alpha\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EkAQAi3a4js&quot;&gt;Multiple Regression, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch each coefficient as a contribution when the other predictors are already in the model, exactly how the lesson reads multiple regression.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mBEA7PKDmiY&quot;&gt;Statistical Rethinking 2023 - 05 - Elemental Confounds&lt;/a&gt; — Richard McElreath, English. Watch why adding one variable changes the meaning of the other variable’s coefficient, supporting the part on conditional effects.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Covariance and the regression line&lt;/td&gt;
          &lt;td&gt;Regression&lt;/td&gt;
          &lt;td&gt;Probability and Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=ualmyZiPs9w) — Khan Academy, English. Watch how covariance enters the regression line, used where the lesson explains that a predictor does not stand alone.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;In the house price prediction problem, why is using only floor area usually not enough?&lt;/li&gt;
  &lt;li&gt;What does “holding the other variables fixed” mean in the example of salary by experience and education?&lt;/li&gt;
  &lt;li&gt;Think of a real problem in your field that needs at least three predictors.&lt;/li&gt;
  &lt;li&gt;When can a coefficient in simple regression differ quite a lot from the corresponding coefficient in multiple regression?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;McElreath, R. (2020).&lt;/strong&gt; &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd Edition). CRC Press.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Hill, J., &amp;amp; Vehtari, A. (2020).&lt;/strong&gt; &lt;em&gt;Regression and Other Stories&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter05/05_02_confounding_dags/&quot;&gt;5.2 Confounding and DAGs&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 4.6: Advanced Case Study - Model Checking & Prediction on a Complex Dataset</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_06_case_study_complex_dataset/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_06_case_study_complex_dataset</id>
   <content type="html">&lt;p&gt;If &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; was a gentle warm-up, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; dataset is a full-contact stress test. Here, price does not rise linearly with carat weight—doubling a diamond from 1 carat to 2 carats more than &lt;em&gt;triples&lt;/em&gt; its price, variance explodes at higher weights, and categorical attributes like cut and clarity layer nonlinearity on top of skewness. A naive linear baseline collapses across every single diagnostic check, making &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; the ideal proving ground for &lt;strong&gt;multi-level PPCs&lt;/strong&gt; and &lt;strong&gt;log-log generative revisions&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lesson Roadmap:&lt;/strong&gt; Why &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; breaks naive linear regression → Key ideas (Power-law scaling &amp;amp; log-log models, Conditional PPCs, Decision-grade uncertainty) → Hand-worked power-law calculation for 0.5, 1.0, and 2.0 carat diamonds → Full complex case study and exercises.&lt;/p&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to grasp how to run a full Bayesian workflow on data with complex structure, where “being able to fit the model” is only a necessary condition and never a sufficient one. The focus of the lesson is not on being able to write one more regression equation, but on reasoning ability: from diagnosing a deviation, identifying its form, to proposing model revisions that fix the real cause instead of fixing by technical intuition.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Opening example.&lt;/strong&gt; In the diamonds data, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; are very highly correlated, but a simple linear model can still fail badly in the tail of the price distribution, that is, right in the “safe” region but wrong in the region of greatest economic value.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Why is a very nice summary metric such as a correlation of 0.9+ still not enough to conclude that the model is trustworthy for real-world prediction?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-stress-testing-bayesian-regression-on-complex-data&quot;&gt;Key ideas: Stress-Testing Bayesian Regression on Complex Data&lt;/h2&gt;

&lt;h3 id=&quot;1-nonlinearity-and-power-law-scaling-loglog-models&quot;&gt;1. Nonlinearity and Power-Law Scaling (Log–Log Models)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Modeling \(\log(y_i) \sim \mathrm{Normal}(\alpha + \beta \log(x_i), \sigma)\), which corresponds on the original scale to a multiplicative power law \(y_i = e^{\alpha} x_i^{\beta} \cdot e^{\varepsilon_i}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Simultaneously curing three classic real-data pathologies—convex curvature, strictly positive outcomes (\(y &amp;gt; 0\)), and multiplicative heteroscedasticity (error proportional to price).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-multi-level-posterior-predictive-checks-global-vs-conditional&quot;&gt;2. Multi-Level Posterior Predictive Checks (Global vs. Conditional)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Checking not only the overall marginal histogram of \(y^{\text{rep}}\), but slicing PPCs by subgroups (e.g., low-carat vs. high-carat, or by diamond clarity).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Catching “canceling errors” where a model looks fine globally only because over-prediction in one carat bracket masks under-prediction in another.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-back-transformation-bias-on-the-log-scale&quot;&gt;3. Back-Transformation Bias on the Log Scale&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Remembering that if \(\log(y) \sim \mathrm{Normal}(\mu, \sigma^2)\), the &lt;strong&gt;median&lt;/strong&gt; on the original scale is \(e^{\mu}\), while the &lt;strong&gt;mean&lt;/strong&gt; is \(e^{\mu + \sigma^2/2}\) (Jensen’s inequality).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Avoiding systematic under-pricing in revenue/cost decisions when converting log-scale predictions back to dollars.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;explanation-hand-checking-power-law-pricing--jensens-correction&quot;&gt;Explanation: Hand-Checking Power-Law Pricing &amp;amp; Jensen’s Correction&lt;/h2&gt;

&lt;p&gt;Suppose a Bayesian log–log model for diamond price yields \(\log(\text{price}) \sim \mathrm{Normal}(8.45 + 1.68\log(\text{carat}),\; 0.25^2)\). Let us compute exact dollar predictions by hand (using \(e^{8.45} \approx 4{,}675\) and \(e^{\sigma^2/2} = e^{0.0625/2} \approx 1.0317\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Carat \(x\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(x^{1.68}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Predicted &lt;strong&gt;Median&lt;/strong&gt; Price \(4{,}675\,x^{1.68}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Predicted &lt;strong&gt;Mean&lt;/strong&gt; Price (\(\times 1.0317\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Multiplicative 95% PI (\(\div 1.63\) to \(\times 1.63\))&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;0.5 ct&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.312\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\$1{,}459\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\$1{,}505\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([\$895,\; \$2{,}380]\) (always positive!)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;1.0 ct&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1.000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\$4{,}675\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\$4{,}823\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([\$2{,}868,\; \$7{,}620]\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;2.0 ct&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(3.204\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\$14{,}980\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\$15{,}455\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([\$9{,}190,\; \$24{,}417]\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Look at the elasticity exponent \(\beta = 1.68 &amp;gt; 1\): doubling carat weight from \(1.0\) to \(2.0\) multiplies price by \(2^{1.68} \approx \mathbf{3.20\times}\), and the 95% interval naturally scales proportionally to price (\(e^{1.96 \times 0.25} \approx 1.63\)) instead of slapping a flat dollar band on both $1,500 and $15,000 stones!&lt;/p&gt;

&lt;h2 id=&quot;1-data-context-why-diamonds-is-a-hard-test&quot;&gt;1. Data context: why &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; is a hard test&lt;/h2&gt;

&lt;p&gt;We use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; dataset (seaborn), with the response variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; and many variables describing both geometric size and perceived quality such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;color&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clarity&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;depth&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;table&lt;/code&gt;. What gives this dataset high pedagogical value is that it forces us to face three layers of complexity at once: a strong relationship that is not homogeneous across the whole predictor domain, a group structure with real meaning, and the tail behavior of the response that directly affects the quality of decision-making.&lt;/p&gt;

&lt;h3 id=&quot;11-excerpt-of-the-observed-data&quot;&gt;1.1. Excerpt of the observed data&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;carat&lt;/th&gt;
      &lt;th&gt;cut&lt;/th&gt;
      &lt;th&gt;color&lt;/th&gt;
      &lt;th&gt;clarity&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;depth&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;table&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;price&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;x&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;y&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;z&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.23&lt;/td&gt;
      &lt;td&gt;Ideal&lt;/td&gt;
      &lt;td&gt;E&lt;/td&gt;
      &lt;td&gt;SI2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;61.5&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;55.0&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;326&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.95&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.98&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.43&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.21&lt;/td&gt;
      &lt;td&gt;Premium&lt;/td&gt;
      &lt;td&gt;E&lt;/td&gt;
      &lt;td&gt;SI1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;59.8&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;61.0&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;326&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.89&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.84&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.31&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.23&lt;/td&gt;
      &lt;td&gt;Good&lt;/td&gt;
      &lt;td&gt;E&lt;/td&gt;
      &lt;td&gt;VS1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;56.9&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;65.0&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;327&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.05&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.07&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.31&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.29&lt;/td&gt;
      &lt;td&gt;Premium&lt;/td&gt;
      &lt;td&gt;I&lt;/td&gt;
      &lt;td&gt;VS2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;62.4&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;58.0&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;334&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.20&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.23&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.63&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.31&lt;/td&gt;
      &lt;td&gt;Good&lt;/td&gt;
      &lt;td&gt;J&lt;/td&gt;
      &lt;td&gt;SI2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;63.3&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;58.0&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;335&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.34&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4.35&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.75&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;12-quantitative-summary-to-lay-the-groundwork-for-the-argument&quot;&gt;1.2. Quantitative summary to lay the groundwork for the argument&lt;/h3&gt;

&lt;p&gt;With &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n = 53,940&lt;/code&gt;, the variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; has a mean of approximately 0.798 and a median of about 0.70, while &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; has a mean of about 3932.8 but a median of only about 2401, showing that the price distribution is considerably right-skewed. The Pearson correlation between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; is about 0.922, i.e. extremely strong at the overall level; yet the proportion of observations falling in the region &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price &amp;gt; 15000&lt;/code&gt; is still only about 3.07%, and this small region is exactly where every model deviation becomes the most costly if the problem is used for high-end pricing.&lt;/p&gt;

&lt;h2 id=&quot;2-from-numbers-to-argument-we-must-prove-with-formulas&quot;&gt;2. From numbers to argument: we must prove with formulas&lt;/h2&gt;

&lt;p&gt;A serious analysis is not allowed to stop at wording like “it seems” or “it looks like”. Every key conclusion needs a corresponding statistical object and measurement.&lt;/p&gt;

&lt;p&gt;The sample correlation coefficient between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; is defined by&lt;/p&gt;

\[r_{xy}=\frac{\sum_{i=1}^{n}(x_i-\bar x)(y_i-\bar y)}{\sqrt{\sum_{i=1}^{n}(x_i-\bar x)^2}\sqrt{\sum_{i=1}^{n}(y_i-\bar y)^2}},\]

&lt;p&gt;and gives a value of about 0.922. This number only lets us state that the fluctuations of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; move strongly in phase in the global linear sense; it in no way guarantees that the residuals are random around 0, in no way guarantees homogeneous error variance, and in no way vouches that the model predicts well in the right tail. In other words, a high correlation is evidence of signal, not evidence of the correctness of the structure of the data-generating model.&lt;/p&gt;

&lt;p&gt;Similarly, the statement “the right tail is rare” must also have a clear definition:&lt;/p&gt;

\[\hat p_{\text{price}&amp;gt;15000}=\frac{1}{n}\sum_{i=1}^{n}\mathbf 1(y_i&amp;gt;15000)\approx 0.0307.\]

&lt;p&gt;Although this proportion is only around 3%, the tail region has outsized economic weight in many practical problems; therefore, a model that is right in the center but wrong in the tail is still a high-risk model if the application goal is pricing, premium portfolio control, or evaluating extreme scenarios.&lt;/p&gt;

&lt;p&gt;Finally, to check the assumption of homogeneous variance, we can use the directional indicator&lt;/p&gt;

\[\operatorname{corr}(\lvert e_i \rvert,x_i), \qquad e_i=y_i-\hat y_i,\]

&lt;p&gt;because when the residual magnitude moves together with the predictor, the assumption of “one common noise level for the whole domain” becomes hard to defend empirically.&lt;/p&gt;

&lt;h2 id=&quot;3-the-baseline-model-necessary-as-a-baseline-but-cannot-be-the-destination&quot;&gt;3. The baseline model: necessary as a baseline, but cannot be the destination&lt;/h2&gt;

&lt;p&gt;We start with the baseline Gaussian linear model&lt;/p&gt;

\[\text{price}_i \sim \mathcal N(\mu_i,\sigma), \qquad \mu_i=\alpha+\beta\,\text{carat}_i,\]

&lt;p&gt;&lt;strong&gt;not because we believe the real world is that simple, but because every later improvement needs a benchmark to compare against. The baseline is an instrument for measuring progress, not a declaration of truth&lt;/strong&gt;. On &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt;, the baseline usually reproduces the average trend fairly well, but easily reveals three limitations: the error width grows with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, the right-tail behavior of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; is squeezed thin, and structural differences by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clarity&lt;/code&gt; are not described.&lt;/p&gt;

&lt;h2 id=&quot;4-multi-level-posterior-predictive-checks-from-global-to-conditional&quot;&gt;4. Multi-level posterior predictive checks: from global to conditional&lt;/h2&gt;

&lt;p&gt;In complex data, a single PPC is almost always insufficient. We need a structured series of checks, going from broad questions to narrow ones, to know where the model is right and where it is wrong.&lt;/p&gt;

&lt;p&gt;At the global level, we compare the observed distribution with the posterior predictive distribution to see whether the model preserves the central location, spread and tail thickness simultaneously; this is the step that quickly eliminates grossly wrong models.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_observed_vs_predicted.png&quot; alt=&quot;Comparing observed data and the posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;At the target-statistic level, instead of vaguely saying “it looks similar”, we force the model to answer with specific quantities:&lt;/p&gt;

\[T_1(y)=\bar y,\quad T_2(y)=\operatorname{Var}(y),\quad T_3(y)=Q_{0.95}(y),\quad T_4(y)=\mathbf 1(y&amp;gt;15000).\]

&lt;p&gt;If the model matches \(T_1\) well but deviates considerably at \(T_3\) or \(T_4\), the valid conclusion cannot be “the model is good”, but must be “the model is good in the center, weak in the tail”; this distinction is decisive when the analysis goal directly concerns high-value risk.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_test_stat_mean.png&quot; alt=&quot;PPC cho mean&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_variance_check.png&quot; alt=&quot;PPC cho variance&quot; /&gt;&lt;/p&gt;

&lt;p&gt;At the level conditional on the predictor, we check each &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; band instead of mixing everything into one common distribution. The idea is that the same model can be right in the central region but systematically wrong in the large-&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; region, where the range of price fluctuation is considerably wider. Quantitatively, we can track&lt;/p&gt;

\[T_{\text{bin},k}(y)=\operatorname{Var}(y\mid x\in B_k),\qquad T^{(0.95)}_{\text{bin},k}(y)=Q_{0.95}(y\mid x\in B_k),\]

&lt;p&gt;and compare the observed value with the posterior predictive distribution of each bin.&lt;/p&gt;

&lt;p&gt;At the quality-group level, data like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; forces us to check the ability to reproduce differences between the groups &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clarity&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;color&lt;/code&gt;. If the model only uses &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, failing to reproduce the group means&lt;/p&gt;

\[T_g(y)=\bar y_g\]

&lt;p&gt;is not a “small error”, but evidence that the generative story is missing an important structural mechanism.&lt;/p&gt;

&lt;h2 id=&quot;5-residual-analysis-where-the-model-is-questioned-most-severely&quot;&gt;5. Residual analysis: where the model is questioned most severely&lt;/h2&gt;

&lt;p&gt;If the PPC gives us the picture at the distribution level, residual analysis gives us a microscope at the mechanism level. The central question is not “are the residuals small” but “do the residuals still carry structured information”. When the residuals still have structure, the model has not yet learned all of the data-generating law.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_scatter.png&quot; alt=&quot;Signs of heteroskedasticity on the scatter plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_residuals.png&quot; alt=&quot;Residuals vs fitted: fan shape&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonnormal_qq.png&quot; alt=&quot;Q-Q plot when the residual tails deviate&quot; /&gt;&lt;/p&gt;

&lt;p&gt;In the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; case, a fan shape in residual-vs-fitted usually strongly suggests that uncertainty grows with price level or size, while the deviation on the Q-Q plot shows that a simple Normal assumption may not be flexible enough to describe the tail. The direct consequence is that the prediction interval in the high-&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; region is easily artificially narrow if we insist on keeping the baseline model.&lt;/p&gt;

&lt;h2 id=&quot;6-prediction-for-decisions-distinguishing-the-two-kinds-of-uncertainty-correctly&quot;&gt;6. Prediction for decisions: distinguishing the two kinds of uncertainty correctly&lt;/h2&gt;

&lt;p&gt;A point often overlooked in practical reports is the difference between the uncertainty of the conditional mean and the uncertainty of a new observation. These two objects are described by&lt;/p&gt;

\[p(\mu_*\mid y,x_*) \quad \text{and} \quad p(\tilde y_*\mid y,x_*),\]

&lt;p&gt;where the second distribution is always wider because it includes the noise of the new observation. If we use the interval of \(p(\mu_*\mid y,x_*)\) to make a statement about one specific diamond, we have created false confidence by definition.&lt;/p&gt;

&lt;p&gt;For prediction problems, an important operational indicator is out-of-sample coverage:&lt;/p&gt;

\[\text{Coverage}_{90\%}=\frac{1}{m}\sum_{j=1}^{m}\mathbf 1\{y_j^{\text{test}}\in \text{PI}_{90\%}(x_j)\}.\]

&lt;p&gt;When coverage drops clearly in the large-&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; region, that is empirical evidence that the model is not yet suitable for real-world use in the high-price segment, regardless of how nice the overall metrics may be.&lt;/p&gt;

&lt;h2 id=&quot;7-model-revision-from-symptom-to-intervention&quot;&gt;7. Model revision: from symptom to intervention&lt;/h2&gt;

&lt;p&gt;A mature workflow does not stop at diagnosis; it must turn diagnosis into an intervention with a mechanism. In other words, each model modification is considered valid only when we can answer three questions at once: which symptom of the data is being addressed, which mathematical component of the model is changed to address that symptom, and which post-hoc evidence allows us to conclude that the change truly takes effect rather than merely making the model look better in form.&lt;/p&gt;

&lt;p&gt;In the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; case, three clusters of symptoms usually appear together: the right tail of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; is thicker than the simple Gaussian predicts, the residual magnitude grows with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, and there is conditional deviation by quality group. From there, the three intervention directions with the clearest theoretical basis are transforming the response scale, loosening the linear structure of the mean function, and bringing group effects into the generative story.&lt;/p&gt;

&lt;h3 id=&quot;71-intervention-1-log-transform-to-handle-the-right-tail-and-multiplicative-noise&quot;&gt;7.1. Intervention 1: log transform to handle the right tail and multiplicative noise&lt;/h3&gt;

&lt;p&gt;When the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; distribution is strongly right-skewed, the assumption of additive noise on the original scale is often no longer appropriate. A more mechanism-rich way to put it is to view the error as multiplicative, i.e. relative fluctuation is more stable than absolute fluctuation. Then the model&lt;/p&gt;

\[\log(\text{price}_i) \sim \mathcal N(\mu_i,\sigma),\]

&lt;p&gt;is not just a technical trick, but a statement about the data-generating mechanism: percentage uncertainty is more reasonable than absolute uncertainty across very different price levels. The practical effect expected after this intervention is a more balanced residual distribution, a lower heteroskedasticity indicator, and a prediction interval in the large-&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; region that is less artificially narrow.&lt;/p&gt;

&lt;p&gt;However, the log transform brings the requirement of correct interpretation when returning to the original scale. If the posterior on the log scale has conditional mean \(\mu_*\) and standard deviation \(\sigma_*\), the expected value on the price scale is not simply \(\exp(\mu_*)\) but&lt;/p&gt;

\[\mathbb E[\text{price}_*\mid y,x_*]=\exp\!\left(\mu_*+\frac{\sigma_*^2}{2}\right),\]

&lt;p&gt;so prediction reports need to be consistent with the transformation to avoid systematic underestimation on the original scale.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_46_intervention_log_transform.png&quot; alt=&quot;Illustration of intervention 1: the log transform reduces heteroskedasticity and improves coverage in the high-carat region&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;72-intervention-2-replace-rigid-linearity-with-controlled-nonlinear-structure&quot;&gt;7.2. Intervention 2: replace rigid linearity with controlled nonlinear structure&lt;/h3&gt;

&lt;p&gt;If the residuals show leftover curvature, the problem is not in the noise but in the form of the mean function. Then the right change is to loosen the model&lt;/p&gt;

\[\mu_i=\alpha+\beta\,\text{carat}_i\]

&lt;p&gt;into a more flexible function, for example&lt;/p&gt;

\[\mu_i=\alpha+f(\text{carat}_i), \qquad f(\cdot)=\sum_{k=1}^{K} w_k B_k(\cdot),\]

&lt;p&gt;where \(B_k\) are basis functions (spline/piecewise basis) and the prior on \(w_k\) plays the role of regularization to avoid overfitting. The key point is that “controlled nonlinearity” is fundamentally different from adding arbitrary polynomials: we increase the representational capacity exactly for the curvature the residuals detect, but still maintain Bayesian discipline through the prior to preserve generalization.&lt;/p&gt;

&lt;p&gt;The expected result after the intervention is that the posterior mean line hugs the data more closely at both the low and high ends of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, while the conditional PPC in each predictor bin improves in step rather than only in the center.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_46_intervention_nonlinear.png&quot; alt=&quot;Illustration of intervention 2: a nonlinear model captures the curvature of the carat-price relationship better than a linear one&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;73-intervention-3-bring-group-structure-into-the-generative-story-via-partial-pooling&quot;&gt;7.3. Intervention 3: bring group structure into the generative story via partial pooling&lt;/h3&gt;

&lt;p&gt;When the data contains grouping variables such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;color&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clarity&lt;/code&gt;, a model with one continuous variable can hardly reproduce the structural differences between quality segments. Instead of adding independent dummy variables in a purely technical way, the more natural Bayesian approach is a hierarchical model, for example with group-wise intercepts:&lt;/p&gt;

\[\mu_i=\alpha_{g(i)}+f(\text{carat}_i), \qquad \alpha_g\sim\mathcal N(\alpha_0,\tau_\alpha).\]

&lt;p&gt;Partial pooling reconciles two extremes: it does not force all groups to be identical (complete pooling), but also does not leave each group excessively free (no pooling). A very important methodological consequence is that groups with little data are “shrunk” toward the center in a principled way, thereby reducing estimation variance and increasing out-of-sample prediction stability.&lt;/p&gt;

&lt;p&gt;If, after introducing group effects, the group-wise PPC is still unsatisfactory, that is a signal that the current group structure is not enough: group-specific slopes, interactions between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; and quality, or modeling errors that differ by segment may be needed.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_46_intervention_group_effects.png&quot; alt=&quot;Illustration of intervention 3: adding group structure makes calibration by cut closer to the observed data&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;experiment-partial-pooling-shrinks-the-groups-toward-the-overall-mean&quot;&gt;Experiment: partial pooling shrinks the groups toward the overall mean&lt;/h3&gt;

&lt;p&gt;Increase τ from complete pooling to no pooling; compare with the posterior distribution of τ.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;pooling-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;74-evaluation-protocol-after-each-intervention-when-we-may-say-it-is-better&quot;&gt;7.4. Evaluation protocol after each intervention: when we may say “it is better”&lt;/h3&gt;

&lt;p&gt;A modification should only be accepted when it passes post-hoc evaluation under the same set of criteria, including global PPC, tail PPC, PPC conditional on predictor bins, residual diagnostics, and out-of-sample coverage. In principle, the new model needs to satisfy two conditions at once: (i) reduce the deviation in the target symptom, and (ii) not create considerable deterioration in regions that were previously fine. If it only improves one plot but worsens coverage in the decision region, that intervention cannot yet be considered a success.&lt;/p&gt;

&lt;p&gt;The recommended intervention order for this case is to go from the least invasive change to the deeper structural change: first stabilize the scale with a log transform, then handle curvature with a regularized nonlinear function, and only finally expand to hierarchical group effects. This order helps us preserve the ability to trace causes, because each step has a clear hypothesis and a corresponding diagnostic signal to verify it.&lt;/p&gt;

&lt;h3 id=&quot;75-concrete-illustrative-results-for-the-intervention-steps&quot;&gt;7.5. Concrete illustrative results for the intervention steps&lt;/h3&gt;

&lt;p&gt;To avoid the feeling of “generic recommendations”, we summarize one directional experiment round on this very dataset (80/20 train/test split, using the same set of evaluation criteria) to illustrate the direction in which results move after each intervention.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Illustrative model&lt;/th&gt;
      &lt;th&gt;Signal to fix&lt;/th&gt;
      &lt;th&gt;Observed result&lt;/th&gt;
      &lt;th&gt;Interpretation&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Baseline: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price ~ carat&lt;/code&gt; (Gaussian)&lt;/td&gt;
      &lt;td&gt;Heteroskedasticity&lt;/td&gt;
      &lt;td&gt;\(\operatorname{corr}(\lvert e \rvert,\text{carat})\approx 0.579\)&lt;/td&gt;
      &lt;td&gt;The error magnitude grows strongly with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, so the homogeneous noise assumption is weak.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Baseline: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price ~ carat&lt;/code&gt; (Gaussian)&lt;/td&gt;
      &lt;td&gt;Interval reliability in the high-value region&lt;/td&gt;
      &lt;td&gt;Global 90% coverage about 0.921, but in the high &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; group only about 0.728&lt;/td&gt;
      &lt;td&gt;The interval looks “wide enough” globally but seriously lacks coverage exactly in the most important region.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Intervention 1: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(price) ~ carat&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Stabilizing variance across the predictor&lt;/td&gt;
      &lt;td&gt;$\operatorname{corr}(\lvert e_{\log} \rvert,\text{carat})\approx 0.269$&lt;/td&gt;
      &lt;td&gt;The heteroskedasticity indicator drops markedly, consistent with the multiplicative noise hypothesis.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Intervention 1: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(price) ~ carat&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Coverage in the high &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; region&lt;/td&gt;
      &lt;td&gt;90% coverage in the high &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; region rises to about 0.850&lt;/td&gt;
      &lt;td&gt;Prediction in the large segment is considerably improved compared with the baseline.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Intervention 1 (tail check)&lt;/td&gt;
      &lt;td&gt;Tail calibration&lt;/td&gt;
      &lt;td&gt;The posterior predictive \(Q_{0.95}\) tends to exceed the observed level&lt;/td&gt;
      &lt;td&gt;An important lesson: the log transform can fix the lack of coverage in the high region but also risks over-correcting in the tail, so a separate tail PPC is still needed.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Intervention 3 in the non-hierarchical style (crude fixed effects)&lt;/td&gt;
      &lt;td&gt;Differences by quality group&lt;/td&gt;
      &lt;td&gt;Some rare groups have abnormally jumping mean predictions&lt;/td&gt;
      &lt;td&gt;This demonstrates why &lt;strong&gt;partial pooling&lt;/strong&gt; is needed instead of adding groups in a completely free style.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The results above show the core message of step 7: each intervention has a measurable effect, but the effect is not monotone in the sense of “the more complex the better”. The right intervention is the one that reduces the target symptom without creating new distortion at another level of checking; therefore, the evaluation process after revising the model is mandatory, not an add-on.&lt;/p&gt;

&lt;h2 id=&quot;8-methodological-conclusions-from-lesson-46&quot;&gt;8. Methodological conclusions from lesson 4.6&lt;/h2&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; case shows a truth running through Bayesian modeling: a nice metric at the overall level can coexist with a serious deviation at the conditional level, and without structured model checking, we easily confuse “the model has signal” with “the model is trustworthy for decisions”. Therefore, the right cycle is never to fit and then conclude, but always to fit, check at multiple levels, interpret deviations in the language of mechanisms, and only then revise the model and evaluate again.&lt;/p&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EkAQAi3a4js&quot;&gt;Multiple Regression, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch that a coefficient in multiple regression only has meaning when the other variables are kept in the model, exactly the kind of many-descriptor data in the case study.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yDPJnV9vcHs&quot;&gt;What is a posterior predictive check and why is it useful?&lt;/a&gt; — Ben Lambert, English. Watch the posterior predictive check, supporting the lesson’s argument that being able to fit a model is not a sufficient condition.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Oriol Abril-Pla - Model criticism with ArviZ&lt;/td&gt;
          &lt;td&gt;Pydata London 26](https://www.youtube.com/watch?v=HHPAzNan7Uw) — PyData, English. Watch model criticism with ArviZ, used for the part of the lesson that turns sampling diagnostics and PPC into a workflow.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;If a model reproduces \(\bar y\) well but fails badly at \(Q_{0.95}(y)\), what would you conclude about using the model for the high-end segment?&lt;/li&gt;
  &lt;li&gt;In a prediction context, why is an error in the right tail usually more dangerous than an error in the central region?&lt;/li&gt;
  &lt;li&gt;When &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt; has been added but the group-wise PPC is still unsatisfactory, which structural assumption would you check first?&lt;/li&gt;
  &lt;li&gt;Why is out-of-sample coverage per &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; band more useful than coverage pooled over all the data?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), chapters on model checking.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Regression and Other Stories&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), chapters on posterior predictive checks.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;End of Chapter 4. Next lesson: &lt;a href=&quot;/contents/en/chapter05/&quot;&gt;Chapter 5 - Multiple Predictors and Causal Thinking&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 4.5: Case Study Model Checking & Prediction - A Full Workflow on One Dataset</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_05_case_study_model_checking_prediction/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_05_case_study_model_checking_prediction</id>
   <content type="html">&lt;p&gt;Theory only clicks when you get your hands dirty on a real dataset that misbehaves. Restaurant tipping (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;) looks deceptively simple at first glance: larger bills lead to larger tips, so a straight line ought to do the job. Yet the moment we run posterior predictive checks and residual plots on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;, a glaring crack opens up: tips on a $10 lunch barely vary by a dollar, whereas tips on a $50 dinner swing wildly—and a constant-variance Normal model even predicts &lt;strong&gt;negative tips&lt;/strong&gt;! Walking through this full workflow shows how Bayesian diagnostics turn a failed check into a principled model upgrade.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lesson Roadmap:&lt;/strong&gt; Putting the full workflow on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; → Key ideas (End-to-end Bayesian workflow, Homoscedasticity vs. Heteroscedasticity, Targeted model revision) → Hand-worked comparison of constant-\(\sigma\) vs. bill-scaled \(\sigma(x)\) intervals → Full 6-step case study and exercises.&lt;/p&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to be able to carry out a full, in-depth workflow on a concrete dataset: build a Bayesian model, assess the quality of sampling, check the model with posterior predictive checks (PPC), analyze residuals, report predictions with the right kind of uncertainty, and propose model revisions based on evidence.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; You predict the tip amount from the total bill in restaurant data. A linear model may give a very nice slope, but the practical question is: does that model really generate data that looks like reality and make trustworthy predictions for new customers?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If the posterior slope is clearly positive but the PPC fails in the large-bill region, what should you trust?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-executing-the-full-bayesian-workflow-on-real-data&quot;&gt;Key ideas: Executing the Full Bayesian Workflow on Real Data&lt;/h2&gt;

&lt;h3 id=&quot;1-iterative-model-building-boxs-loop&quot;&gt;1. Iterative Model Building (Box’s Loop)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; The disciplined cycle: &lt;em&gt;Specify generative baseline → Check sampler diagnostics → Run PPC &amp;amp; residual plots → Diagnose failure mode → Revise model → Re-check&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Treating every model as a provisional hypothesis to be stress-tested against real data rather than a one-shot fit.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-homoscedasticity-vs-heteroscedasticity&quot;&gt;2. Homoscedasticity vs. Heteroscedasticity&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Whether observation noise \(\sigma\) stays constant across all predictor values (\(\sigma_i = \sigma\)) or grows systematically with the predictor (\(\sigma_i = \gamma_0 + \gamma_1 x_i\) or log-scale modeling).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Why fan-shaped residual plots invalidate prediction intervals even when the mean regression line \(\alpha + \beta x\) looks accurate.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-domain-constraints-on-predictive-distributions&quot;&gt;3. Domain Constraints on Predictive Distributions&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Checking whether \(p(y^{\text{rep}} \mid y)\) respects physical boundaries of the outcome (such as tips being strictly non-negative, \(y \ge 0\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Selecting likelihoods or link/log transforms so predictions remain coherent at both low and high extremes of the covariate.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;explanation-catching-heteroscedasticity-by-hand-on-tips&quot;&gt;Explanation: Catching Heteroscedasticity by Hand on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;Suppose a baseline homoscedastic model on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; gives \(\mu(x) = 0.80 + 0.14 x\) with constant noise \(\sigma = 1.00\) (in USD). Compare its 95% prediction intervals (\(\mu \pm 1.96\sigma\)) against a heteroscedastic revision where \(\sigma(x) = 0.10 + 0.05 x\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Bill \(x\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Mean tip \(\mu(x)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Baseline 95% PI (\(\sigma = 1.00\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Revised 95% PI (\(\sigma(x) = 0.10 + 0.05x\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;What the check reveals&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;$10&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\$2.20\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([0.24,\; 4.16]\) (at $5: \([-0.46,\; 3.46]\)!)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\sigma = 0.60 \implies [1.02,\; 3.38]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Baseline leaks negative tips on small bills!&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;$50&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\$7.80\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([5.84,\; 9.76]\) (width \(\$3.92\))&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\sigma = 2.60 \implies [2.70,\; 12.90]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Baseline is far too narrow for big-table variance!&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Notice the crisp diagnostic signature: a single constant \(\sigma\) simultaneously &lt;strong&gt;over-estimates&lt;/strong&gt; uncertainty for small bills and &lt;strong&gt;under-estimates&lt;/strong&gt; uncertainty for large bills. Letting \(\sigma\) scale with \(x\) (or modeling \(\log(\text{tip})\)) fixes both ends in one targeted move.&lt;/p&gt;

&lt;h2 id=&quot;1-the-concrete-dataset-tips-seaborn&quot;&gt;1. The concrete dataset: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; (seaborn)&lt;/h2&gt;

&lt;p&gt;We use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; dataset, in which:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;: the total bill,&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt;: the tip amount,&lt;/li&gt;
  &lt;li&gt;each row is one table of diners.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Main goal: model and predict &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt; from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Secondary goal: check whether a baseline Gaussian linear model is good enough, instead of trusting the posterior slope by default.&lt;/p&gt;

&lt;p&gt;The reason this dataset suits lesson 4.5 is that it is small enough to read intuitively, yet realistic enough to show model checking problems: possibly mild nonlinearity, variance that grows with the bill level, and tail behavior that is not entirely ideal for a simple Normal.&lt;/p&gt;

&lt;h3 id=&quot;11-a-quick-look-at-part-of-the-data&quot;&gt;1.1. A quick look at part of the data&lt;/h3&gt;

&lt;p&gt;The table below shows the first 5 rows of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; dataset so you get an intuitive feel for the data:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;total_bill&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;tip&lt;/th&gt;
      &lt;th&gt;sex&lt;/th&gt;
      &lt;th&gt;smoker&lt;/th&gt;
      &lt;th&gt;day&lt;/th&gt;
      &lt;th&gt;time&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;size&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;16.99&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1.01&lt;/td&gt;
      &lt;td&gt;Female&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Sun&lt;/td&gt;
      &lt;td&gt;Dinner&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;10.34&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1.66&lt;/td&gt;
      &lt;td&gt;Male&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Sun&lt;/td&gt;
      &lt;td&gt;Dinner&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;21.01&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.50&lt;/td&gt;
      &lt;td&gt;Male&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Sun&lt;/td&gt;
      &lt;td&gt;Dinner&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;23.68&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.31&lt;/td&gt;
      &lt;td&gt;Male&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Sun&lt;/td&gt;
      &lt;td&gt;Dinner&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;24.59&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3.61&lt;/td&gt;
      &lt;td&gt;Female&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Sun&lt;/td&gt;
      &lt;td&gt;Dinner&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;12-summarizing-the-data-before-modeling&quot;&gt;1.2. Summarizing the data before modeling&lt;/h3&gt;

&lt;p&gt;Over all 244 observations:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;: mean about 19.79, standard deviation about 8.90, min 3.07, max 50.81,&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt;: mean about 3.00, standard deviation about 1.38, min 1.00, max 10.00,&lt;/li&gt;
  &lt;li&gt;the linear correlation between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt; is about 0.676 (positive, moderate to fairly strong).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;An important point for the later checking step:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;only about 2.9% of observations have &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip &amp;gt; 6&lt;/code&gt;,&lt;/li&gt;
  &lt;li&gt;but this is exactly the region that determines tail behavior, where a Gaussian linear model is often prone to error.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Clarifying this argument:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Why does 2.9% still matter?&lt;/strong&gt; In prediction problems, errors in the tail are often tied to high-impact cases (large bills, large tips). Even though rare, these points determine the quality of prediction in risk or high-value scenarios.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why is a linear Gaussian model prone to error in the tail?&lt;/strong&gt; The baseline model assumes symmetric errors and a single common noise \(\sigma\) for every level of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;. In reality, service data often has variance that grows with the bill level, so the tail can be thicker than a simple Normal predicts.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Consequence of ignoring the tail region:&lt;/strong&gt; the model may still fit the mean well but underestimate the probability of very high tips, making the prediction interval in the large-bill region artificially narrow.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The right check in PPC:&lt;/strong&gt; besides mean/variance, you should also check tail statistics, for example&lt;/li&gt;
&lt;/ul&gt;

\[T(y)=\mathbf 1(y&amp;gt;6),\quad T(y)=\max(y),\quad T(y)=Q_{0.95}(y).\]

&lt;p&gt;If \(T(y_{obs})\) lies at the edge of or outside the distribution of \(T(y_{rep})\), that is a sign the model has not reproduced the tail behavior.&lt;/p&gt;

&lt;h3 id=&quot;13-interpreting-the-conclusions-with-formulas&quot;&gt;1.3. Interpreting the conclusions with formulas&lt;/h3&gt;

&lt;p&gt;To avoid the “look at a plot and guess” style of conclusion, we write down the formulas behind the important statements.&lt;/p&gt;

&lt;p&gt;The sample linear correlation coefficient (Pearson) between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt; is computed by:&lt;/p&gt;

\[r_{xy}=\frac{\sum_{i=1}^{n}(x_i-\bar x)(y_i-\bar y)}{\sqrt{\sum_{i=1}^{n}(x_i-\bar x)^2}\sqrt{\sum_{i=1}^{n}(y_i-\bar y)^2}}.\]

&lt;p&gt;For this dataset, \(r_{xy}\approx 0.676\), so we have two separate conclusions:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;positive sign: as the bill increases, the tip tends to increase,&lt;/li&gt;
  &lt;li&gt;magnitude of about 0.68: the linear relationship is moderate to fairly strong, not weak but not nearly perfect either.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The proportion in the right tail (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip &amp;gt; 6&lt;/code&gt;) is computed by:&lt;/p&gt;

\[\hat p_{\text{tip}&amp;gt;6}=\frac{1}{n}\sum_{i=1}^{n}\mathbf 1(y_i&amp;gt;6),\]

&lt;p&gt;and gives a value of about 0.029 (2.9%). Because this proportion is small, every conclusion about the tail must be checked by PPC instead of only looking at the mean.&lt;/p&gt;

&lt;p&gt;A quick connection for reading the level of linear explanation is:&lt;/p&gt;

\[R^2 \approx r_{xy}^2.\]

&lt;p&gt;Therefore, with \(r_{xy}\approx 0.676\) we get \(R^2\approx 0.46\), meaning the linear model only explains about 46% of the variation of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip&lt;/code&gt;. This is the reason we must continue with model checking and residual analysis.&lt;/p&gt;

&lt;p&gt;Finally, to quickly detect heteroskedasticity, we look at the correlation between the residual magnitude and the predictor:&lt;/p&gt;

\[\operatorname{corr}(|e_i|,x_i), \quad e_i=y_i-\hat y_i.\]

&lt;p&gt;If this indicator is clearly positive, the error magnitude tends to grow with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;, and the assumption of homogeneous errors needs to be reconsidered.&lt;/p&gt;

&lt;h2 id=&quot;2-step-1---write-the-generative-story-and-fit-the-baseline-model&quot;&gt;2. Step 1 - Write the generative story and fit the baseline model&lt;/h2&gt;

&lt;p&gt;The baseline model of the case study:&lt;/p&gt;

\[\text{tip}_i \sim \mathcal{N}(\mu_i, \sigma), \quad \mu_i = \alpha + \beta\,x_i,\]

&lt;p&gt;with \(x_i\) being the standardized &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Interpreting the generative story:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;each table has an expected tip that depends linearly on the bill level,&lt;/li&gt;
  &lt;li&gt;around that expectation, the tip fluctuates with a common noise \(\sigma\),&lt;/li&gt;
  &lt;li&gt;the prior should regularize enough to avoid overfitting in the sparse data region (very large bills).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The linear fit usually gives a clearly positive slope. However, in this lesson we treat that only as a starting point, not the final conclusion.&lt;/p&gt;

&lt;h2 id=&quot;3-step-2---check-sampler-diagnostics-before-talking-about-meaning&quot;&gt;3. Step 2 - Check sampler diagnostics before talking about meaning&lt;/h2&gt;

&lt;p&gt;Before interpreting the slope/intercept, we need to look at:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;whether the trace plot mixes well,&lt;/li&gt;
  &lt;li&gt;whether &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;r_hat&lt;/code&gt; is close to 1,&lt;/li&gt;
  &lt;li&gt;whether ESS is large enough,&lt;/li&gt;
  &lt;li&gt;whether there are warnings about divergences or sampling pathologies.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If the diagnostics are not fine, all conclusions about the posterior and predictions are not yet trustworthy.&lt;/p&gt;

&lt;p&gt;Practical benchmarks to follow:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;r_hat&lt;/code&gt; approaching 1.00 for the main parameters,&lt;/li&gt;
  &lt;li&gt;ESS large enough to estimate tail quantiles stably,&lt;/li&gt;
  &lt;li&gt;no systematic divergences.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The reason to take this step seriously: a good or bad PPC only has meaning once the posterior samples are trustworthy.&lt;/p&gt;

&lt;h2 id=&quot;4-step-3---posterior-predictive-distribution-and-ppc&quot;&gt;4. Step 3 - Posterior predictive distribution and PPC&lt;/h2&gt;

&lt;p&gt;Following lesson 4.4, we use:&lt;/p&gt;

\[p(\tilde y \mid y)=\int p(\tilde y \mid \theta)\,p(\theta\mid y)\,d\theta.\]

&lt;p&gt;In the context of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; dataset, the PPC question is:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;If the baseline model is correct, does the simulated tip data look like the real tip data in both the central region and the tail region?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;41-comparing-the-overall-distribution&quot;&gt;4.1. Comparing the overall distribution&lt;/h3&gt;

&lt;p&gt;Compare the observed &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y_rep&lt;/code&gt; from the posterior predictive:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;whether the histogram/density overlap reasonably well,&lt;/li&gt;
  &lt;li&gt;whether the right tail (very high tips) is underestimated by the model,&lt;/li&gt;
  &lt;li&gt;whether the simulated min/max are reasonable.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_observed_vs_predicted.png&quot; alt=&quot;Figure 2 - Comparing observed and posterior predictive over the whole distribution&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;42-comparing-mean-variance-and-specific-statistics&quot;&gt;4.2. Comparing mean, variance, and specific statistics&lt;/h3&gt;

&lt;p&gt;Compute the statistic on the real data and on each simulated sample:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;mean,&lt;/li&gt;
  &lt;li&gt;variance,&lt;/li&gt;
  &lt;li&gt;the proportion of tips exceeding a threshold (for example &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tip &amp;gt; 6&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If the observed value falls too far at the edge relative to the posterior predictive distribution of the statistic, the model is missing a part of the data structure.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_test_stat_mean.png&quot; alt=&quot;Figure 3 - Checking the mean with the posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_variance_check.png&quot; alt=&quot;Figure 4 - Checking the variance with the posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;In the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; case, the baseline model usually reproduces the mean fairly well but tends to be off in the variance in the large-bill region. This is an early signal of heteroskedasticity.&lt;/p&gt;

&lt;h3 id=&quot;43-comparing-the-x---y-relationship&quot;&gt;4.3. Comparing the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x -&amp;gt; y&lt;/code&gt; relationship&lt;/h3&gt;

&lt;p&gt;For regression, the most important thing is the shape of the relationship:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;plot many regression lines/draws from the posterior predictive over the real scatter,&lt;/li&gt;
  &lt;li&gt;see whether the model predicts too optimistically in the large &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; region,&lt;/li&gt;
  &lt;li&gt;see whether the width of the prediction grows with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is usually where nonlinearity or heteroskedasticity is detected earliest.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_distribution_at_x5.png&quot; alt=&quot;Figure 5 - Comparing the predictor-response relationship between real data and posterior predictive samples&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;5-step-4---residual-analysis-to-find-systematic-deviations&quot;&gt;5. Step 4 - Residual analysis to find systematic deviations&lt;/h2&gt;

&lt;p&gt;Simple standardized residual:&lt;/p&gt;

\[r_i = y_i - \mathbb{E}[y_i \mid y].\]

&lt;p&gt;You should look at at least three plots:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;residual vs fitted,&lt;/li&gt;
  &lt;li&gt;residual vs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;,&lt;/li&gt;
  &lt;li&gt;Q-Q plot of the residuals.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Signs to watch for:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;a curved pattern: suggests a nonlinear relationship,&lt;/li&gt;
  &lt;li&gt;a fan shape: suggests changing variance,&lt;/li&gt;
  &lt;li&gt;strongly skewed tails on the Q-Q plot: suggests the Normal assumption may be too simple.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; case, a common signal is that the residual magnitude grows with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;. This is why a homoskedastic error model may not be good enough.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_residual_distribution.png&quot; alt=&quot;Figure 6 - Residual distribution: observed vs posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_residuals.png&quot; alt=&quot;Figure 7 - Residuals vs fitted to identify systematic patterns&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-step-5---prediction-for-a-specific-case&quot;&gt;6. Step 5 - Prediction for a specific case&lt;/h2&gt;

&lt;p&gt;Suppose we predict for a new table with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill = 40&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You should report &lt;strong&gt;two kinds of uncertainty&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;the posterior interval of the mean tip at that bill level,&lt;/li&gt;
  &lt;li&gt;the prediction interval for one specific new table.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example interpretation:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the mean tip at a bill of 40 may be around 5.8 to 6.5,&lt;/li&gt;
  &lt;li&gt;but one specific table may be wider, for example 3.8 to 8.7.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The second interval is wider because it adds both parameter uncertainty and new individual noise.&lt;/p&gt;

&lt;p&gt;An important reporting point for decision-making:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;if the goal is planning average revenue, use the interval of the mean response,&lt;/li&gt;
  &lt;li&gt;if the goal is the risk of one specific transaction, use the prediction interval.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;7-step-6---when-the-checks-are-not-fine-revise-the-model-with-a-reason&quot;&gt;7. Step 6 - When the checks are not fine: revise the model with a reason&lt;/h2&gt;

&lt;p&gt;Suppose the PPC and residuals show that:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the original linear model under-predicts in the right tail,&lt;/li&gt;
  &lt;li&gt;the variance grows with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A reasonable way to revise:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;use a log-transform for the response, for example \(\log(\text{tip})\),&lt;/li&gt;
  &lt;li&gt;or model \(\sigma\) as a function of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt;,&lt;/li&gt;
  &lt;li&gt;or add a mild nonlinear component (spline/low-degree polynomial).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The important message: do not revise the model by gut feeling. Revise it according to the exact deviation signs that the PPC and residuals point out.&lt;/p&gt;

&lt;h3 id=&quot;71-a-quick-comparison-of-three-candidate-models&quot;&gt;7.1. A quick comparison of three candidate models&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Candidate&lt;/th&gt;
      &lt;th&gt;Addresses the main problem&lt;/th&gt;
      &lt;th&gt;Strength&lt;/th&gt;
      &lt;th&gt;Risk&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Baseline Gaussian linear&lt;/td&gt;
      &lt;td&gt;Initial reference point&lt;/td&gt;
      &lt;td&gt;Easy to interpret&lt;/td&gt;
      &lt;td&gt;Prone to errors in the tail and changing variance&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Log-tip Gaussian&lt;/td&gt;
      &lt;td&gt;Shrinks the right tail, stabilizes variance more&lt;/td&gt;
      &lt;td&gt;Often improves the tail PPC&lt;/td&gt;
      &lt;td&gt;Back-interpreting to the original units needs care&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Heteroskedastic Gaussian&lt;/td&gt;
      &lt;td&gt;Lets \(\sigma\) change with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;More honest prediction intervals at large bills&lt;/td&gt;
      &lt;td&gt;Increases complexity and checking cost&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;In practice, you should compare these candidates using the same set of PPC/residual criteria before concluding which model is most useful.&lt;/p&gt;

&lt;h2 id=&quot;8-summary-of-the-lesson-44-workflow-on-a-real-case&quot;&gt;8. Summary of the lesson 4.4 workflow on a real case&lt;/h2&gt;

&lt;p&gt;On the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; dataset, we have gone through the right cycle:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;state the generative story and fit the model,&lt;/li&gt;
  &lt;li&gt;check the diagnostics,&lt;/li&gt;
  &lt;li&gt;do posterior predictive checks,&lt;/li&gt;
  &lt;li&gt;read the residuals to find patterns,&lt;/li&gt;
  &lt;li&gt;predict for a specific situation with clear uncertainty,&lt;/li&gt;
  &lt;li&gt;propose a model revision based on evidence.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is the hands-on version of the message of lesson 4.4: Bayesian regression is only complete when you check and revise the model, not stopping at the posterior of the parameters alone.&lt;/p&gt;

&lt;h3 id=&quot;81-in-depth-analysis-checklist-reuse-for-other-problems&quot;&gt;8.1. In-depth analysis checklist (reuse for other problems)&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;check the data structure and tail region before fitting,&lt;/li&gt;
  &lt;li&gt;confirm the sampler meets the minimum standard,&lt;/li&gt;
  &lt;li&gt;run PPC at three levels: overall distribution, target statistic, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x -&amp;gt; y&lt;/code&gt; relationship,&lt;/li&gt;
  &lt;li&gt;read residuals by pattern, not just by looking at the mean,&lt;/li&gt;
  &lt;li&gt;report predictions with the right kind of uncertainty,&lt;/li&gt;
  &lt;li&gt;revise the model only when there are clear deviation signs from the checks.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;9-common-mistakes-in-this-case-study&quot;&gt;9. Common mistakes in this case study&lt;/h2&gt;

&lt;h3 id=&quot;91-stopping-at-the-slope-is-positive&quot;&gt;9.1. Stopping at “the slope is positive”&lt;/h3&gt;

&lt;p&gt;A positive slope does not guarantee that the model generates reasonable data over the whole domain of the predictor.&lt;/p&gt;

&lt;h3 id=&quot;92-reporting-the-wrong-kind-of-interval&quot;&gt;9.2. Reporting the wrong kind of interval&lt;/h3&gt;

&lt;p&gt;Using the interval of the mean response to speak about one specific individual/table creates false certainty.&lt;/p&gt;

&lt;h3 id=&quot;93-revising-the-model-without-relying-on-checks&quot;&gt;9.3. Revising the model without relying on checks&lt;/h3&gt;

&lt;p&gt;Trying many arbitrary transformations without following the residual/PPC signs makes the workflow lose its scientific character.&lt;/p&gt;

&lt;h3 id=&quot;94-reporting-results-without-stating-the-scope-of-applicability&quot;&gt;9.4. Reporting results without stating the scope of applicability&lt;/h3&gt;

&lt;p&gt;A model may be fine in the central &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total_bill&lt;/code&gt; region but weak in the very large region. If this is not stated clearly, users easily misjudge the reliability of the predictions.&lt;/p&gt;

&lt;h2 id=&quot;10-what-to-keep-after-this-lesson&quot;&gt;10. What to keep after this lesson&lt;/h2&gt;

&lt;p&gt;A mature Bayesian workflow always follows the loop:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;modeling -&amp;gt; checking -&amp;gt; predicting -&amp;gt; revising the model&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; case shows that even a small problem needs this full loop to reach a responsible conclusion.&lt;/p&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yDPJnV9vcHs&quot;&gt;What is a posterior predictive check and why is it useful?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the question a posterior predictive check asks before doing the workflow on the tips data.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=fpS0NjqNHn8&quot;&gt;L4: Interpretable Linear Regressions (State of Bayes Lecture Series)&lt;/a&gt; — PyMC Labs, English. Watch a Bayesian regression being fitted and its coefficients interpreted, supporting the model-building half of the case study.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=iMdtTCX2Q70&quot;&gt;Simple Linear Regression:  Checking Assumptions with Residual Plots&lt;/a&gt; — jbstatistics, English. Watch how to read a residual plot when checking assumptions, used for the residual analysis part of the lesson.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;For the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tips&lt;/code&gt; dataset, which statistic would you choose for the PPC besides the mean/variance, and why?&lt;/li&gt;
  &lt;li&gt;If the residual vs fitted forms a U shape, which direction would you try to revise the model first?&lt;/li&gt;
  &lt;li&gt;Why is the prediction interval for a new table always wider than the uncertainty interval of the mean tip?&lt;/li&gt;
  &lt;li&gt;If the model predicts the central region well but fails in the right tail, how does this affect business decisions?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), chapters on model checking.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Regression and Other Stories&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), chapters on posterior predictive checks.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter04/04_06_case_study_complex_dataset/&quot;&gt;Lesson 4.6 - Advanced Case Study on a Complex Dataset&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 4.4: Model Checking and Prediction - Making Sure the Model Is Good</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_04_model_checking_prediction/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_04_model_checking_prediction</id>
   <content type="html">&lt;p&gt;Your MCMC chains converged cleanly with \(\hat{R} = 1.00\), zero divergences, and 4,000 effective samples. Time to celebrate and ship the model? Not yet! Convergence only proves that your sampler accurately explored the posterior of &lt;em&gt;the model you wrote down&lt;/em&gt;—it says nothing about whether that model is a decent description of reality. A perfectly converged linear model fit to curved or heavy-tailed data will produce confidently wrong predictions. That is why every serious Bayesian workflow pivots from inference to &lt;strong&gt;model criticism&lt;/strong&gt;: Posterior Predictive Checks (PPC) and residual diagnostics.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lesson Roadmap:&lt;/strong&gt; Why convergence \(\neq\) a good model → Key ideas (Posterior predictive distribution, Bayesian p-values &amp;amp; test statistics, Mean vs. Prediction intervals) → Hand-worked Bayesian p-value &amp;amp; predictive interval width comparison → Residual analysis, uncertainty, and exercises.&lt;/p&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to understand that fitting the model is only the first half of Bayesian regression. The other half is checking whether the model describes the data reasonably, and using the posterior to predict new data honestly. You also need to grasp posterior predictive checks as the central tool of this step.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; A regression line can look very nice on a scatter plot, but if it does not generate data that looks like the real data, the model still has a problem. Model checking is the way to interrogate the model instead of trusting it just because it has finished running.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Why is a posterior that “looks fine” not enough to conclude that the model is good?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-criticizing-and-predicting-with-bayesian-models&quot;&gt;Key ideas: Criticizing and Predicting with Bayesian Models&lt;/h2&gt;

&lt;h3 id=&quot;1-posterior-predictive-distribution-pytextrep-mid-y&quot;&gt;1. Posterior Predictive Distribution (\(p(y^{\text{rep}} \mid y)\))&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Averaging the data likelihood over the entire posterior \(p(y^{\text{rep}} \mid y) = \int p(y^{\text{rep}} \mid \theta) p(\theta \mid y)\,d\theta\)—implemented by drawing \(\theta^{(s)}\) from the posterior and then simulating synthetic data \(y^{\text{rep},(s)} \sim p(y \mid \theta^{(s)})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Answering the acid test of generative modeling: &lt;em&gt;“If my fitted model were truly the data-generating machine, would its simulated worlds look like the real dataset I actually observed?”&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-posterior-predictive-checks-ppc-and-tail-area-diagnostics&quot;&gt;2. Posterior Predictive Checks (PPC) and Tail-Area Diagnostics&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Comparing observed summary statistics \(T(y)\) (mean, spread, max, skewness, fraction of zeros) against the distribution of \(T(y^{\text{rep},(s)})\), summarized by the Bayesian \(p\)-value \(p_B = P(T(y^{\text{rep}}) \ge T(y) \mid y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Pinpointing &lt;em&gt;exactly how&lt;/em&gt; a model fails—for instance, matching the mean perfectly while missing skewness, heteroscedasticity, or extreme outliers.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-credible-interval-for-the-mean-vs-prediction-interval-for-new-data&quot;&gt;3. Credible Interval for the Mean vs. Prediction Interval for New Data&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Separating uncertainty about the regression line \(\mu(x^*)\) from uncertainty about a brand-new observation \(y^* = \mu(x^*) + \varepsilon\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Preventing dangerously overconfident forecasts by always adding observation noise \(\sigma^2\) when predicting individual future outcomes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;explanation-bayesian-p-value--prediction-interval-width-by-hand&quot;&gt;Explanation: Bayesian p-Value &amp;amp; Prediction Interval Width by Hand&lt;/h2&gt;

&lt;h3 id=&quot;part-1-reading-a-posterior-predictive-check-via-p_b&quot;&gt;Part 1: Reading a Posterior Predictive Check via \(p_B\)&lt;/h3&gt;
&lt;p&gt;Suppose you fit a Normal linear model and check whether it captures extreme observations using the test statistic \(T(y) = \max_i \vert r_i \vert\) (largest standardized residual). In your real dataset, \(T(y) = 4.2\). Across \(S = 1{,}000\) posterior predictive replications \(y^{\text{rep},(s)}\), only &lt;strong&gt;12&lt;/strong&gt; simulations produce a max residual \(\ge 4.2\):
\(p_B = \frac{12}{1{,}000} = \mathbf{0.012}.\)
A value near \(0.5\) means the model reproduces that feature effortlessly; \(p_B = 0.012\) (close to 0 or 1) flags a concrete mismatch—here, heavier tails than a Normal likelihood, pointing directly toward a Student-\(t\) revision!&lt;/p&gt;

&lt;h3 id=&quot;part-2-why-a-95-prediction-interval-is-much-wider-than-a-95-mean-interval&quot;&gt;Part 2: Why a 95% Prediction Interval Is Much Wider Than a 95% Mean Interval&lt;/h3&gt;
&lt;p&gt;Suppose at \(x^* = 3\), your posterior gives \(\mathrm{Var}(\alpha \mid D) = 0.25\), \(\mathrm{Var}(\beta \mid D) = 0.16\) (uncorrelated), and noise variance \(\sigma^2 = 4.00\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Uncertainty of the regression line \(\mu(3)\):&lt;/strong&gt;
\(\mathrm{Var}(\mu(3)) = 0.25 + 3^2(0.16) = 1.69 \implies \mathrm{SD} = \mathbf{1.30} \quad (\text{95\% half-width } \approx \pm 2.55).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Uncertainty of a single new observation \(y^*(3)\):&lt;/strong&gt;
\(\mathrm{Var}(y^*(3)) = 4.00 + 1.69 = 5.69 \implies \mathrm{SD} = \mathbf{2.385} \quad (\text{95\% half-width } \approx \pm 4.67).\)
The prediction interval is &lt;strong&gt;\(1.83\times\) wider&lt;/strong&gt;—because knowing the average line accurately still cannot eliminate individual observation noise \(\sigma\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1-a-good-fit-is-not-necessarily-a-good-model&quot;&gt;1. A good fit is not necessarily a good model&lt;/h2&gt;

&lt;p&gt;This is an important shift in thinking.&lt;/p&gt;

&lt;p&gt;Many people learning regression stop at estimating the slope, looking at the interval, and then concluding as if the job were done.&lt;/p&gt;

&lt;p&gt;But a mature Bayesian workflow asks harder questions: can this model reproduce the observed data, do the residuals still show suspicious patterns, and are the predictions for new data really reasonable?&lt;/p&gt;

&lt;p&gt;George Box has a very famous saying:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“All models are wrong, but some are useful.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The goal is not to find an “absolutely correct” model, but a model that is useful enough, honest enough, and does not miss the important structures of the data.&lt;/p&gt;

&lt;h2 id=&quot;2-what-is-the-posterior-predictive-distribution&quot;&gt;2. What is the posterior predictive distribution?&lt;/h2&gt;

&lt;p&gt;Suppose you already have the posterior of the parameters. Then you can generate new data \(\tilde y\) from the model:&lt;/p&gt;

\[p(\tilde y \mid y) = \int p(\tilde y \mid \theta)\,p(\theta \mid y)\,d\theta.\]

&lt;p&gt;The meaning of the posterior predictive distribution is that we infer not only about the parameters, but also about future data or data replicated from the model itself.&lt;/p&gt;

&lt;p&gt;This is the bridge between estimation and prediction.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Reading the formula above&lt;/em&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\tilde y\) is the new data (or simulated data) that we want to predict,&lt;/li&gt;
  &lt;li&gt;\(\theta\) is the model parameter,&lt;/li&gt;
  &lt;li&gt;\(p(\theta \mid y)\) is how much we believe in each parameter value after seeing the data,&lt;/li&gt;
  &lt;li&gt;\(p(\tilde y \mid \theta)\) is how the model generates new data if the parameter is fixed at \(\theta\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So the integral is a “weighted average” over all possibilities of the parameters. The weight here is the posterior \(p(\theta \mid y)\): &lt;strong&gt;the parameters that the posterior deems more plausible contribute more to the final prediction&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In short, the posterior predictive does not use a single set of parameters, but combines the predictions of many sets of parameters according to their credibility.&lt;/p&gt;

&lt;p&gt;In MCMC practice, we usually approximate the integral by a sum:&lt;/p&gt;

\[p(\tilde y \mid y) \approx \frac{1}{S}\sum_{s=1}^{S} p(\tilde y \mid \theta^{(s)}), \quad \theta^{(s)} \sim p(\theta \mid y).\]

&lt;p&gt;The computation is very intuitive: draw many samples \(\theta^{(s)}\) from the posterior, generate \(\tilde y^{(s)}\) from each sample, and then combine them all into the posterior predictive distribution.&lt;/p&gt;

&lt;h2 id=&quot;3-what-is-a-posterior-predictive-check-ppc&quot;&gt;3. What is a posterior predictive check (PPC)?&lt;/h2&gt;

&lt;p&gt;The PPC asks a very practical question:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;If my model is correct, does the simulated data generated from the model look like the real data?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The basic PPC procedure is to draw many parameter samples from the posterior, generate fake data from each sample, and then compare the fake data with the observed data.&lt;/p&gt;

&lt;p&gt;If the fake data has a similar shape, spread, and patterns to the real data, the model has more grounds to be considered fine.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_summary.png&quot; alt=&quot;Summary of the posterior predictive check workflow&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;31-a-concrete-example-the-slope-looks-great-but-the-model-is-still-wrong&quot;&gt;3.1. A concrete example: the slope looks great but the model is still wrong&lt;/h3&gt;

&lt;p&gt;Suppose you model the relationship between study hours and exam score with a straight line. The posterior of the slope comes out very nice: clearly positive, a narrow interval, and the probability \(\beta &amp;gt; 0\) is almost 1.&lt;/p&gt;

&lt;p&gt;If we stop here, many people would conclude that the model is good. But imagine the true relationship in the data is: more study hours make the score rise quickly at first, after which the effect gradually saturates when studying too much. Then a straight line will typically produce three warning signs:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the PPC generates too many unrealistically high predicted points in the region of very many study hours,&lt;/li&gt;
  &lt;li&gt;the residuals in the middle region tend to be negative while the residuals at the two ends tend to be positive, creating a curved pattern,&lt;/li&gt;
  &lt;li&gt;the mean prediction looks fine overall but is systematically wrong in the important regions of \(x\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The meaning of this example is: the posterior of the parameters can be “nice” because the model has fitted very firmly to a wrong structure. PPC and residual analysis exist precisely to expose that kind of error.&lt;/p&gt;

&lt;h2 id=&quot;4-what-should-a-ppc-look-at&quot;&gt;4. What should a PPC look at?&lt;/h2&gt;

&lt;p&gt;There is no single check suitable for every problem. You should look from many angles:&lt;/p&gt;

&lt;h3 id=&quot;41-overall-distribution&quot;&gt;4.1. Overall distribution&lt;/h3&gt;

&lt;p&gt;Does the histogram or density of the fake data look like the real data?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_distribution_at_x5.png&quot; alt=&quot;Comparing the posterior predictive distribution at a representative value of x&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;42-mean-and-spread&quot;&gt;4.2. Mean and spread&lt;/h3&gt;

&lt;p&gt;Does the model reproduce the mean, variance, reasonable min/max, or tail behavior of the real data?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_test_stat_mean.png&quot; alt=&quot;Checking the mean of the observed data within the posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_variance_check.png&quot; alt=&quot;Checking the variance of the observed data within the posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;43-the-relationship-between-predictor-and-response&quot;&gt;4.3. The relationship between predictor and response&lt;/h3&gt;

&lt;p&gt;For regression, it is very important whether the model reproduces the right pattern between the predictor \(x\) and the response \(y\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_observed_vs_predicted.png&quot; alt=&quot;Comparing observed data with posterior predictive samples&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;44-problem-specific-statistics&quot;&gt;4.4. Problem-specific statistics&lt;/h3&gt;

&lt;p&gt;For example, the number of outliers, skewness, asymmetry, or the rate of exceeding a threshold.&lt;/p&gt;

&lt;h2 id=&quot;5-residual-analysis-is-still-very-important&quot;&gt;5. Residual analysis is still very important&lt;/h2&gt;

&lt;p&gt;Even in Bayesian regression, residuals are still a good mirror for the model.&lt;/p&gt;

&lt;p&gt;We usually look at residual vs fitted, residual vs predictor, the residual distribution, signs of heteroskedasticity, and signs of nonlinearity.&lt;/p&gt;

&lt;p&gt;Residual analysis is easiest to understand when placed beside typical situations: a good model, a model that misses nonlinearity, a model with heteroskedasticity, and a model with heavy-tailed residuals.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_ppc_residual_distribution.png&quot; alt=&quot;Residual distribution: observed vs posterior predictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;At the level of the raw scatter plot, the four figures below show what the data can look like in each situation.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_good_model_scatter.png&quot; alt=&quot;Scatter plot of a good model&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonlinearity_scatter.png&quot; alt=&quot;Scatter plot when the true relationship is nonlinear&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_scatter.png&quot; alt=&quot;Scatter plot when the variance grows with x&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonnormal_scatter.png&quot; alt=&quot;Scatter plot when the residuals have heavy tails&quot; /&gt;&lt;/p&gt;

&lt;p&gt;When moving to residual vs fitted, we want to see the residuals scattered randomly around 0 instead of forming a systematic pattern.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_good_model_residuals.png&quot; alt=&quot;Residuals vs fitted of a good model&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonlinearity_residuals.png&quot; alt=&quot;Residuals vs fitted showing signs of nonlinearity&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_residuals.png&quot; alt=&quot;Residuals vs fitted showing signs of heteroskedasticity&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonnormal_residuals.png&quot; alt=&quot;Residuals vs fitted with heavy-tailed residuals&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The Q-Q plot helps check whether the residuals are still close to Normal or are deviating from this assumption.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_good_model_qq.png&quot; alt=&quot;Q-Q plot of the residuals in a good model&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonlinearity_qq.png&quot; alt=&quot;Q-Q plot when the model misses nonlinearity&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_heteroskedasticity_qq.png&quot; alt=&quot;Q-Q plot when there is heteroskedasticity&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bad_nonnormal_qq.png&quot; alt=&quot;Q-Q plot when the residuals have heavy tails&quot; /&gt;&lt;/p&gt;

&lt;p&gt;If the residuals show a systematic pattern, the model may be missing nonlinearity, an interaction, heteroskedasticity, or some important variable that has not been included.&lt;/p&gt;

&lt;h2 id=&quot;6-how-does-prediction-in-bayes-differ-from-point-prediction&quot;&gt;6. How does prediction in Bayes differ from point prediction?&lt;/h2&gt;

&lt;p&gt;In classical regression, many people are used to only a single mean predicted value.&lt;/p&gt;

&lt;p&gt;Bayesian prediction goes further in that it keeps the uncertainty of the parameters, and also the uncertainty due to the noise of a new observation.&lt;/p&gt;

&lt;p&gt;This lets you say not only “the prediction is 72”, but also “where the plausible region of the prediction lies, and how sure we are”.&lt;/p&gt;

&lt;p&gt;That is a much more useful kind of forecast for decision-making.&lt;/p&gt;

&lt;h2 id=&quot;7-prediction-interval-and-uncertainty&quot;&gt;7. Prediction interval and uncertainty&lt;/h2&gt;

&lt;p&gt;There are two main sources of uncertainty:&lt;/p&gt;

&lt;h3 id=&quot;71-parameter-uncertainty&quot;&gt;7.1. Parameter uncertainty&lt;/h3&gt;

&lt;p&gt;We do not know exactly \(\alpha,\beta,\sigma\).&lt;/p&gt;

&lt;h3 id=&quot;72-uncertainty-of-a-new-observation&quot;&gt;7.2. Uncertainty of a new observation&lt;/h3&gt;

&lt;p&gt;Even if we knew the parameters perfectly, a new observation would still fluctuate around the mean line.&lt;/p&gt;

&lt;p&gt;A prediction interval is therefore always wider than the uncertainty of the mean response alone.&lt;/p&gt;

&lt;p&gt;This is very important when reporting predictions to end users.&lt;/p&gt;

&lt;h3 id=&quot;73-a-short-example-to-avoid-confusing-the-two-kinds-of-interval&quot;&gt;7.3. A short example to avoid confusing the two kinds of interval&lt;/h3&gt;

&lt;p&gt;Suppose that for a student who studies 6 hours, the model gives:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;a posterior interval for the mean score from 7.4 to 8.2,&lt;/li&gt;
  &lt;li&gt;a prediction interval for a new student from 6.0 to 9.3.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first interval answers the question: “if we take very many students who all study 6 hours, where does their average score lie?”&lt;/p&gt;

&lt;p&gt;The second interval answers the question: “in which region might the score of one specific student who studies 6 hours fall?”&lt;/p&gt;

&lt;p&gt;If you accidentally use the first interval to communicate about a specific individual, you will create an excessive sense of certainty. This is a very common interpretation error in prediction.&lt;/p&gt;

&lt;h2 id=&quot;8-model-checking-is-not-for-catching-a-perfect-model&quot;&gt;8. Model checking is not for “catching a perfect model”&lt;/h2&gt;

&lt;p&gt;Do not understand model checking as a binary game of either a perfect model or one to be thrown away.&lt;/p&gt;

&lt;p&gt;It is a process of asking where the model is wrong, how wrong it is, and whether that deviation affects the practical question we care about.&lt;/p&gt;

&lt;p&gt;For example, if the model is slightly off in the tail but still predicts the mean very well, it may still be acceptable; but if you care about extreme risk, then the error in the tail becomes a very serious problem.&lt;/p&gt;

&lt;h2 id=&quot;9-when-the-checks-are-not-fine-what-should-we-do&quot;&gt;9. When the checks are not fine, what should we do?&lt;/h2&gt;

&lt;p&gt;Do not react mechanically with “run the sampler more”.&lt;/p&gt;

&lt;p&gt;Instead, think in the following three broad directions:&lt;/p&gt;

&lt;h3 id=&quot;91-is-the-generative-story-missing-something&quot;&gt;9.1. Is the generative story missing something?&lt;/h3&gt;

&lt;p&gt;Ask whether there is nonlinearity, an interaction, or some group/hierarchical structure being overlooked.&lt;/p&gt;

&lt;h3 id=&quot;92-is-there-a-problem-with-the-prior&quot;&gt;9.2. Is there a problem with the prior?&lt;/h3&gt;

&lt;p&gt;Look at whether the prior is too wide, too narrow, or whether its prior predictive is really reasonable.&lt;/p&gt;

&lt;h3 id=&quot;93-is-there-anything-special-about-the-data&quot;&gt;9.3. Is there anything special about the data?&lt;/h3&gt;

&lt;p&gt;Check whether the data has outliers, measurement error, missing variables, or any noteworthy heteroskedasticity.&lt;/p&gt;

&lt;p&gt;Good model checking is what paves the way for good model revision.&lt;/p&gt;

&lt;h2 id=&quot;10-a-closed-loop-workflow-for-bayesian-regression&quot;&gt;10. A closed-loop workflow for Bayesian regression&lt;/h2&gt;

&lt;p&gt;Chapter 4 is actually teaching a complete workflow: tell the generative story, choose priors in a principled way, fit the posterior, check the sampler diagnostics, check the model with PPC and residuals, use the posterior to predict, and then go back and fix the model if needed.&lt;/p&gt;

&lt;p&gt;If you do all of these seven steps, regression is no longer “running a function”, but a real modeling process.&lt;/p&gt;

&lt;h2 id=&quot;11-common-mistakes&quot;&gt;11. Common mistakes&lt;/h2&gt;

&lt;h3 id=&quot;111-trusting-the-posterior-without-checking-the-model&quot;&gt;11.1. Trusting the posterior without checking the model&lt;/h3&gt;

&lt;p&gt;The posterior is only trustworthy if the model that generated that posterior is still reasonable.&lt;/p&gt;

&lt;h3 id=&quot;112-looking-only-at-the-fit-on-old-data&quot;&gt;11.2. Looking only at the fit on old data&lt;/h3&gt;

&lt;p&gt;Prediction for new data is where the model reveals its real value.&lt;/p&gt;

&lt;h3 id=&quot;113-doing-only-a-single-ppc&quot;&gt;11.3. Doing only a single PPC&lt;/h3&gt;

&lt;p&gt;A model can pass one criterion but fail another. Check from many perspectives.&lt;/p&gt;

&lt;h2 id=&quot;12-what-to-keep-after-this-lesson&quot;&gt;12. What to keep after this lesson&lt;/h2&gt;

&lt;p&gt;Bayesian regression does not end at the posterior. It really lives in whether the model explains the data reasonably, and whether the predictions it produces are truly useful.&lt;/p&gt;

&lt;p&gt;Without the checking and prediction steps, Bayesian regression has only gone halfway.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; The posterior predictive check is the way to ask whether the model generates data that looks like the real data; residual analysis and prediction are two important parts of evaluating whether the model is truly useful; and fitting the model is only the first step, because a complete Bayesian workflow always includes checking, prediction, and revision if needed.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yDPJnV9vcHs&quot;&gt;What is a posterior predictive check and why is it useful?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the posterior predictive check ask whether the model reproduces the features of the data, exactly the second half of regression that the lesson emphasizes.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=okjYjClSjOg&quot;&gt;Quantile-Quantile Plots (QQ plots), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch the Q–Q plot, supporting the part that compares the residual distribution with the Normal assumption.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Residual plots&lt;/td&gt;
          &lt;td&gt;Exploring bivariate numerical data&lt;/td&gt;
          &lt;td&gt;AP Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=VamMrPZ-8fc) — Khan Academy, English. Watch a residual plot detect leftover structure, used for the part of the lesson that does not stop at the sampler having converged.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why should a model that has been fitted but has not passed a PPC not yet be fully trusted?&lt;/li&gt;
  &lt;li&gt;What is the difference between the uncertainty of the mean prediction and the uncertainty of a new observation?&lt;/li&gt;
  &lt;li&gt;Name three things you can compare between the real data and the posterior predictive data.&lt;/li&gt;
  &lt;li&gt;If the residuals show a clearly curved pattern, what would you suspect about the model?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), chapters on model checking.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Regression and Other Stories&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), chapters on posterior predictive checks.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter04/04_05_case_study_model_checking_prediction/&quot;&gt;Lesson 4.5 - Case Study: Model Checking &amp;amp; Prediction&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 4.3: Posterior Inference with PyMC - From Theory to Practice</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_03_posterior_inference_pymc/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_03_posterior_inference_pymc</id>
   <content type="html">&lt;p&gt;Writing a Bayesian model on a whiteboard is deeply satisfying—until you actually want to run it on real data. That is where probabilistic programming languages like &lt;strong&gt;PyMC&lt;/strong&gt; come in: you write the exact generative story in 6 lines of Python, hit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.sample()&lt;/code&gt;, and NUTS automatically differentiates your log-posterior and draws thousands of correlated samples. Yet treating &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.sample()&lt;/code&gt; as a black box is dangerous: before you interpret a single credible interval, you need to know how to back-transform standardized coefficients, read \(\hat{R}\) and ESS, and check whether your Monte Carlo standard error is small enough to trust.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lesson Roadmap:&lt;/strong&gt; Translating math to PyMC code → Key ideas (Probabilistic programming &amp;amp; autodiff, Sampler diagnostics before interpretation, Posterior predictive propagation) → Hand-worked standardization back-transform &amp;amp; MCSE check → Full PyMC workflow, code, and exercises.&lt;/p&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to know how to turn Bayesian regression from a generative story into a model that runs in PyMC. You also need to understand a basic practical workflow: standardizing the data, writing priors, declaring the likelihood, sampling the posterior, reading diagnostics, and interpreting the results.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; Once you understand the generative story and know how to choose reasonable priors, the next step is to write the real model in PyMC to get the posterior of the intercept, slope and noise. PyMC does not think about the model for you; it helps you implement that model more efficiently.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If PyMC has already produced the posterior, why do we still have to look at diagnostics before interpreting the results?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-from-mathematical-model-to-reliable-pymc-inference&quot;&gt;Key ideas: From Mathematical Model to Reliable PyMC Inference&lt;/h2&gt;

&lt;h3 id=&quot;1-probabilistic-programming-and-automatic-differentiation&quot;&gt;1. Probabilistic Programming and Automatic Differentiation&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Expressing random variables (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.Normal&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.HalfNormal&lt;/code&gt;) as nodes in a computational graph whose exact log-density gradient \(\nabla \log p(\theta \mid D)\) is computed automatically via reverse-mode autodiff (PyTensor).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Decoupling &lt;em&gt;model specification&lt;/em&gt; (what you believe about the world) from &lt;em&gt;inference&lt;/em&gt; (how NUTS explores the posterior).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-diagnostic-gating-never-interpret-an-unchecked-posterior&quot;&gt;2. Diagnostic Gating: Never Interpret an Unchecked Posterior&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Checking &lt;strong&gt;divergences&lt;/strong&gt; (must be 0), &lt;strong&gt;\(\hat{R}\)&lt;/strong&gt; (\(\le 1.01\)), &lt;strong&gt;bulk/tail ESS&lt;/strong&gt; (ideally \(&amp;gt; 400\)), and &lt;strong&gt;MCSE&lt;/strong&gt; (Monte Carlo Standard Error \(\mathrm{SD}/\sqrt{\mathrm{ESS}}\)) before looking at parameter means.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Ensuring numerical approximation error from finite MCMC draws is negligible compared to genuine posterior uncertainty.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-posterior-summaries-vs-posterior-predictive-draws&quot;&gt;3. Posterior Summaries vs. Posterior Predictive Draws&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Distinguishing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;idata.posterior&lt;/code&gt; (distributions over parameters \(\alpha, \beta, \sigma\)) from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.sample_posterior_predictive&lt;/code&gt; (distributions over &lt;em&gt;new data&lt;/em&gt; \(y^*\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Propagating full joint parameter uncertainty—including correlations between \(\alpha\) and \(\beta\)—into real-world predictions and intervals.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;explanation-back-transforming-standardized-pymc-output--checking-mcse&quot;&gt;Explanation: Back-Transforming Standardized PyMC Output &amp;amp; Checking MCSE&lt;/h2&gt;

&lt;p&gt;Suppose you standardize height (\(\bar{x} = 170\text{ cm},\, s_x = 10\text{ cm}\)) and weight (\(\bar{y} = 65\text{ kg},\, s_y = 12\text{ kg}\)), fit a PyMC model, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;az.summary()&lt;/code&gt; reports:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\alpha_z \approx 0.02\), \(\beta_z \approx 0.80\) (with posterior \(\mathrm{SD}(\beta_z) = 0.12\) and \(\mathrm{ESS} = 1{,}600\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;1-convert-standardized-parameters-back-to-physical-units-kg-and-cm&quot;&gt;1. Convert standardized parameters back to physical units (kg and cm)&lt;/h3&gt;
&lt;p&gt;Since \(\frac{y - \bar{y}}{s_y} = \alpha_z + \beta_z \frac{x - \bar{x}}{s_x}\), solving for \(y = \alpha + \beta x\) gives:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Physical slope:&lt;/strong&gt; \(\beta = \beta_z \frac{s_y}{s_x} = 0.80 \times \frac{12}{10} = \mathbf{0.96\text{ kg/cm}}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Physical intercept:&lt;/strong&gt; \(\alpha = \bar{y} + s_y \alpha_z - \beta \bar{x} = 65 + 12(0.02) - 0.96(170) = 65.24 - 163.20 = \mathbf{-97.96\text{ kg}}.\)
(This immediately shows why centering matters: \(-97.96\text{ kg}\) at height \(0\text{ cm}\) is meaningless, while \(\alpha_z = 0.02\) says an average-height person weighs \(65.24\text{ kg}\)!)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-verify-monte-carlo-standard-error-mcse&quot;&gt;2. Verify Monte Carlo Standard Error (MCSE)&lt;/h3&gt;
&lt;p&gt;How noisy is our MCMC estimate of the posterior mean \(0.80\)?
\(\mathrm{MCSE}(\beta_z) = \frac{\mathrm{SD}(\beta_z)}{\sqrt{\mathrm{ESS}}} = \frac{0.12}{\sqrt{1{,}600}} = \frac{0.12}{40} = \mathbf{0.003}.\)
Because \(0.003\) is only &lt;strong&gt;\(2.5\%\)&lt;/strong&gt; of the posterior SD (well below the \(5\%\) rule of thumb), the reported mean &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.80&lt;/code&gt; is numerically rock-solid to two decimal places.&lt;/p&gt;

&lt;h2 id=&quot;1-from-a-model-on-paper-to-a-model-in-code&quot;&gt;1. From a model on paper to a model in code&lt;/h2&gt;

&lt;p&gt;In lessons 4.1 and 4.2, we already have all three ingredients: the generative story, priors for the parameters, and intuition about Bayesian regression.&lt;/p&gt;

&lt;p&gt;This lesson mainly performs a very practical translation step: moving from statistical thinking to a model that can run in PyMC.&lt;/p&gt;

&lt;p&gt;The minimal workflow here is to prepare the data, standardize if needed, declare the priors, declare the likelihood, run the sampler, check the diagnostics, and only then read the posterior.&lt;/p&gt;

&lt;h2 id=&quot;2-why-do-we-need-mcmc-because-there-is-no-closed-form-formula&quot;&gt;2. Why do we need MCMC? Because there is no closed-form formula&lt;/h2&gt;

&lt;h3 id=&quot;21-from-conjugacy-to-non-conjugacy&quot;&gt;2.1. From conjugacy to non-conjugacy&lt;/h3&gt;

&lt;p&gt;In Chapter 2, we learned about &lt;strong&gt;conjugate priors&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Beta-Binomial&lt;/strong&gt;: Prior Beta + Likelihood Binomial → Posterior Beta&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gamma-Poisson&lt;/strong&gt;: Prior Gamma + Likelihood Poisson → Posterior Gamma&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Normal-Normal&lt;/strong&gt;: Prior Normal + Likelihood Normal → Posterior Normal&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With these conjugate pairs, we have a &lt;strong&gt;closed-form formula&lt;/strong&gt; to compute the posterior directly:&lt;/p&gt;

\[\theta \mid D \sim \text{Beta}(\alpha_0 + k, \beta_0 + n - k)\]

&lt;p&gt;Just plug the numbers into the formula and you are done. &lt;strong&gt;No powerful computer needed, no sampling.&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;22-bayesian-regression-no-more-simple-formula&quot;&gt;2.2. Bayesian regression: no more simple formula&lt;/h3&gt;

&lt;p&gt;But with &lt;strong&gt;Bayesian regression&lt;/strong&gt;, the situation is more complicated:&lt;/p&gt;

\[\begin{aligned}
\beta_0 &amp;amp;\sim \mathcal{N}(5, 5) \\
\beta_1 &amp;amp;\sim \mathcal{N}(2, 5) \\
\sigma &amp;amp;\sim \text{HalfNormal}(2) \\
y_i &amp;amp;\sim \mathcal{N}(\beta_0 + \beta_1 x_i, \sigma^2)
\end{aligned}\]

&lt;p&gt;&lt;strong&gt;Problems:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Three parameters ($\beta_0, \beta_1, \sigma$) must be updated &lt;strong&gt;simultaneously&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;The priors are Normal + HalfNormal (not conjugate with the likelihood)&lt;/li&gt;
  &lt;li&gt;The posterior is a 3-dimensional &lt;strong&gt;joint&lt;/strong&gt; distribution, with no simple formula&lt;/li&gt;
&lt;/ul&gt;

\[p(\beta_0, \beta_1, \sigma \mid D) = \frac{p(D \mid \beta_0, \beta_1, \sigma) \cdot p(\beta_0) \cdot p(\beta_1) \cdot p(\sigma)}{p(D)}\]

&lt;p&gt;With $p(D) = \int\int\int p(D \mid \beta_0, \beta_1, \sigma) \cdot p(\beta_0) \cdot p(\beta_1) \cdot p(\sigma) \, d\beta_0 \, d\beta_1 \, d\sigma$&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This integral cannot be computed by hand!&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;23-mcmc-sample-instead-of-computing-a-formula&quot;&gt;2.3. MCMC: sample instead of computing a formula&lt;/h3&gt;

&lt;p&gt;When there is no closed-form formula, we use &lt;strong&gt;MCMC (Markov Chain Monte Carlo)&lt;/strong&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Core idea:&lt;/strong&gt; Instead of doing complicated mathematical computation, we &lt;strong&gt;sample&lt;/strong&gt; from the posterior.&lt;/p&gt;

  &lt;p&gt;Like an opinion survey: you do not ask all 10 million people, you only need to ask 4000 representative people.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;MCMC works as follows:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Start&lt;/strong&gt; from a random point in the parameter space&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Move&lt;/strong&gt; to a new point following a smart rule (favoring high-probability regions)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Repeat&lt;/strong&gt; thousands of times to create a “chain” of samples&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Result:&lt;/strong&gt; The set of samples faithfully reflects the posterior distribution&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Illustrative example:&lt;/strong&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Instead of computing a complicated formula:
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;complicated_integral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(...)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ❌ Cannot be computed!
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# We sample:
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Declare priors
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beta_0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta_0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta_1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Likelihood
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# MCMC: draw 2000 samples from the posterior
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ← THIS IS MCMC!
&lt;/span&gt;    
&lt;span class=&quot;c1&quot;&gt;# Result: trace contains 2000 sets (β₀, β₁, σ) from the posterior
# Each set is a &quot;possible world&quot; consistent with the data
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;MCMC result:&lt;/strong&gt;&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Sample&lt;/th&gt;
      &lt;th&gt;β₀&lt;/th&gt;
      &lt;th&gt;β₁&lt;/th&gt;
      &lt;th&gt;σ&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;6.8&lt;/td&gt;
      &lt;td&gt;2.1&lt;/td&gt;
      &lt;td&gt;0.6&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;6.5&lt;/td&gt;
      &lt;td&gt;2.2&lt;/td&gt;
      &lt;td&gt;0.5&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;…&lt;/td&gt;
      &lt;td&gt;…&lt;/td&gt;
      &lt;td&gt;…&lt;/td&gt;
      &lt;td&gt;…&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2000&lt;/td&gt;
      &lt;td&gt;6.9&lt;/td&gt;
      &lt;td&gt;2.0&lt;/td&gt;
      &lt;td&gt;0.7&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;From these 2000 samples, we can compute:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Posterior mean:&lt;/strong&gt; The average of the samples&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;95% Credible Interval:&lt;/strong&gt; The 2.5% and 97.5% percentiles&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Probability β₁ &amp;gt; 0:&lt;/strong&gt; Count how many samples have β₁ &amp;gt; 0&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;24-comparing-conjugacy-vs-mcmc&quot;&gt;2.4. Comparing conjugacy vs MCMC&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;Conjugate Priors&lt;/th&gt;
      &lt;th&gt;MCMC (Regression)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Prior&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Beta, Gamma, simple Normal&lt;/td&gt;
      &lt;td&gt;Many complicated priors&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Likelihood&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Binomial, Poisson, Normal&lt;/td&gt;
      &lt;td&gt;Normal with many parameters&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Posterior&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Closed-form formula&lt;/td&gt;
      &lt;td&gt;No formula&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Computation&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Plug numbers into the formula&lt;/td&gt;
      &lt;td&gt;Sampling with MCMC&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Result&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Exact distribution&lt;/td&gt;
      &lt;td&gt;Approximation from samples&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Example&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Beta(17, 103)&lt;/td&gt;
      &lt;td&gt;2000 samples (β₀, β₁, σ)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Time&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&amp;lt; 1 second&lt;/td&gt;
      &lt;td&gt;10-60 seconds&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Accuracy&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;100%&lt;/td&gt;
      &lt;td&gt;~99% (with enough samples)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;25-pymc-hides-the-complexity-of-mcmc&quot;&gt;2.5. PyMC hides the complexity of MCMC&lt;/h3&gt;

&lt;p&gt;The great thing about PyMC is that you do not need to understand deeply:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Metropolis-Hastings algorithm&lt;/li&gt;
  &lt;li&gt;Gibbs sampling&lt;/li&gt;
  &lt;li&gt;NUTS (No-U-Turn Sampler)&lt;/li&gt;
  &lt;li&gt;Hamiltonian Monte Carlo&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You only need to:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Declare the model (priors + likelihood)&lt;/li&gt;
  &lt;li&gt;Call &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.sample()&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Check diagnostics (R-hat, ESS)&lt;/li&gt;
  &lt;li&gt;Read the results&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;PyMC automatically:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chooses the best sampler (usually NUTS)&lt;/li&gt;
  &lt;li&gt;Tunes automatically during the warm-up phase&lt;/li&gt;
  &lt;li&gt;Parallelizes multiple chains&lt;/li&gt;
  &lt;li&gt;Detects problems and warns you&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;26-summary-when-to-use-mcmc&quot;&gt;2.6. Summary: When to use MCMC?&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Situation&lt;/th&gt;
      &lt;th&gt;Method&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Conjugate priors + 1 parameter&lt;/td&gt;
      &lt;td&gt;✅ Closed-form formula&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Non-conjugate or many parameters&lt;/td&gt;
      &lt;td&gt;✅ MCMC&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Regression with &amp;gt;2 parameters&lt;/td&gt;
      &lt;td&gt;✅ MCMC (PyMC)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Hierarchical models&lt;/td&gt;
      &lt;td&gt;✅ MCMC&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mixture models&lt;/td&gt;
      &lt;td&gt;✅ MCMC&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Simple rule:&lt;/strong&gt;&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;If you cannot compute the posterior by hand in 5 minutes → Use MCMC!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;3-what-does-a-simple-bayesian-regression-in-pymc-look-like-structurally&quot;&gt;3. What does a simple Bayesian regression in PyMC look like structurally?&lt;/h2&gt;

&lt;p&gt;The right way of thinking is always to start from the prior for \(\alpha\), the prior for \(\beta\), the prior for \(\sigma\), and only then reach the likelihood:&lt;/p&gt;

\[y_i \sim \mathcal{N}(\alpha + \beta x_i,\sigma).\]

&lt;p&gt;In PyMC, you are just rewriting that story as code.&lt;/p&gt;

&lt;p&gt;What matters is that the code should reflect the model, not that the model be distorted just to fit a specific API.&lt;/p&gt;

&lt;h3 id=&quot;31-a-minimal-but-runnable-pymc-example&quot;&gt;3.1. A minimal but runnable PyMC example&lt;/h3&gt;

&lt;p&gt;Suppose you have a very small dataset on height and weight:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pymc&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;height&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;150&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;155&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;160&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;165&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;170&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;175&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;180&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;185&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;54&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;57&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;62&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;66&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;76&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;82&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;height&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reg_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;HalfNormal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_z&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y_obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y_obs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;draws&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;tune&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;chains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;target_accept&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;random_seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Notably, each block of code maps directly onto the statistical story:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alpha&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;beta&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sigma&lt;/code&gt; are the three priors for the three core parameters,&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mu = alpha + beta * x_z&lt;/code&gt; is the mean line of the regression,&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y_obs = pm.Normal(...)&lt;/code&gt; is the likelihood, i.e. how the data is generated around that mean line,&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pm.sample(...)&lt;/code&gt; is the step that samples from the posterior instead of finding a single point estimate.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you can keep the one-to-one link between the model on paper and this block of code, you are on the right track.&lt;/p&gt;

&lt;h2 id=&quot;4-why-standardize-the-data-before-fitting&quot;&gt;4. Why standardize the data before fitting?&lt;/h2&gt;

&lt;p&gt;Bayesian regression usually runs better when variables are well scaled.&lt;/p&gt;

&lt;p&gt;The benefits of standardizing are that priors are easier to choose, the intercept is easier to interpret, the sampler usually converges more smoothly, and the posterior is also less “distorted by measurement units”.&lt;/p&gt;

&lt;p&gt;So in a great many cases, standardizing is a practice step worth having.&lt;/p&gt;

&lt;h2 id=&quot;5-after-sampling-what-do-we-read-first&quot;&gt;5. After sampling, what do we read first?&lt;/h2&gt;

&lt;p&gt;Many beginners jump straight to the posterior mean and interval. But the thing to look at first is actually the diagnostics, meaning whether the trace plot looks fine, whether R-hat is close to 1, whether ESS is sufficient, and whether the sampler emitted any warnings.&lt;/p&gt;

&lt;p&gt;If this part is not good, every posterior interpretation afterwards should be considered tentative.&lt;/p&gt;

&lt;h2 id=&quot;6-interpreting-the-posterior-in-regression&quot;&gt;6. Interpreting the posterior in regression&lt;/h2&gt;

&lt;p&gt;When the model runs well, only then do we return to the statistical questions.&lt;/p&gt;

&lt;h3 id=&quot;61-intercept&quot;&gt;6.1. Intercept&lt;/h3&gt;

&lt;p&gt;With data that has been standardized or centered, the intercept is usually easier to read because it describes the mean value of \(y\) when \(x\) is at the central level.&lt;/p&gt;

&lt;h3 id=&quot;62-slope&quot;&gt;6.2. Slope&lt;/h3&gt;

&lt;p&gt;The posterior of the slope tells whether the relationship is positive or negative, strong or weak, and how sure we are about it. The nice thing about Bayes is that you can directly ask what the probability of \(\beta &amp;gt; 0\) is.&lt;/p&gt;

&lt;h3 id=&quot;63-noise&quot;&gt;6.3. Noise&lt;/h3&gt;

&lt;p&gt;The posterior of \(\sigma\) tells how widely the data is spread around the regression line, that is, how much unexplained variation the model still leaves behind.&lt;/p&gt;

&lt;h3 id=&quot;64-example-updating-from-prior-to-posterior-for-regression-parameters&quot;&gt;6.4. Example: updating from prior to posterior for regression parameters&lt;/h3&gt;

&lt;p&gt;Suppose that after fitting a one-variable linear model with PyMC, we obtain the following summary:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Prior: \(\alpha\sim\mathcal N(60,20),\;\beta\sim\mathcal N(0,2),\;\sigma\sim\text{HalfNormal}(5)\).&lt;/li&gt;
  &lt;li&gt;Posterior summary:
    &lt;ul&gt;
      &lt;li&gt;
\[\alpha\mid D\approx \mathcal N(63.2,\,1.1^2)\]
      &lt;/li&gt;
      &lt;li&gt;
\[\beta\mid D\approx \mathcal N(0.78,\,0.09^2)\]
      &lt;/li&gt;
      &lt;li&gt;\(\sigma\mid D\) has a posterior mean of about \(2.4\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Quick interpretation:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the data has pulled the intercept from a prior region around 60 up to about 63.2,&lt;/li&gt;
  &lt;li&gt;the slope is clearly positive with small uncertainty (SD 0.09),&lt;/li&gt;
  &lt;li&gt;the remaining noise is about 2.4 response units.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If we need an approximate 95% posterior interval for the slope (approximately Normal):&lt;/p&gt;

\[0.78\pm 1.96\times 0.09\Rightarrow [0.604,\;0.956].\]

&lt;p&gt;This interval does not cross 0, so the posterior evidence supports a fairly clear positive relationship.&lt;/p&gt;

&lt;h2 id=&quot;7-from-parameter-posteriors-to-predictions&quot;&gt;7. From parameter posteriors to predictions&lt;/h2&gt;

&lt;p&gt;Bayesian regression is not only for knowing what the slope is. It is also for predicting. For example, for a new value of \(x\), we want to know where the predicted weight or exam score will be, and how wide the uncertainty that comes with that prediction is.&lt;/p&gt;

&lt;p&gt;This is where PyMC is very convenient, because once we have posterior draws, we can move rather naturally into the posterior predictive.&lt;/p&gt;

&lt;h3 id=&quot;71-a-concrete-example-prediction-for-a-person-175-cm-tall&quot;&gt;7.1. A concrete example: prediction for a person 175 cm tall&lt;/h3&gt;

&lt;p&gt;With the model above, suppose you want to predict for a person 175 cm tall. We can directly take the posterior draws and propagate them to the prediction:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;extract&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;group&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;alpha_draws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_draws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sigma_draws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x_new_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;175&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;mu_new_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_draws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_draws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_new_z&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_new_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_new_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma_draws&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;mu_new&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_new_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_new&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_new_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The two objects here serve two different questions:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mu_new&lt;/code&gt; is the distribution for the &lt;strong&gt;predicted mean value&lt;/strong&gt;, i.e. the average weight of the group of people 175 cm tall under the model.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y_new&lt;/code&gt; is the distribution for &lt;strong&gt;a new observation&lt;/strong&gt;, i.e. the weight of one specific individual 175 cm tall.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Suppose that after summarizing these samples, you see:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the mean of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mu_new&lt;/code&gt; is about 71 kg with an 89% interval from 69 to 73 kg,&lt;/li&gt;
  &lt;li&gt;while &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y_new&lt;/code&gt; has a wider 89% prediction interval, for example from 63 to 79 kg.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then you should read the result in proper Bayesian language:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the model is quite sure about the &lt;strong&gt;average trend&lt;/strong&gt; in the region of 175 cm height,&lt;/li&gt;
  &lt;li&gt;but still honestly says that &lt;strong&gt;a new individual&lt;/strong&gt; can deviate from the average quite a lot.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is exactly where posterior inference turns into prediction very naturally: we do not change the model, we just continue telling the generative story one step further.&lt;/p&gt;

&lt;h2 id=&quot;8-a-minimal-healthy-workflow-when-using-pymc-for-regression&quot;&gt;8. A minimal healthy workflow when using PyMC for regression&lt;/h2&gt;

&lt;p&gt;You can remember this workflow as three consecutive stages, each with a central question that must be answered clearly before moving to the next step:&lt;/p&gt;

&lt;h3 id=&quot;before-running&quot;&gt;Before running&lt;/h3&gt;

&lt;p&gt;Before running, ask whether the variables need standardizing, whether the priors are reasonable on the actual scale of the data, and whether the generative story is truly clear.&lt;/p&gt;

&lt;h3 id=&quot;while-running&quot;&gt;While running&lt;/h3&gt;

&lt;p&gt;While running, watch whether the sampler issues any warnings and whether the warm-up phase is sufficient.&lt;/p&gt;

&lt;h3 id=&quot;after-running&quot;&gt;After running&lt;/h3&gt;

&lt;p&gt;After running, look at whether the trace plot looks fine, whether R-hat and ESS are good, what the parameter posteriors are saying, and whether the posterior predictive is reasonable.&lt;/p&gt;

&lt;h3 id=&quot;note-on-the-knownunknown-variance-setting&quot;&gt;Note on the known/unknown variance setting&lt;/h3&gt;

&lt;p&gt;In PyMC practice, we usually infer \(\sigma\) as well, so the interval of the slope already reflects uncertainty about the noise. If you fix \(\sigma\) in advance (a special problem), the interval for the slope is usually narrower. When reporting results, you should state clearly which scenario you are in.&lt;/p&gt;

&lt;h2 id=&quot;9-common-mistakes-of-beginners-using-pymc-for-regression&quot;&gt;9. Common mistakes of beginners using PyMC for regression&lt;/h2&gt;

&lt;h3 id=&quot;91-treating-pymc-as-a-black-box&quot;&gt;9.1. Treating PyMC as a black box&lt;/h3&gt;

&lt;p&gt;This is the biggest mistake.&lt;/p&gt;

&lt;p&gt;If you do not understand the model, you will not know what the prior is saying, what the warnings are reporting, and whether the posterior is really trustworthy.&lt;/p&gt;

&lt;h3 id=&quot;92-reading-only-the-posterior-mean&quot;&gt;9.2. Reading only the posterior mean&lt;/h3&gt;

&lt;p&gt;The posterior mean is not enough. You need to look at the interval, the probability of exceeding a threshold, the shape of the posterior, and also the prediction uncertainty.&lt;/p&gt;

&lt;h3 id=&quot;93-forgetting-model-checking&quot;&gt;9.3. Forgetting model checking&lt;/h3&gt;

&lt;p&gt;Finishing the regression fit is not the end. The next lesson will emphasize posterior predictive checks, residual analysis, and prediction quality.&lt;/p&gt;

&lt;h2 id=&quot;10-what-this-lesson-wants-you-to-keep&quot;&gt;10. What this lesson wants you to keep&lt;/h2&gt;

&lt;p&gt;The goal is not to remember every line of the PyMC API. The goal is to see that Bayesian regression can be implemented very naturally as long as you keep the right thinking workflow. PyMC is just a tool; the most important parts are still the model story, the priors, the diagnostics, and how to interpret the posterior.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; PyMC helps implement Bayesian regression following exactly the prior + likelihood + posterior structure you have learned; after fitting the model, diagnostics must always come before interpreting the posterior; and the real value of posterior inference lies not only in parameter estimation but also in the ability to move on to prediction and model checking.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jrU0UBr2z3k&quot;&gt;[114] Getting Started with PyMC (Chris Fonnesbeck)&lt;/a&gt; — Data Umbrella, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch a PyMC model being declared and then sampled, exactly the step where the lesson goes from generative story to code.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=fpS0NjqNHn8&quot;&gt;L4: Interpretable Linear Regressions (State of Bayes Lecture Series)&lt;/a&gt; — PyMC Labs, English. Watch linear regression in PyMC and how to read the coefficients, supporting the lesson’s workflow of standardization, priors and likelihood.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=911d4A1U0BE&quot;&gt;Chris Fonnesbeck - Probabilistic Python: An Introduction to Bayesian Modeling with PyMC&lt;/a&gt; — PyData, English. Watch a longer introduction to Bayesian modeling with PyMC, for when you need to see both the priors and the checks after sampling.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;List the 5 minimal steps of a Bayesian regression workflow with PyMC.&lt;/li&gt;
  &lt;li&gt;Why does standardizing the data usually help both prior selection and sampling?&lt;/li&gt;
  &lt;li&gt;If the posterior of the slope looks reasonable but R-hat is not good, what should you do?&lt;/li&gt;
  &lt;li&gt;In Bayesian regression, why is prediction just as important a part as estimation?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;PyMC Documentation.&lt;/li&gt;
  &lt;li&gt;ArviZ Documentation.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 4-5.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter04/04_04_model_checking_prediction/&quot;&gt;4.4 Model Checking and Prediction - Ensuring a Good Model&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 4.2b: MCMC Methods - Mathematical Theory</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_02b_mcmc_theory/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_02b_mcmc_theory</id>
   <content type="html">&lt;p&gt;In Lesson 2.6, we watched grid approximation hit an impenetrable exponential wall: even a 10-parameter model requires \(10^{20}\) grid evaluations. Yet every day, modern statisticians fit Bayesian models with &lt;em&gt;thousands&lt;/em&gt; of parameters in seconds. How do they compute a thousand-dimensional integral without ever laying down a grid? They stop trying to map the entire desert and instead send a clever random walker—a &lt;strong&gt;Markov chain&lt;/strong&gt;—engineered so that the fraction of time it spends in every region equals the exact posterior probability of that region.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lesson Roadmap:&lt;/strong&gt; From intractable integrals to Markov chain samplers → Key ideas (Detailed balance &amp;amp; stationary distributions, Metropolis–Hastings &amp;amp; Gibbs, Hamiltonian Monte Carlo &amp;amp; convergence diagnostics) → Hand-worked 2-step Metropolis–Hastings &amp;amp; ESS calculation → Full algorithmic theory, code, and exercises.&lt;/p&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to firmly grasp &lt;strong&gt;why MCMC works&lt;/strong&gt; from a mathematical point of view. Specifically, you need to understand: (1) the Monte Carlo principle - sampling to estimate integrals, (2) the Metropolis-Hastings algorithm - the accept/reject mechanism and the proof of convergence, (3) Gibbs sampling - sampling each parameter conditionally, and (4) the convergence diagnostics R-hat and ESS.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Why don’t we simply draw random samples directly from the posterior, instead of using a Markov chain to gradually “probe” into the high-probability region?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-mathematical-engine-behind-mcmc&quot;&gt;Key ideas: The Mathematical Engine Behind MCMC&lt;/h2&gt;

&lt;h3 id=&quot;1-stationary-distributions-and-detailed-balance&quot;&gt;1. Stationary Distributions and Detailed Balance&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Designing a Markov transition kernel \(T(\theta \to \theta&apos;)\) that satisfies &lt;strong&gt;detailed balance&lt;/strong&gt; \(\pi(\theta) T(\theta \to \theta&apos;) = \pi(\theta&apos;) T(\theta&apos; \to \theta)\) for the target posterior \(\pi(\theta) \propto p(D \mid \theta)p(\theta)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Guaranteeing that the chain converges to \(\pi\) &lt;em&gt;without ever needing the normalizing constant \(P(D)\)&lt;/em&gt;, because \(P(D)\) cancels out in every probability ratio \(\pi(\theta&apos;)/\pi(\theta)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-proposal-geometries-random-walk-mh-gibbs-and-hmc&quot;&gt;2. Proposal Geometries: Random-Walk MH, Gibbs, and HMC&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Three escalating strategies for proposing \(\theta^*\): blind local steps (Metropolis–Hastings), exact conditional updates (Gibbs), and gradient-guided Hamiltonian trajectories (HMC/NUTS).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Why random walks diffuse slowly (\(O(d^2)\) steps) in high dimensions whereas HMC surfs the &lt;strong&gt;typical set&lt;/strong&gt; along level curves of energy using \(\nabla \log \pi(\theta)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-convergence-diagnostics-hatr-and-effective-sample-size-ess&quot;&gt;3. Convergence Diagnostics: \(\hat{R}\) and Effective Sample Size (ESS)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Measuring whether multiple independent chains mix into the same distribution (\(\hat{R} \approx 1.00\)) and how many &lt;em&gt;effectively independent&lt;/em&gt; draws remain after accounting for autocorrelation \(\rho_k\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Protecting against silent sampler failure where 4,000 correlated draws actually contain less information than 50 independent ones.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;explanation-two-metropolishastings-steps--ess-by-hand&quot;&gt;Explanation: Two Metropolis–Hastings Steps &amp;amp; ESS by Hand&lt;/h2&gt;

&lt;h3 id=&quot;part-1-two-exact-mh-steps-without-the-normalizing-constant&quot;&gt;Part 1: Two Exact MH Steps Without the Normalizing Constant&lt;/h3&gt;
&lt;p&gt;Target the standard normal \(\pi(\theta) = \frac{1}{\sqrt{2\pi}} e^{-\theta^2/2}\) using only the unnormalized kernel \(\tilde{\pi}(\theta) = e^{-\theta^2/2}\) and a symmetric proposal (so \(q(\theta \mid \theta^*)/q(\theta^* \mid \theta) = 1\)). Start at \(\theta_0 = 2.0\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Step 1 (propose \(\theta^* = 1.0\)):&lt;/strong&gt;
\(r = \frac{\tilde{\pi}(1.0)}{\tilde{\pi}(2.0)} = \frac{e^{-1^2/2}}{e^{-2^2/2}} = e^{-0.5 + 2.0} = e^{1.5} \approx 4.482.\)
Acceptance probability \(A = \min(1, 4.482) = \mathbf{1.0}\) → &lt;strong&gt;Accept&lt;/strong&gt; uphill move: \(\theta_1 = 1.0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step 2 (from \(\theta_1 = 1.0\), propose \(\theta^* = 2.5\)):&lt;/strong&gt;
\(r = \frac{\tilde{\pi}(2.5)}{\tilde{\pi}(1.0)} = \frac{e^{-6.25/2}}{e^{-1/2}} = e^{-2.625} \approx \mathbf{0.0724}.\)
Draw uniform \(u = 0.25\). Since \(u = 0.25 &amp;gt; 0.0724\) → &lt;strong&gt;Reject&lt;/strong&gt; and record the current state again: \(\theta_2 = 1.0\). Notice we never used \(\sqrt{2\pi}\) once!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;part-2-why-autocorrelation-shrinks-your-sample-size-ess&quot;&gt;Part 2: Why Autocorrelation Shrinks Your Sample Size (ESS)&lt;/h3&gt;
&lt;p&gt;Suppose a chain produces \(N = 1{,}000\) draws with AR(1) lag-1 autocorrelation \(\rho_1 = 0.8\) (so \(\rho_k = 0.8^k\)). The integrated autocorrelation time is:
\(\tau_{\text{int}} = 1 + 2\sum_{k=1}^{\infty} \rho_1^k = \frac{1 + \rho_1}{1 - \rho_1} = \frac{1.8}{0.2} = \mathbf{9.0} \implies \mathrm{ESS} = \frac{1{,}000}{9.0} \approx \mathbf{111}.\)
One thousand sluggish draws deliver only &lt;strong&gt;111&lt;/strong&gt; independent samples—which is why ESS, not raw draw count, governs Monte Carlo precision!&lt;/p&gt;

&lt;h2 id=&quot;1-from-a-real-problem-to-an-incomputable-integral&quot;&gt;1. From a real problem to an “incomputable” integral&lt;/h2&gt;

&lt;h3 id=&quot;11-what-does-bayesian-inference-give-you-as-you-already-know&quot;&gt;1.1. What does Bayesian inference give you, as you already know?&lt;/h3&gt;

&lt;p&gt;When we have data \(D\) and want to infer the parameter \(\theta\), Bayes gives us:&lt;/p&gt;

\[p(\theta \mid D) = \frac{p(D \mid \theta) \cdot p(\theta)}{p(D)}.\]

&lt;p&gt;But &lt;strong&gt;that is only a formula&lt;/strong&gt;. To really understand the data, we need to answer concrete questions:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Question 1 - What is the mean?&lt;/strong&gt;
If we want to know the expected value of \(\theta\) after observing the data, we need to compute:&lt;/p&gt;

\[\mathbb{E}[\theta \mid D] = \int \theta \cdot p(\theta \mid D) \, d\theta.\]

&lt;p&gt;&lt;strong&gt;Question 2 - Which range of values contains 95% of the probability mass?&lt;/strong&gt;
We need to find two thresholds \(a\) and \(b\) satisfying:&lt;/p&gt;

\[\int_a^b p(\theta \mid D) \, d\theta = 0.95.\]

&lt;p&gt;&lt;strong&gt;Question 3 - What is the probability that \(\theta\) exceeds a threshold \(c\)?&lt;/strong&gt;
For example, the probability that \(\theta &amp;gt; 0\) (positive slope):&lt;/p&gt;

\[p(\theta &amp;gt; c \mid D) = \int_c^\infty p(\theta \mid D) \, d\theta.\]

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Remark:&lt;/strong&gt; All of these natural questions lead to &lt;strong&gt;integrals&lt;/strong&gt;!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;12-the-problem-the-matrix-hidden-in-the-bayes-formula&quot;&gt;1.2. The problem: the “matrix” hidden in the Bayes formula&lt;/h3&gt;

&lt;p&gt;Look closely again at the Bayes formula:&lt;/p&gt;

\[p(\theta \mid D) = \frac{p(D \mid \theta) \cdot p(\theta)}{p(D)}.\]

&lt;p&gt;We already know the &lt;strong&gt;numerator&lt;/strong&gt; - it is:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(p(D \mid \theta)\): the likelihood (easy to compute, given by the model)&lt;/li&gt;
  &lt;li&gt;\(p(\theta)\): the prior (we choose it)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But what about the &lt;strong&gt;denominator&lt;/strong&gt; \(p(D)\)?&lt;/p&gt;

\[p(D) = \int p(D \mid \theta) \cdot p(\theta) \, d\theta\]

&lt;p&gt;This is an &lt;strong&gt;integral over the whole parameter space&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Concrete example:&lt;/strong&gt; Suppose you have a regression:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;3 parameters \(\theta = (\beta_0, \beta_1, \sigma)\)&lt;/li&gt;
  &lt;li&gt;\(n = 100\) data points&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then \(p(D)\) is a &lt;strong&gt;103-dimensional&lt;/strong&gt; integral:&lt;/p&gt;

\[p(D) = \iiint \prod_{i=1}^{100} \mathcal{N}(y_i \mid \beta_0 + \beta_1 x_i, \sigma^2) \cdot \mathcal{N}(\beta_0) \cdot \mathcal{N}(\beta_1) \cdot \text{HalfNormal}(\sigma) \, d\beta_0 \, d\beta_1 \, d\sigma.\]

&lt;p&gt;&lt;strong&gt;No one can compute this by hand!&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;13-the-surprising-solution-dont-compute-measure&quot;&gt;1.3. The surprising solution: “Don’t compute, measure!”&lt;/h3&gt;

&lt;p&gt;Instead of trying to compute the integral, &lt;strong&gt;we measure by sampling&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This is the idea of &lt;strong&gt;Monte Carlo&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;If you have a scale with a randomly swinging needle (completely random, no known formula!), and you weigh \(S\) times and get the numbers \(\theta^{(1)}, \theta^{(2)}, \ldots, \theta^{(S)}\), then:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Sample mean&lt;/strong&gt;: \(\bar{\theta} = \frac{1}{S}\sum_{s=1}^{S} \theta^{(s)}\) will be close to \(\mathbb{E}[\theta \mid D]\) when \(S\) is large&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sample percentiles&lt;/strong&gt; will be close to the credible intervals&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is the &lt;strong&gt;Law of Large Numbers&lt;/strong&gt; - one of the most important theorems in probability and statistics:&lt;/p&gt;

\[\frac{1}{S}\sum_{s=1}^{S} g(\theta^{(s)}) \xrightarrow{p} \mathbb{E}[g(\theta) \mid D] \quad \text{as } S \to \infty.\]

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Summary of step 1:&lt;/strong&gt; We do not compute the integral. We draw samples from the posterior and then take the average!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;14-but-where-do-we-sample-from&quot;&gt;1.4. But… where do we sample from?&lt;/h3&gt;

&lt;p&gt;Now we run into the &lt;strong&gt;biggest paradox&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;To compute the integral, we need to draw samples from the posterior&lt;/li&gt;
  &lt;li&gt;But the posterior is exactly what we are trying to find!&lt;/li&gt;
  &lt;li&gt;We do not know the formula of \(p(\theta \mid D)\) in order to sample from it directly&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Solution: Build a “road” to the posterior&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Instead of sampling directly, we build a &lt;strong&gt;chain of points&lt;/strong&gt; \(\theta^{(0)}, \theta^{(1)}, \theta^{(2)}, \ldots\) such that:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;We start from somewhere&lt;/li&gt;
  &lt;li&gt;Each step “probes” a little&lt;/li&gt;
  &lt;li&gt;After many steps, the points \(\theta^{(t)}\) land in exactly the posterior distribution!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is the idea of &lt;strong&gt;Markov Chain Monte Carlo (MCMC)&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-building-the-road-to-the-posterior&quot;&gt;2. Building the “road” to the posterior&lt;/h2&gt;

&lt;h3 id=&quot;21-how-does-a-markov-chain-work&quot;&gt;2.1. How does a Markov chain work?&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Picture this:&lt;/strong&gt; You are lost in a forest (the parameter space) and want to find the highest mountain peak (the region of highest probability).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Markov chain way:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;From your current position, you &lt;strong&gt;look around&lt;/strong&gt; a little&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Move to a new position&lt;/strong&gt; with higher probability (if you see an uphill path)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stay put&lt;/strong&gt; if the new position is not better (with some probability)&lt;/li&gt;
  &lt;li&gt;Repeat thousands of times!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The key point: &lt;strong&gt;You do not need to know where the “peak” is&lt;/strong&gt; - you only need to know “which direction is uphill” (comparing heights between two points).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mathematical definition:&lt;/strong&gt; A Markov chain is a sequence \(\theta^{(0)}, \theta^{(1)}, \theta^{(2)}, \ldots\) in which the next position depends only on the current position:&lt;/p&gt;

\[p(\theta^{(t)} \mid \theta^{(t-1)}, \theta^{(t-2)}, \ldots) = p(\theta^{(t)} \mid \theta^{(t-1)}).\]

&lt;h3 id=&quot;22-the-destination-of-a-markov-chain&quot;&gt;2.2. The “destination” of a Markov chain&lt;/h3&gt;

&lt;p&gt;An important property of Markov chains: &lt;strong&gt;If run long enough, it will “forget” the starting position and converge to a limiting distribution&lt;/strong&gt; \(\pi(\theta)\), called the &lt;strong&gt;stationary distribution&lt;/strong&gt;.&lt;/p&gt;

\[\pi(\theta&apos;) = \int p(\theta&apos; \mid \theta) \pi(\theta) \, d\theta.\]

&lt;p&gt;&lt;strong&gt;Ergodic theorem:&lt;/strong&gt; If a Markov chain is:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Irreducible&lt;/strong&gt; - can reach every region from every other region&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Aperiodic&lt;/strong&gt; - has no fixed cycle&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Positive recurrent&lt;/strong&gt; - the mean return time is finite&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;…then a unique stationary distribution \(\pi(\theta)\) exists, and every initial distribution will converge to \(\pi(\theta)\).&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;The secret of MCMC:&lt;/strong&gt; We construct the Markov chain so that the &lt;strong&gt;stationary distribution is exactly the posterior \(p(\theta \mid D)\)&lt;/strong&gt;! Then, after enough steps, the samples \(\theta^{(t)}\) are exactly samples from the posterior!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-the-metropolis-hastings-algorithm-building-a-road-to-the-peak&quot;&gt;3. The Metropolis-Hastings algorithm: “Building a road to the peak”&lt;/h2&gt;

&lt;h3 id=&quot;31-the-idea-try-a-step-reject-if-it-is-not-good&quot;&gt;3.1. The idea: Try a step, reject if it is not good&lt;/h3&gt;

&lt;p&gt;You are at position \(\theta\). How do you decide where to go?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1 - Proposal:&lt;/strong&gt; From \(\theta\), you “close your eyes” and propose a new position \(\theta^*\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Random walk&lt;/strong&gt;: \(\theta^* = \theta + \epsilon\), with \(\epsilon \sim \mathcal{N}(0, \sigma^2 I)\) (a small random step)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Independence&lt;/strong&gt;: \(\theta^* \sim q(\theta^*)\) (a proposal independent of the current position)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 2 - Compute the acceptance ratio:&lt;/strong&gt;
Compare the “height” at the two points:
\(\alpha = \min\left(1, \frac{p(\theta^* \mid D) \cdot q(\theta \mid \theta^*)}{p(\theta \mid D) \cdot q(\theta^* \mid \theta)}\right).\)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;The wonderful point:&lt;/strong&gt; This formula &lt;strong&gt;does not need to compute the denominator&lt;/strong&gt; \(p(D)\)! Because:
\(\frac{p(\theta^* \mid D)}{p(\theta \mid D)} = \frac{p(D \mid \theta^*) \cdot p(\theta^*)}{p(D \mid \theta) \cdot p(\theta)}\)
…we only need the ratio of likelihood × prior!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Step 3 - Decide:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Flip a random coin \(u \sim \text{Uniform}(0, 1)\)&lt;/li&gt;
  &lt;li&gt;If \(u \leq \alpha\): Accept! Move to \(\theta^*\)&lt;/li&gt;
  &lt;li&gt;If \(u &amp;gt; \alpha\): Stay! \(\theta_{t+1} = \theta_t\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;32-illustration-in-code&quot;&gt;3.2. Illustration in code&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;metropolis_hastings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_log_pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;proposal_sd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    p_log_pdf: log posterior (unnormalized) - only needs log p(D|θ) + log p(θ)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Step 1: Propose a new position (random walk)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;theta_star&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;proposal_sd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Step 2: Compute the acceptance ratio (log scale for safety)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;log_alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;p_log_pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_star&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;p_log_pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Step 3: Decide
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_star&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Accept and move on
&lt;/span&gt;            
        &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;33-why-does-this-algorithm-work-mathematical-proof&quot;&gt;3.3. Why does this algorithm work? (Mathematical proof)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt; How do we know this chain will converge to the correct posterior?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt; Because we design it so that &lt;strong&gt;Detailed Balance&lt;/strong&gt; is satisfied:&lt;/p&gt;

\[p(\theta \mid D) \cdot p(\theta&apos; \mid \theta) = p(\theta&apos; \mid D) \cdot p(\theta \mid \theta&apos;).\]

&lt;p&gt;That is, the probability of going from \(\theta\) to \(\theta&apos;\) (times the probability of being at \(\theta\)) equals the probability of going from \(\theta&apos;\) to \(\theta\) (times the probability of being at \(\theta&apos;\)).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Check:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Transition probability: \(p(\theta&apos; \mid \theta) = q(\theta&apos; \mid \theta) \cdot \alpha(\theta \to \theta&apos;)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consider two cases:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Case 1:&lt;/strong&gt; \(\theta&apos; \neq \theta\) (there is movement)&lt;/p&gt;

\[\alpha(\theta \to \theta&apos;) = \min\left(1, \frac{p(\theta&apos; \mid D) \cdot q(\theta \mid \theta&apos;)}{p(\theta \mid D) \cdot q(\theta&apos; \mid \theta)}\right).\]

&lt;p&gt;Let \(r = \frac{p(\theta&apos; \mid D) \cdot q(\theta \mid \theta&apos;)}{p(\theta \mid D) \cdot q(\theta&apos; \mid \theta)}\).&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;If \(r \geq 1\): \(\alpha = 1\), always accept moving toward higher probability&lt;/li&gt;
  &lt;li&gt;If \(r &amp;lt; 1\): \(\alpha = r\), accept with probability \(r\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We can prove that the balance equality is satisfied.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Case 2:&lt;/strong&gt; \(\theta&apos; = \theta\) (staying in place)&lt;/p&gt;

&lt;p&gt;The probability of staying includes: (rejecting a move to another position).&lt;/p&gt;

&lt;p&gt;Because &lt;strong&gt;Detailed Balance is satisfied&lt;/strong&gt;, \(p(\theta \mid D)\) is the stationary distribution. By the ergodic theorem, the chain will converge to \(p(\theta \mid D)\)!&lt;/p&gt;

&lt;h3 id=&quot;34-tuning-how-to-choose-the-step-size&quot;&gt;3.4. Tuning: How to choose the step size?&lt;/h3&gt;

&lt;p&gt;With a symmetric Gaussian proposal, the formula simplifies to:&lt;/p&gt;

\[\alpha = \min\left(1, \frac{p(\theta^* \mid D)}{p(\theta \mid D)}\right).\]

&lt;p&gt;&lt;strong&gt;Golden rule:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;A step that is &lt;strong&gt;too small&lt;/strong&gt; → almost every step is accepted but the chain barely moves → acceptance rate ~90% (but moves very slowly)&lt;/li&gt;
  &lt;li&gt;A step that is &lt;strong&gt;too large&lt;/strong&gt; → often rejected because it “jumps” over low-probability regions → acceptance rate ~5%&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sweet spot&lt;/strong&gt;: Acceptance rate &lt;strong&gt;23-50%&lt;/strong&gt; depending on dimension&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;experiment-metropolis-step-by-step&quot;&gt;Experiment: Metropolis step by step&lt;/h3&gt;

&lt;p&gt;Watch proposals being accepted or rejected, the histogram approaching the target, and the trace plot and R-hat of 4 chains.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;mcmc-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;metropolis&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-gibbs-sampling-divide-and-conquer&quot;&gt;4. Gibbs Sampling: “Divide and conquer”&lt;/h2&gt;

&lt;h3 id=&quot;41-the-problem-with-metropolis-hastings&quot;&gt;4.1. The problem with Metropolis-Hastings&lt;/h3&gt;

&lt;p&gt;When there are &lt;strong&gt;many parameters&lt;/strong&gt; (for example 100 parameters in a neural network), random walk Metropolis-Hastings runs into trouble:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;It has to move in a &lt;strong&gt;100-dimensional&lt;/strong&gt; space all at once&lt;/li&gt;
  &lt;li&gt;The probability of “aiming” in the highest direction is \(\approx 0.5^{100}\) → almost 0!&lt;/li&gt;
  &lt;li&gt;The acceptance rate is extremely low, and the chain moves very slowly&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;42-the-idea-one-small-step-at-a-time&quot;&gt;4.2. The idea: One small step at a time&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gibbs sampling&lt;/strong&gt; solves this by: &lt;strong&gt;“Don’t try to jump in all 100 dimensions, jump one dimension at a time!”&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With a model \(\theta = (\theta_1, \theta_2, \ldots, \theta_K)\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Initialization:&lt;/strong&gt; \(\theta^{(0)} = (\theta_1^{(0)}, \ldots, \theta_K^{(0)})\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For each step \(t\):&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;\(\theta_1^{(t+1)} \sim p(\theta_1 \mid \theta_2^{(t)}, \theta_3^{(t)}, \ldots, \theta_K^{(t)}, D)\) - Keep the other parameters fixed, only update \(\theta_1\)&lt;/li&gt;
  &lt;li&gt;\(\theta_2^{(t+1)} \sim p(\theta_2 \mid \theta_1^{(t+1)}, \theta_3^{(t)}, \ldots, \theta_K^{(t)}, D)\) - Now that \(\theta_1\) has been updated, update \(\theta_2\)&lt;/li&gt;
  &lt;li&gt;Continue until \(\theta_K\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Concrete example:&lt;/strong&gt; Suppose the model is \(\theta = (\alpha, \beta)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1 - Sample \(\alpha\) conditionally:&lt;/strong&gt;
\(p(\alpha \mid \beta, D) \propto p(D \mid \alpha, \beta) \cdot p(\alpha).\)&lt;/p&gt;

&lt;p&gt;We only need 1 dimension - much easier to compute!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2 - Sample \(\beta\) conditionally:&lt;/strong&gt;
\(p(\beta \mid \alpha, D) \propto p(D \mid \alpha, \beta) \cdot p(\beta).\)&lt;/p&gt;

&lt;h3 id=&quot;43-gibbs--metropolis-hastings-with-accept--100&quot;&gt;4.3. Gibbs = Metropolis-Hastings with accept = 100%&lt;/h3&gt;

&lt;div class=&quot;textbook-theorem&quot;&gt;
  &lt;p&gt;&lt;strong&gt;Theorem:&lt;/strong&gt; Gibbs sampling is a special case of Metropolis-Hastings with acceptance probability = 1!&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;Indeed:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Proposal: Change one parameter \(\theta_j\) using a value from the conditional distribution&lt;/li&gt;
  &lt;li&gt;The ratio works out to 1 (no division needed!)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantage:&lt;/strong&gt; Always accepts → moves more efficiently!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Disadvantage:&lt;/strong&gt; You must know the formula of the conditional distribution for each parameter (not always available!).&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;experiment-gibbs-on-a-correlated-distribution&quot;&gt;Experiment: Gibbs on a correlated distribution&lt;/h3&gt;

&lt;p&gt;Each step changes one coordinate; high correlation makes the horizontal/vertical steps very short.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;mcmc-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;gibbs&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;5-hamiltonian-monte-carlo-skiing-downhill&quot;&gt;5. Hamiltonian Monte Carlo: “Skiing downhill”&lt;/h2&gt;

&lt;h3 id=&quot;51-the-next-limitation&quot;&gt;5.1. The next limitation&lt;/h3&gt;

&lt;p&gt;Gibbs is good, but it needs to know the conditional distributions. What if we do not know them?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HMC&lt;/strong&gt; comes to solve this:&lt;/p&gt;

&lt;h3 id=&quot;52-the-idea-use-the-gradient-to-slide&quot;&gt;5.2. The idea: Use the “gradient” to slide&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Picture this:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;You are at the top of a mountain and want to get down to the foot&lt;/li&gt;
  &lt;li&gt;Instead of a random walk, you &lt;strong&gt;ski&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;The gradient tells you which direction is “downhill”&lt;/li&gt;
  &lt;li&gt;Momentum helps you go farther and not get stuck in local minima&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Mathematics:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Add “momentum” \(r\) for each \(\theta\)&lt;/li&gt;
  &lt;li&gt;Hamiltonian: \(H(\theta, r) = -\log p(\theta \mid D) - \log p(r \mid \theta) = U(\theta) + K(r)\)
    &lt;ul&gt;
      &lt;li&gt;\(U(\theta)\) = potential energy = \(-\log p(\theta \mid D)\) (height)&lt;/li&gt;
      &lt;li&gt;\(K(r)\) = kinetic energy = \(\frac{1}{2}r^T M^{-1} r\) (velocity)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Simulate the Hamiltonian system using &lt;strong&gt;leapfrog integration&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;Accept with ratio \(e^{-H(\theta^*, r^*) + H(\theta, r)}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;53-advantages&quot;&gt;5.3. Advantages&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Moves far&lt;/strong&gt;: Leapfrog creates large jumps, not a small random walk&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;High acceptance rate&lt;/strong&gt;: Thanks to using the gradient to “push” toward high-probability regions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Higher efficiency&lt;/strong&gt;: Especially in high-dimensional spaces&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;NUTS (No-U-Turn Sampler)&lt;/strong&gt; automatically chooses a suitable number of leapfrog steps by running until the chain “turns back” (U-turn). This is the default sampler in PyMC!&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;experiment-the-leapfrog-trajectory-of-hmc&quot;&gt;Experiment: the leapfrog trajectory of HMC&lt;/h3&gt;

&lt;p&gt;Adjust ε and L: a long trajectory is accepted when energy is conserved.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;mcmc-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;hmc&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;6-how-do-we-know-the-chain-has-converged-r-hat-and-ess&quot;&gt;6. How do we know the chain has converged? (R-hat and ESS)&lt;/h2&gt;

&lt;h3 id=&quot;61-r-hat-do-the-different-roads-arrive-at-the-same-place&quot;&gt;6.1. R-hat: Do the different “roads” arrive at the same place?&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Problem:&lt;/strong&gt; How do we know the chain has converged?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt; Run &lt;strong&gt;multiple independent chains&lt;/strong&gt; from different starting positions. If they all converge to the same distribution, the chains “merge”.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Within-chain variance&lt;/strong&gt;: \(W = \frac{1}{M} \sum_{m=1}^{M} \frac{1}{S-1} \sum_{s=1}^{S} (\theta_{m,s} - \bar{\theta}_m)^2\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Between-chain variance&lt;/strong&gt;: \(B = \frac{S}{M-1} \sum_{m=1}^{M} (\bar{\theta}_m - \bar{\theta}_{..})^2\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Estimated variance&lt;/strong&gt;: \(\hat{\sigma}^2 = \frac{S-1}{S}W + \frac{1}{S}B\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;R-hat&lt;/strong&gt;: \(\hat{R} = \sqrt{\frac{\hat{\sigma}^2}{W}}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Interpretation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\hat{R} \approx 1\): The chains have converged, between-chain variance ≈ within-chain variance!&lt;/li&gt;
  &lt;li&gt;\(\hat{R} &amp;gt; 1.1\): &lt;strong&gt;Warning!&lt;/strong&gt; The chains have not converged - they are in different places!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;62-ess-are-the-samples-independent&quot;&gt;6.2. ESS: Are the samples “independent”?&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Problem:&lt;/strong&gt; MCMC samples are &lt;strong&gt;autocorrelated&lt;/strong&gt;. A chain of 2000 samples is &lt;strong&gt;not equivalent&lt;/strong&gt; to 2000 i.i.d. samples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Picture this:&lt;/strong&gt; If you walk in small steps, the positions you step on will be &lt;strong&gt;close together&lt;/strong&gt; → not independent samples!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ESS measures:&lt;/strong&gt; The number of i.i.d. samples equivalent to the current MCMC chain.&lt;/p&gt;

\[\text{ESS} = \frac{S}{1 + 2\sum_{k=1}^{\infty} \rho(k)}\]

&lt;p&gt;where \(\rho(k)\) is the autocorrelation at lag \(k\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Rule of thumb:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;ESS &amp;gt; 400: Enough for estimating the mean&lt;/li&gt;
  &lt;li&gt;ESS &amp;gt; 1000: Enough for quantile estimation&lt;/li&gt;
  &lt;li&gt;ESS &amp;lt; 100: &lt;strong&gt;Warning!&lt;/strong&gt; Samples are too correlated&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;63-practice-with-arviz&quot;&gt;6.3. Practice with ArviZ&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arviz&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;from_pymc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;az&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;summary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idata&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var_names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta_0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;beta_1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;mean&lt;/th&gt;
      &lt;th&gt;sd&lt;/th&gt;
      &lt;th&gt;hdi_3%&lt;/th&gt;
      &lt;th&gt;hdi_97%&lt;/th&gt;
      &lt;th&gt;r_hat&lt;/th&gt;
      &lt;th&gt;ess&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;beta_0&lt;/td&gt;
      &lt;td&gt;6.52&lt;/td&gt;
      &lt;td&gt;0.31&lt;/td&gt;
      &lt;td&gt;5.91&lt;/td&gt;
      &lt;td&gt;7.13&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1.00&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1203&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;beta_1&lt;/td&gt;
      &lt;td&gt;0.78&lt;/td&gt;
      &lt;td&gt;0.09&lt;/td&gt;
      &lt;td&gt;0.61&lt;/td&gt;
      &lt;td&gt;0.96&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1.01&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;987&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;sigma&lt;/td&gt;
      &lt;td&gt;2.41&lt;/td&gt;
      &lt;td&gt;0.24&lt;/td&gt;
      &lt;td&gt;1.98&lt;/td&gt;
      &lt;td&gt;2.87&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1.00&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;856&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Criteria:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;R-hat &amp;lt; 1.05 (the closer to 1 the better)&lt;/li&gt;
  &lt;li&gt;ESS &amp;gt; 400 for the mean&lt;/li&gt;
  &lt;li&gt;ESS &amp;gt; 200 for tail probabilities&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-when-to-use-which-algorithm&quot;&gt;7. When to use which algorithm?&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Algorithm&lt;/th&gt;
      &lt;th&gt;Advantages&lt;/th&gt;
      &lt;th&gt;Disadvantages&lt;/th&gt;
      &lt;th&gt;When to use&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Metropolis-Hastings&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Simple, flexible&lt;/td&gt;
      &lt;td&gt;Slow random walk, low acceptance rate&lt;/td&gt;
      &lt;td&gt;Complex distributions, no alternative&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Gibbs Sampling&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;100% acceptance, simple&lt;/td&gt;
      &lt;td&gt;Needs known conditional distributions&lt;/td&gt;
      &lt;td&gt;When there are conjugate structures&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Hamiltonian MC&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;High efficiency, moves far&lt;/td&gt;
      &lt;td&gt;Needs gradient, more complex&lt;/td&gt;
      &lt;td&gt;High-dimensional spaces (default in PyMC)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;NUTS&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Automatic tuning&lt;/td&gt;
      &lt;td&gt;Tuning overhead&lt;/td&gt;
      &lt;td&gt;PyMC/PyMC3 (default sampler)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-what-this-lesson-wants-you-to-keep&quot;&gt;8. What this lesson wants you to keep&lt;/h2&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas:&lt;/strong&gt;&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;Metropolis-Hastings&lt;/strong&gt; works because it ensures detailed balance with the posterior as the stationary distribution&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Gibbs sampling&lt;/strong&gt; is MH with an acceptance rate of 100% when the conditionals are known&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;HMC/NUTS&lt;/strong&gt; is a highly efficient version thanks to using the gradient and momentum&lt;/li&gt;
  &lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;MCMC is not “magic” - it is a rigorous mathematical consequence of the theorems on Markov chains and Monte Carlo. When you understand it deeply, you will:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Be confident in diagnostics because you know what R-hat and ESS measure&lt;/li&gt;
  &lt;li&gt;Choose a sampler suited to the problem&lt;/li&gt;
  &lt;li&gt;Debug when a sampler runs into problems&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yApmR-c_hKU&quot;&gt;Markov Chain Monte Carlo (MCMC) : Data Science Concepts&lt;/a&gt; — ritvikmath, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch MCMC as a way of sampling when the normalizing integral cannot be computed, exactly why the lesson opens with the posterior integral.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yCv2N7wGDCw&quot;&gt;Metropolis - Hastings : Data Science Concepts&lt;/a&gt; — ritvikmath, English. Watch the proposal step and the accept–reject step of Metropolis–Hastings, supporting the algorithm section of the lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=a-wydhEuAm0&quot;&gt;The intuition behind the Hamiltonian Monte Carlo algorithm&lt;/a&gt; — Ben Lambert, English. Watch the intuition of Hamiltonian Monte Carlo using derivatives to follow the shape of the posterior, exactly the HMC part of the lesson.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why does the acceptance ratio of Metropolis-Hastings with a symmetric proposal not need to compute \(p(D)\)?&lt;/li&gt;
  &lt;li&gt;Prove that Gibbs sampling is a special case of Metropolis-Hastings with acceptance rate = 1.&lt;/li&gt;
  &lt;li&gt;Given a simple model, explain why R-hat &amp;gt; 1.1 indicates that the chains have not converged.&lt;/li&gt;
  &lt;li&gt;Compare the ESS of a random-walk chain (Metropolis-Hastings) with a chain using leapfrog (HMC). What is the reason the ESS differs?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., Carlin, J., Stern, H., Dunson, D., Vehtari, A., &amp;amp; Rubin, D. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 11.&lt;/li&gt;
  &lt;li&gt;Robert, C., &amp;amp; Casella, G. (2004). &lt;em&gt;Monte Carlo Statistical Methods&lt;/em&gt;, Chapter 7.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 8.&lt;/li&gt;
  &lt;li&gt;Hoff, P. (2009). &lt;em&gt;A First Course in Bayesian Statistical Methods&lt;/em&gt;, Chapter 6.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter04/04_03_posterior_inference_pymc/&quot;&gt;4.3 Posterior Inference with PyMC&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 4.2: Priors for Regression - Choosing Priors in a Principled Way</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_02_priors_for_regression/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_02_priors_for_regression</id>
   <content type="html">&lt;p&gt;Nothing makes a newcomer to Bayesian regression freeze up faster than the blank line next to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;beta ~ Normal(?, ?)&lt;/code&gt;. Choose a prior that is too tight and you risk steamrolling your own data; choose a “safe, uninformative” flat prior like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Normal(0, 100)&lt;/code&gt; and—as we are about to verify by hand—you have accidentally told the model that a 7 cm taller human might weigh as much as a sedan! Choosing priors is not guesswork; it is a disciplined engineering loop anchored by standardization and &lt;strong&gt;prior predictive checks&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lesson Roadmap:&lt;/strong&gt; Why “flat” priors are secretly absurd → Key ideas (Standardization, Weakly informative priors, Prior predictive simulation) → Hand-check of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Normal(0, 100)&lt;/code&gt; vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Normal(0, 1)&lt;/code&gt; on standardized variables → Choosing priors for \(\alpha\), \(\beta\), \(\sigma\), and exercises.&lt;/p&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to know how to choose priors for regression in a principled way. You also need to understand why standardization is so important, why weakly informative priors are usually a good starting point, and why the prior predictive check is an almost mandatory step before fitting a model.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; If you set the prior for the slope too wide, the model may implicitly allow crazy regression lines that domain knowledge immediately calls absurd. A prior for regression is not “fill in anything to complete the model”, but a way to keep the model grounded.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Why can the same prior look reasonable on one scale but absurd on another?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-principled-prior-specification-for-regression&quot;&gt;Key ideas: Principled Prior Specification for Regression&lt;/h2&gt;

&lt;h3 id=&quot;1-standardization-z-scoring-as-a-universal-scale&quot;&gt;1. Standardization (Z-Scoring) as a Universal Scale&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Transforming predictors and outcomes via \(x_z = (x - \bar{x})/s_x\) and \(y_z = (y - \bar{y})/s_y\) before specifying priors.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Making parameters dimensionless (\(\beta_z\) is now “SDs of \(y\) per 1 SD of \(x\)”), decoupling the intercept from the slope, and dramatically improving MCMC geometry.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-weakly-informative-priors-regularizing-without-dogma&quot;&gt;2. Weakly Informative Priors (Regularizing Without Dogma)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Priors broad enough to accommodate every scientifically plausible effect (e.g., \(\beta_z \sim \mathrm{Normal}(0, 1)\)) yet tight enough to rule out physically impossible nonsense.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Stabilizing inference on small or noisy datasets while letting moderate-to-large datasets speak freely.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-prior-predictive-checks-simulating-before-seeing-data&quot;&gt;3. Prior Predictive Checks (Simulating Before Seeing Data)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Drawing parameters \((\alpha^{(s)}, \beta^{(s)}, \sigma^{(s)})\) from the prior &lt;em&gt;alone&lt;/em&gt; and plotting the implied regression lines \(\mu^{(s)}(x)\) in observable data units.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Translating abstract parameter numbers into concrete observable consequences so domain knowledge can immediately catch absurd priors.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;explanation-why-normal0-100-is-not-uninformative&quot;&gt;Explanation: Why &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Normal(0, 100)&lt;/code&gt; Is Not “Uninformative”&lt;/h2&gt;

&lt;p&gt;Suppose you model adult weight (\(\bar{y} = 65\text{ kg},\, s_y = 10\text{ kg}\)) from height (\(\bar{x} = 170\text{ cm},\, s_x = 7\text{ cm}\)) on standardized scales \(x_z, y_z\). Compare two candidate priors on the standardized slope \(\beta_z\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Prior on \(\beta_z\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;95% Prior Interval for \(\beta_z\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Implied weight shift per \(+1\text{ SD}\) (\(+7\text{ cm}\)) height&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Scientific verdict&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;“Flat” \(\mathrm{Normal}(0, 100^2)\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([-196,\; +196]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\pm 196 \times 10 = \mathbf{\pm 1{,}960\text{ kg}}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Predicts humans weighing as much as a car—wildly implausible!&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Weakly informative \(\mathrm{Normal}(0, 1^2)\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\([-1.96,\; +1.96]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\pm 1.96 \times 10 = \mathbf{\pm 19.6\text{ kg}}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Covers flat, strong positive, and even negative slopes within physical reality&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Even more striking: under \(\mathrm{Normal}(0, 100^2)\), the probability that \(\vert \beta_z \vert &amp;gt; 5\) (meaning a \(7\text{ cm}\) height difference shifts weight by more than \(50\text{ kg}\)) is \(2\Phi(-5/100) \approx \mathbf{96\%}\)! Far from being “neutral,” a flat prior puts 96% of its mass on impossible relationships.&lt;/p&gt;

&lt;h2 id=&quot;1-what-makes-choosing-priors-for-regression-hard&quot;&gt;1. What makes choosing priors for regression hard?&lt;/h2&gt;

&lt;p&gt;In regression, we usually have at least three kinds of parameters: the intercept \(\alpha\), the slope \(\beta\), and the noise \(\sigma\). If we are not careful, a prior can be too wide and allow absurd values, too narrow and distort the posterior, or simply make the sampler run harder than necessary.&lt;/p&gt;

&lt;p&gt;This is why choosing priors for regression is both a statistical matter and a matter of understanding the scale and context of the data.&lt;/p&gt;

&lt;h2 id=&quot;2-standardization-a-step-well-worth-doing-before-thinking-about-priors&quot;&gt;2. Standardization: a step well worth doing before thinking about priors&lt;/h2&gt;

&lt;p&gt;One of the simplest ways to make prior selection easier is to standardize the data. For example, we can write:&lt;/p&gt;

\[x_{std} = \frac{x-\bar{x}}{\mathrm{SD}(x)}, \qquad
y_{std} = \frac{y-\bar{y}}{\mathrm{SD}(y)}.\]

&lt;p&gt;After this step, the variable has a mean close to 0 and a standard deviation close to 1, and therefore “standard” priors also become much easier to choose.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_standardization_raw_data.png&quot; alt=&quot;Data on the original scale before standardizing&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_standardization_standardized_data.png&quot; alt=&quot;Data after standardizing to mean 0 and SD 1&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;why-does-standardization-help-so-much&quot;&gt;Why does standardization help so much?&lt;/h3&gt;

&lt;h4 id=&quot;1-the-intercept-is-easier-to-interpret&quot;&gt;1. The intercept is easier to interpret&lt;/h4&gt;

&lt;p&gt;After centering or standardizing, the intercept is usually close to the mean of \(y\) at the central level of \(x\), so interpreting it becomes more natural.&lt;/p&gt;

&lt;h4 id=&quot;2-the-prior-no-longer-depends-too-strongly-on-the-measurement-unit&quot;&gt;2. The prior no longer depends too strongly on the measurement unit&lt;/h4&gt;

&lt;p&gt;For example, cm versus m, or kg versus pounds, can make a prior that “reads the same” mean something completely different if you do not standardize.&lt;/p&gt;

&lt;h4 id=&quot;3-the-sampler-usually-runs-more-smoothly&quot;&gt;3. The sampler usually runs more smoothly&lt;/h4&gt;

&lt;p&gt;When the variables are on relatively similar scales, the posterior is usually friendlier to HMC/NUTS, the Hamiltonian sampling algorithms commonly used in modern Bayes.&lt;/p&gt;

&lt;h3 id=&quot;21-a-concrete-example-the-same-prior-before-and-after-standardizing&quot;&gt;2.1. A concrete example: the same prior before and after standardizing&lt;/h3&gt;

&lt;p&gt;Suppose \(x\) is height in cm, mostly in the range 150 to 190, and \(y\) is weight in kg, around 45 to 90.&lt;/p&gt;

&lt;p&gt;If you have not standardized and set directly:&lt;/p&gt;

\[\alpha \sim \mathcal{N}(0,1), \qquad \beta \sim \mathcal{N}(0,1),\]

&lt;p&gt;then these two priors sound “nice” but are actually hard to accept semantically.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The prior \(\alpha \sim \mathcal{N}(0,1)\) implicitly says that when \(x=0\) cm, the average weight will be around 0 kg, which is clearly meaningless in the height - weight context.&lt;/li&gt;
  &lt;li&gt;The prior \(\beta \sim \mathcal{N}(0,1)\) has an approximate 95% range from \(-2\) to \(2\) kg/cm. That means that with just a 20 cm difference in height, the model is already ready to accept an average difference from \(-40\) to \(40\) kg, which is usually too wide for many practical problems.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But if you standardize both \(x\) and \(y\) into \(x_{std}, y_{std}\) and only then set:&lt;/p&gt;

\[\alpha \sim \mathcal{N}(0,1), \qquad \beta \sim \mathcal{N}(0,1),\]

&lt;p&gt;then the meaning changes completely:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\alpha\) around 0 now means that the mean value of \(y\) at the central level of \(x\) also lies around the data mean, which is very natural.&lt;/li&gt;
  &lt;li&gt;\(\beta\) around 0 with standard deviation 1 now means that when \(x\) increases by 1 standard deviation, \(y\) typically changes within a region of a few standard deviations, i.e. still flexible enough but no longer “flying off the ground”.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is why standardization is not just a technical trick. It turns a prior from something hard to understand into a statement that can be read intuitively.&lt;/p&gt;

&lt;h2 id=&quot;3-prior-for-the-intercept-alpha&quot;&gt;3. Prior for the intercept \(\alpha\)&lt;/h2&gt;

&lt;p&gt;After standardizing, the intercept should usually lie around 0 with moderate uncertainty. So a prior such as:&lt;/p&gt;

\[\alpha \sim \mathcal{N}(0,1)\]

&lt;p&gt;or&lt;/p&gt;

\[\alpha \sim \mathcal{N}(0,2)\]

&lt;p&gt;is usually a reasonable start.&lt;/p&gt;

&lt;p&gt;The three contrasting situations below show that the prior for the intercept can be too wide, moderate, or too narrow.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_intercept_too_wide.png&quot; alt=&quot;A prior that is too wide for the intercept&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_intercept_weakly_informative.png&quot; alt=&quot;Prior weakly informative cho intercept&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_intercept_too_narrow.png&quot; alt=&quot;A prior that is too narrow for the intercept&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The intuition here is fairly simple: a prior that is too wide allows unrealistic values, a prior that is too narrow forces the model too hard, while a moderate prior keeps regularization yet remains flexible enough to let the data speak.&lt;/p&gt;

&lt;h2 id=&quot;4-prior-for-the-slope-beta&quot;&gt;4. Prior for the slope \(\beta\)&lt;/h2&gt;

&lt;p&gt;After standardization, the slope has a very clear meaning: when \(x\) increases by 1 standard deviation, by how many standard deviations does \(y\) change on average.&lt;/p&gt;

&lt;p&gt;Then a prior such as:&lt;/p&gt;

\[\beta \sim \mathcal{N}(0,1)\]

&lt;p&gt;is usually quite reasonable for many problems.&lt;/p&gt;

&lt;p&gt;This prior says that we expect the slope not to be too extreme, but still leave it open to both positive and negative effects.&lt;/p&gt;

&lt;p&gt;If you have no strong prior knowledge, this is a very good weakly informative choice.&lt;/p&gt;

&lt;p&gt;The three choices below help you see clearly the difference between a prior that is too wide, weakly informative, and too narrow for the slope.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_slope_too_wide.png&quot; alt=&quot;A prior that is too wide for the slope&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_slope_weakly_informative.png&quot; alt=&quot;Prior weakly informative cho slope&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_slope_too_narrow.png&quot; alt=&quot;A prior that is too narrow for the slope&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;5-prior-for-the-noise-sigma&quot;&gt;5. Prior for the noise \(\sigma\)&lt;/h2&gt;

&lt;p&gt;Because \(\sigma &amp;gt; 0\), we usually use positive priors such as HalfNormal, Exponential, or sometimes HalfStudentT.&lt;/p&gt;

&lt;p&gt;A common choice after standardization is:&lt;/p&gt;

\[\sigma \sim \mathrm{HalfNormal}(1).\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_noise_halfnormal_curve.png&quot; alt=&quot;HalfNormal prior curve for the noise sigma&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The intuition here is that we expect the noise to be moderate, but still want to leave the model enough room to accept noisier data if that is actually observed.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_noise_halfnormal_summary.png&quot; alt=&quot;Summary of how to read the prior for the noise sigma&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-what-are-weakly-informative-priors-and-why-should-we-usually-start-there&quot;&gt;6. What are weakly informative priors, and why should we usually start there?&lt;/h2&gt;

&lt;p&gt;A weakly informative prior does not mean “I know nothing”. What it really means is that I do not want to impose a very strong belief, but I still want to remove absurd values that domain knowledge can reject right from the start.&lt;/p&gt;

&lt;p&gt;In regression, this is a very useful way to regularize the model, making the posterior more stable and keeping the sampler from being pulled into meaningless regions of parameter space.&lt;/p&gt;

&lt;h2 id=&quot;7-prior-predictive-check-the-most-important-step-of-this-lesson&quot;&gt;7. Prior predictive check: the most important step of this lesson&lt;/h2&gt;

&lt;p&gt;If you only look at the prior on the parameters, it is often hard to know whether it is reasonable. But if you use that prior to generate simulated data, everything becomes very clear.&lt;/p&gt;

&lt;p&gt;The idea is to draw \(\alpha,\beta,\sigma\) from the prior, generate many fake regression lines from those draws, and then see whether those lines produce data that is realistic in practical terms.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_predictive_weakly_informative.png&quot; alt=&quot;Prior predictive with a weakly informative slope&quot; /&gt;&lt;/p&gt;

&lt;p&gt;For example, if the prior for the slope yields absurdly steep lines, or generates predictions such as negative weight, exam scores of 300 points, or absurdly explosive revenue growth, then the prior has a problem, even though mathematically it is “valid”.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_predictive_too_wide.png&quot; alt=&quot;Prior predictive with a slope that is too wide&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;8-an-intuitive-example-advertising-and-revenue&quot;&gt;8. An intuitive example: advertising and revenue&lt;/h2&gt;

&lt;p&gt;Suppose you model \(x\) as advertising cost and \(y\) as revenue. If the prior for the slope is too wide, the model may implicitly accept that a tiny increase in budget makes revenue explode absurdly, or conversely, that a slight increase in advertising makes revenue collapse very sharply.&lt;/p&gt;

&lt;p&gt;Before looking at the data, you already know that many of those scenarios are unrealistic. The prior needs to reflect that.&lt;/p&gt;

&lt;h3 id=&quot;81-how-is-the-prior-predictive-read-in-numbers&quot;&gt;8.1. How is the prior predictive read in numbers?&lt;/h3&gt;

&lt;p&gt;Suppose you have standardized the advertising and revenue data, and you are deciding between two priors for the slope:&lt;/p&gt;

\[\beta \sim \mathcal{N}(0,3)\]

&lt;p&gt;or&lt;/p&gt;

\[\beta \sim \mathcal{N}(0,0.5).\]

&lt;p&gt;With the first prior, the 95% interval for \(\beta\) is approximately \([-6,6]\). If a new campaign sits at \(x_{std}=2\), i.e. 2 standard deviations above the mean, then the predicted mean alone:&lt;/p&gt;

\[\mu = \alpha + \beta x_{std}\]

&lt;p&gt;can already be pulled into a region of about \(-12\) to \(12\) standard deviations of \(y\), before even adding noise. For many business problems, this is a sign of being so wide as to be unrealistic.&lt;/p&gt;

&lt;p&gt;By contrast, with&lt;/p&gt;

\[\beta \sim \mathcal{N}(0,0.5),\]

&lt;p&gt;the 95% interval for the slope is only about \([-1,1]\). At the same level \(x_{std}=2\), the model mainly allows the predicted mean to lie in a region of about \(-2\) to \(2\) standard deviations around the center. That is still a sufficiently open space, but much closer to practical intuition.&lt;/p&gt;

&lt;p&gt;This example shows why the prior predictive check is stronger than just looking at the prior plot over the parameters: it forces us to read the prior in the language of the data the model will generate.&lt;/p&gt;

&lt;h2 id=&quot;9-prior-sensitivity-analysis&quot;&gt;9. Prior sensitivity analysis&lt;/h2&gt;

&lt;p&gt;After fitting the model, a very worthwhile question to ask is: &lt;strong&gt;If I change to another reasonable prior a little, does the posterior change a lot?&lt;/strong&gt; If the posterior changes strongly, that may signal that the data is not strong enough, the prior is influencing the result considerably, and so you need to be more transparent when reporting conclusions.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_sensitivity_posterior_overlay.png&quot; alt=&quot;Posterior when changing different reasonable priors&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Sensitivity analysis is not meant to find an “absolutely correct” prior. Its goal is to understand how much your conclusions depend on the prior.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_prior_sensitivity_summary.png&quot; alt=&quot;Summary of how to read prior sensitivity analysis&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;10-a-very-practical-set-of-starting-priors&quot;&gt;10. A very practical set of starting priors&lt;/h2&gt;

&lt;p&gt;With standardized data, a good set of starting priors for simple linear regression is usually:&lt;/p&gt;

\[\alpha \sim \mathcal{N}(0,1)\]

\[\beta \sim \mathcal{N}(0,1)\]

\[\sigma \sim \mathrm{HalfNormal}(1)\]

&lt;p&gt;This is not a fixed truth for every problem, but it is a very healthy default to start from.&lt;/p&gt;

&lt;h2 id=&quot;11-common-mistakes-when-choosing-priors-for-regression&quot;&gt;11. Common mistakes when choosing priors for regression&lt;/h2&gt;

&lt;h3 id=&quot;111-choosing-a-prior-without-looking-at-the-data-scale&quot;&gt;11.1. Choosing a prior without looking at the data scale&lt;/h3&gt;

&lt;p&gt;This is a very common error.&lt;/p&gt;

&lt;h3 id=&quot;112-using-an-extremely-wide-prior-and-calling-it-non-informative&quot;&gt;11.2. Using an extremely wide prior and calling it “non-informative”&lt;/h3&gt;

&lt;p&gt;A prior that is too wide often has bad consequences such as difficult sampling, absurd prior predictives, and a posterior that is harder to read.&lt;/p&gt;

&lt;h3 id=&quot;113-not-doing-a-prior-predictive-check&quot;&gt;11.3. Not doing a prior predictive check&lt;/h3&gt;

&lt;p&gt;This throws away an extremely powerful check.&lt;/p&gt;

&lt;h3 id=&quot;114-not-checking-sensitivity&quot;&gt;11.4. Not checking sensitivity&lt;/h3&gt;

&lt;p&gt;A prior that looks reasonable should still be challenged with a few neighboring choices.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; Standardization is usually the best step to make priors for regression easier to choose and interpret; weakly informative priors help remove absurd values while still letting the data speak strongly; and the prior predictive check together with sensitivity analysis are two important tools for evaluating priors in regression.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Bayesian Priors Explained&lt;/td&gt;
          &lt;td&gt;Prior Modelling &amp;amp; Prior Predictive Checks](https://www.youtube.com/watch?v=G3ludfAUAng) — stats 4 good, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch how a prior is stated and then checked with a prior predictive, exactly the habit the lesson wants when choosing priors for regression.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=UH6-9FU6bRg&quot;&gt;Keynote 2: Weakly Informative Priors – Andrew Gelman&lt;/a&gt; — AISTATS 2014, English. Watch the argument for weakly informative priors, supporting the part of the lesson that takes a weakly informative prior as the starting point.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=RTFnrK5ZZ8E&quot;&gt;Standardized variables in a simple regression&lt;/a&gt; — Jos Dornschneider-Elkink, English. Watch how the coefficient changes meaning after standardizing variables, used for the part that explains why standardization comes before setting a prior.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why does standardization make prior selection easier?&lt;/li&gt;
  &lt;li&gt;Explain in words what a weakly informative prior for the slope is saying.&lt;/li&gt;
  &lt;li&gt;What does the prior predictive check test that looking at the prior over the parameters may not show us?&lt;/li&gt;
  &lt;li&gt;In one of your own regression problems, which parameter is where the prior needs the most careful choice?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., Simpson, D., &amp;amp; Betancourt, M. (2017). The prior can often only be understood in the context of the likelihood.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 4.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Regression and Other Stories&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter04/04_03_posterior_inference_pymc/&quot;&gt;4.3 Posterior Inference with PyMC - From Theory to Practice&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 4.1: Bayesian Linear Regression - A Generative Model</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_01_linear_regression_generative/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter04/04_01_linear_regression_generative</id>
   <content type="html">&lt;p&gt;In an introductory statistics class, linear regression is often reduced to a geometric chore: drop a single straight line through a cloud of dots by minimizing squared vertical errors. Yet the moment you ask &lt;em&gt;“How confident should I be in a prediction for someone 195 cm tall?”&lt;/em&gt; or &lt;em&gt;“Could this data realistically have come from a flat line?”&lt;/em&gt;, a single best-fit line falls silent. Bayesian linear regression flips the script completely: instead of hunting for one line, we write down a &lt;strong&gt;generative story&lt;/strong&gt; for how the data came to be, and let Bayes’ rule hand us an entire probability distribution of plausible lines.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lesson Roadmap:&lt;/strong&gt; From one OLS line to a full generative model → Key ideas (Generative likelihoods, Posterior over parameters, Epistemic vs. Aleatoric uncertainty) → Hand-worked exact Bayesian regression on 4 points → Full model specification, real examples, and exercises.&lt;/p&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to see Bayesian linear regression as a &lt;strong&gt;data-generating story&lt;/strong&gt;, not just the problem of “fitting a straight line”. You also need to understand the roles of the intercept, slope, and noise in the model, and why Bayesian regression always keeps the uncertainty of both the parameters and the predictions.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; You want to describe the relationship between height and weight. The old view is “find the best straight line”. The Bayesian view is “each person’s weight is generated around an average trend, and we are not certain about that trend”.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Why shouldn’t Bayesian-style regression be understood simply as finding a single straight line?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-the-architecture-of-bayesian-linear-regression&quot;&gt;Key ideas: The Architecture of Bayesian Linear Regression&lt;/h2&gt;

&lt;h3 id=&quot;1-generative-modeling-forward-data-generating-process&quot;&gt;1. Generative Modeling (Forward Data-Generating Process)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Specifying a complete probability machine \(y_i \sim \mathrm{Normal}(\mu_i, \sigma)\), \(\mu_i = \alpha + \beta x_i\), together with prior distributions on \((\alpha, \beta, \sigma)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; How parameters generate synthetic datasets &lt;em&gt;before&lt;/em&gt; seeing data (prior predictive simulation) and &lt;em&gt;after&lt;/em&gt; updating (posterior predictive simulation), turning regression from curve-fitting into scientific modeling.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-joint-posterior-distribution-over-alpha-beta-sigma&quot;&gt;2. Joint Posterior Distribution over \((\alpha, \beta, \sigma)\)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Applying Bayes’ rule \(p(\alpha, \beta, \sigma \mid x, y) \propto \prod_{i=1}^n \mathrm{Normal}(y_i \mid \alpha + \beta x_i, \sigma)\, p(\alpha, \beta, \sigma)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Quantifying parameter uncertainty and correlation (for example, why uncentered \(x\) creates a strong negative correlation between intercept \(\alpha\) and slope \(\beta\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-two-distinct-sources-of-predictive-uncertainty&quot;&gt;3. Two Distinct Sources of Predictive Uncertainty&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Decomposing total predictive variance \(\mathrm{Var}(y^* \mid x^*, D) = \underbrace{\sigma^2}_{\text{aleatoric}} + \underbrace{\mathrm{Var}(\alpha + \beta x^* \mid D)}_{\text{epistemic}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Separating irreducible observation noise (\(\sigma^2\), which never shrinks even with infinite data) from parameter uncertainty (which shrinks as \(1/n\) and flares outward as \(x^*\) moves away from \(\bar{x}\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;explanation-exact-bayesian-slope--prediction-on-4-points&quot;&gt;Explanation: Exact Bayesian Slope &amp;amp; Prediction on 4 Points&lt;/h2&gt;

&lt;p&gt;Consider 4 centered observations: \(x = [-2, -1, 1, 2]\) (so \(\sum x_i = 0\) and \(\sum x_i^2 = 10\)) and \(y = [1, 3, 7, 9]\) (so \(\bar{y} = 5\) and \(\sum x_i y_i = -2 - 3 + 7 + 18 = 20\)). Assume known observation noise \(\sigma = 1\), known intercept \(\alpha = 5\), and a Gaussian prior on the slope \(\beta \sim \mathrm{Normal}(0, 1^2)\) (prior precision \(1/\tau_0^2 = 1\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;OLS slope:&lt;/strong&gt; \(\hat{\beta}_{\text{OLS}} = \frac{\sum x_i y_i}{\sum x_i^2} = \frac{20}{10} = \mathbf{2.00}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian posterior precision &amp;amp; variance:&lt;/strong&gt; Precision adds cleanly:
\(\frac{1}{\tau_n^2} = \frac{1}{\tau_0^2} + \frac{\sum x_i^2}{\sigma^2} = 1 + \frac{10}{1} = 11 \implies \tau_n^2 = \frac{1}{11} \approx 0.0909 \quad (\tau_n \approx 0.302).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian posterior mean:&lt;/strong&gt; Precision-weighted average of prior mean (\(0\)) and OLS estimate (\(2.00\)):
\(\mu_n = \frac{1 \cdot 0 + 10 \cdot 2.00}{11} = \frac{20}{11} \approx \mathbf{1.818}.\)
Notice how the prior gently shrinks \(2.00 \to 1.818\) (exact Ridge / L2 regularization!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Predicting a new point at \(x^* = 3\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Predictive mean: \(\mathbb{E}[y^* \mid x^* = 3, D] = 5 + 1.818(3) = \mathbf{10.45}\).&lt;/li&gt;
      &lt;li&gt;Predictive variance: \(\mathrm{Var}(y^*) = \underbrace{1.000}_{\sigma^2 \text{ (noise)}} + \underbrace{3^2 \cdot \frac{1}{11}}_{\text{slope uncertainty}} = 1 + 0.818 = \mathbf{1.818} \implies \text{SD} \approx \mathbf{1.348}.\)
Far from the center (\(x^* = 3\)), epistemic uncertainty nearly doubles the variance compared to noise alone!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;1-regression-is-not-just-drawing-a-straight-line&quot;&gt;1. Regression is not just drawing a straight line&lt;/h2&gt;

&lt;p&gt;When first learning regression, many people are taught that you just choose a line \(y = \alpha + \beta x\) and then find the line that minimizes the squared error.&lt;/p&gt;

&lt;p&gt;That approach is useful, but it easily makes us think regression is just a geometric fitting technique.&lt;/p&gt;

&lt;p&gt;In Bayesian regression, we look deeper and force ourselves to ask where the data comes from, why the points do not lie exactly on a line, and how uncertain we are about the parameters of that line itself.&lt;/p&gt;

&lt;h2 id=&quot;2-the-data-generating-story-of-linear-regression&quot;&gt;2. The data-generating story of linear regression&lt;/h2&gt;

&lt;p&gt;Suppose we want to model the relationship between height \(x\) and weight \(y\).&lt;/p&gt;

&lt;p&gt;The data-generating story can be told as follows.&lt;/p&gt;

&lt;h3 id=&quot;step-1-there-is-an-average-trend&quot;&gt;Step 1. There is an average trend&lt;/h3&gt;

&lt;p&gt;Taller people are usually heavier. We describe that trend by:&lt;/p&gt;

\[\mu_i = \alpha + \beta x_i.\]

&lt;p&gt;Here \(\alpha\) is the intercept and \(\beta\) is the slope.&lt;/p&gt;

&lt;h3 id=&quot;step-2-each-individual-fluctuates-around-that-trend&quot;&gt;Step 2. Each individual fluctuates around that trend&lt;/h3&gt;

&lt;p&gt;Nobody lies exactly on the average line, because there are many other factors such as muscle mass, diet, sex, activity level, or measurement error.&lt;/p&gt;

&lt;p&gt;So we write:&lt;/p&gt;

\[y_i \sim \mathcal{N}(\mu_i,\sigma).\]

&lt;p&gt;Here \(\sigma\) is the noise around the regression line.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_regression_data_generating_process.png&quot; alt=&quot;The data-generating process of regression&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_regression_distribution_fixed_height.png&quot; alt=&quot;Distribution of weight at a fixed height&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;step-3-we-do-not-know-the-parameters-exactly&quot;&gt;Step 3. We do not know the parameters exactly&lt;/h3&gt;

&lt;p&gt;We do not really know what the intercept is, what the slope is, and what the noise is.&lt;/p&gt;

&lt;p&gt;So we place priors on them, and then use the data to infer the posterior.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_regression_story_summary.png&quot; alt=&quot;Summary of the regression generative story&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-three-parameters-to-understand-firmly&quot;&gt;3. Three parameters to understand firmly&lt;/h2&gt;

&lt;h3 id=&quot;31-intercept-alpha&quot;&gt;3.1. Intercept \(\alpha\)&lt;/h3&gt;

&lt;p&gt;The intercept is the mean value of \(y\) when \(x = 0\).&lt;/p&gt;

&lt;p&gt;Mathematically, it is very convenient. But in practical terms, it is not always easy to interpret.&lt;/p&gt;

&lt;p&gt;For example, if \(x\) is height in cm, then \(x=0\) has almost no practical meaning.&lt;/p&gt;

&lt;p&gt;That is why in Bayesian regression we often center or standardize the input variable so that the intercept has a more readable meaning.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_intercept_after_centering.png&quot; alt=&quot;Intercept after centering the input variable&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;32-slope-beta&quot;&gt;3.2. Slope \(\beta\)&lt;/h3&gt;

&lt;p&gt;The slope tells how much the mean of \(y\) changes when \(x\) increases by 1 unit.&lt;/p&gt;

&lt;p&gt;For example, if \(\beta = 0.7\) kg/cm, then each cm of height corresponds to an average increase of 0.7 kg in weight.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_slope_interpretation.png&quot; alt=&quot;Interpreting the slope in linear regression&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;33-noise-sigma&quot;&gt;3.3. Noise \(\sigma\)&lt;/h3&gt;

&lt;p&gt;Noise tells how widely the data points are spread around the regression line. If \(\sigma\) is small, the data hug the line more closely, while if \(\sigma\) is large, the data are more widely dispersed.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_noise_interpretation.png&quot; alt=&quot;Interpreting noise around the regression line&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;4-how-does-bayesian-regression-differ-from-ols&quot;&gt;4. How does Bayesian regression differ from OLS?&lt;/h2&gt;

&lt;h3 id=&quot;what-ols-usually-answers&quot;&gt;What OLS usually answers&lt;/h3&gt;

&lt;p&gt;OLS (ordinary least squares) usually answers the question of what the “best” line is under a certain optimization criterion.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_frequentist_point_estimate.png&quot; alt=&quot;The OLS point-estimate view&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;what-bayesian-regression-answers&quot;&gt;What Bayesian regression answers&lt;/h3&gt;

&lt;p&gt;Bayesian regression answers a much broader question: which lines remain plausible after seeing the data, how large the uncertainty of the slope and intercept is, and how uncertain the prediction for a new observation will be. In other words, OLS gives you a central line, while Bayes gives you a &lt;strong&gt;distribution of possible lines&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_bayesian_uncertainty_quantification.png&quot; alt=&quot;The uncertainty view of Bayesian regression&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;41-classical-assumptions-to-state-clearly-before-bayesian-inference&quot;&gt;4.1. Classical assumptions to state clearly before Bayesian inference&lt;/h3&gt;

&lt;p&gt;Before moving on to the posterior, we should state clearly the underlying assumptions of linear regression:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the mean relationship is linear in the parameters,&lt;/li&gt;
  &lt;li&gt;the errors have expected value 0,&lt;/li&gt;
  &lt;li&gt;the errors are conditionally independent given the input variable,&lt;/li&gt;
  &lt;li&gt;the error variance is stable (homoscedastic) in the basic model,&lt;/li&gt;
  &lt;li&gt;in the simplest version, the errors are usually assumed Normal.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Bayes does not “erase” these assumptions; Bayes only adds a layer of uncertainty for the parameters and lets us check the assumptions more transparently at the model checking step.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter04/chapter04_regression_residual_distribution.png&quot; alt=&quot;Residual distribution around the regression line&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;experiment-the-regression-posterior-is-a-whole-bundle-of-lines&quot;&gt;Experiment: the regression posterior is a whole bundle of lines&lt;/h3&gt;

&lt;p&gt;Add data points one at a time and watch the bundle of plausible lines narrow; compare with OLS and the true line.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;regression-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;5-why-is-generative-such-an-important-word&quot;&gt;5. Why is “generative” such an important word?&lt;/h2&gt;

&lt;p&gt;If you view regression as a generative model, you will ask the right questions: what process was the data generated from, is the Normal assumption for the residuals reasonable, is the noise homogeneous across all values of \(x\), and does this model really produce data that looks like the real data.&lt;/p&gt;

&lt;p&gt;This is a very important difference between the attitude of “once it is fitted, we are done” and the attitude of “model it and then check”.&lt;/p&gt;

&lt;h2 id=&quot;6-writing-out-the-full-bayesian-model&quot;&gt;6. Writing out the full Bayesian model&lt;/h2&gt;

&lt;p&gt;A minimal Bayesian linear regression has the form:&lt;/p&gt;

\[\alpha \sim p(\alpha)\]

\[\beta \sim p(\beta)\]

\[\sigma \sim p(\sigma)\]

\[y_i \sim \mathcal{N}(\alpha + \beta x_i,\sigma)\]

&lt;p&gt;From there we derive the posterior:&lt;/p&gt;

\[p(\alpha,\beta,\sigma \mid x,y).\]

&lt;p&gt;What matters is not memorizing this formula, but understanding what the prior says before the data, where the likelihood says the data comes from, and that the posterior is the answer that appears after the two are combined.&lt;/p&gt;

&lt;h3 id=&quot;61-the-joint-likelihood---prior---posterior-framework-for-regression&quot;&gt;6.1. The joint likelihood - prior - posterior framework for regression&lt;/h3&gt;

&lt;p&gt;With data \(\mathcal D=\{(x_i,y_i)\}_{i=1}^n\), we have:&lt;/p&gt;

\[p(y\mid X,\alpha,\beta,\sigma)=\prod_{i=1}^n \mathcal N(y_i\mid \alpha+\beta x_i,\sigma).\]

&lt;p&gt;Joint prior (if we assume prior independence):&lt;/p&gt;

\[p(\alpha,\beta,\sigma)=p(\alpha)p(\beta)p(\sigma).\]

&lt;p&gt;Hence:&lt;/p&gt;

\[p(\alpha,\beta,\sigma\mid X,y)
\propto p(y\mid X,\alpha,\beta,\sigma)\,p(\alpha,\beta,\sigma).\]

&lt;p&gt;This is the unified view of this chapter: every inference about regression parameters starts from a clearly stated joint model.&lt;/p&gt;

&lt;h3 id=&quot;62-interval-for-the-slope-known-variance-and-unknown-variance&quot;&gt;6.2. Interval for the slope: known variance and unknown variance&lt;/h3&gt;

&lt;p&gt;When the noise variance is treated as known, the posterior of the slope is usually close to Normal and the posterior interval for \(\beta\) reads as:&lt;/p&gt;

\[\mu_{\beta\mid D}\pm z_{0.975}\,\sigma_{\beta\mid D}.\]

&lt;p&gt;When the variance is unknown and inferred together with the data, the posterior of \(\beta\) usually has heavier tails (in practice close to Student-t), so the posterior interval is usually wider to reflect the additional uncertainty.&lt;/p&gt;

&lt;p&gt;So when reporting “the interval of the slope”, you need to state clearly whether you are in the known-variance or unknown-variance setting.&lt;/p&gt;

&lt;h2 id=&quot;7-another-real-example-beyond-height---weight&quot;&gt;7. Another real example beyond height - weight&lt;/h2&gt;

&lt;p&gt;Bayesian regression appears in many places:&lt;/p&gt;

&lt;h3 id=&quot;house-price-and-area&quot;&gt;House price and area&lt;/h3&gt;

&lt;p&gt;Here \(x\) may be the area and \(y\) the house price.&lt;/p&gt;

&lt;h3 id=&quot;exam-score-and-study-hours&quot;&gt;Exam score and study hours&lt;/h3&gt;

&lt;p&gt;Here \(x\) may be the number of revision hours and \(y\) the exam score.&lt;/p&gt;

&lt;h3 id=&quot;revenue-and-advertising-cost&quot;&gt;Revenue and advertising cost&lt;/h3&gt;

&lt;p&gt;Here \(x\) may be the advertising budget and \(y\) the revenue.&lt;/p&gt;

&lt;p&gt;In all of those examples, the generative thinking is still the same: there is an average trend, the real data fluctuates around that trend, and we are still uncertain about the very parameters that control the trend.&lt;/p&gt;

&lt;h2 id=&quot;8-how-does-bayesian-regression-make-predictions&quot;&gt;8. How does Bayesian regression make predictions?&lt;/h2&gt;

&lt;p&gt;Suppose you want to predict the weight of a person who is 175 cm tall.&lt;/p&gt;

&lt;p&gt;Bayesian regression does not give just a single number. It gives a predicted mean value, uncertainty from not being sure about \(\alpha\) and \(\beta\), and also the uncertainty from the individual noise \(\sigma\).&lt;/p&gt;

&lt;p&gt;This is a very strong point: we not only predict, but also know how confident we should be in that prediction.&lt;/p&gt;

&lt;h3 id=&quot;81-a-concrete-example-predicting-weight-at-175-cm&quot;&gt;8.1. A concrete example: predicting weight at 175 cm&lt;/h3&gt;

&lt;p&gt;Suppose that after fitting the model on height - weight data, our posterior shows the following typical values:&lt;/p&gt;

\[\alpha \approx -55,\qquad \beta \approx 0.75,\qquad \sigma \approx 6.\]

&lt;p&gt;We can understand these three numbers in everyday language as follows:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;an intercept of about \(-55\) helps determine the position of the average line,&lt;/li&gt;
  &lt;li&gt;a slope of about \(0.75\) means that 1 cm taller raises the average weight by about 0.75 kg,&lt;/li&gt;
  &lt;li&gt;noise of about \(6\) kg means that even at the same height, the actual weight of each person still fluctuates quite considerably around the mean.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For a new person with height \(x_{\text{new}}=175\), the model’s predicted mean is:&lt;/p&gt;

\[\mu_{\text{new}} = \alpha + \beta x_{\text{new}}
\approx -55 + 0.75 \times 175 = 76.25.\]

&lt;p&gt;If we look at only one representative set of parameters, we can say: “for a person 175 cm tall, the reasonable average weight under the model is about 76.25 kg”. But Bayesian regression does not stop there, because it does not pretend that \(\alpha\) and \(\beta\) are known exactly.&lt;/p&gt;

&lt;p&gt;Imagine the posterior gives us a few parameter samples as follows:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Posterior sample&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(\alpha\)&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(\beta\)&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(\sigma\)&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(\mu_{\text{new}} = \alpha + \beta \cdot 175\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;-52&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.73&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;5.8&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;75.75&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;-58&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.77&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6.1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;76.75&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;-50&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.72&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;5.5&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;76.00&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;-57&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.76&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6.4&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;76.00&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;This table shows a very important idea: even before accounting for individual noise, merely being uncertain about the intercept and slope already produces a &lt;strong&gt;distribution of the predicted mean value&lt;/strong&gt;. In other words, the model does not say “it is certainly 76.25 kg”, but “the plausible region for the mean at a height of 175 cm lies around 75 to 77 kg”.&lt;/p&gt;

&lt;p&gt;This is where we need to separate two different questions very clearly:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Question 1.&lt;/strong&gt; What is the average weight of people who are 175 cm tall?&lt;/p&gt;

&lt;p&gt;This question targets \(\mu_{\text{new}}\). If we draw many samples from the posterior and compute \(\mu_{\text{new}}\) for each one, we get a posterior distribution for the mean value. Suppose that after this step we obtain an approximate 89% posterior interval:&lt;/p&gt;

\[\mu_{\text{new}} \in [74,\ 78.5]\ \text{kg}.\]

&lt;p&gt;This interval reflects &lt;strong&gt;parameter uncertainty&lt;/strong&gt;: we do not know exactly where the regression line lies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Question 2.&lt;/strong&gt; How much will one specific individual who is 175 cm tall weigh?&lt;/p&gt;

&lt;p&gt;This question is harder, because besides parameter uncertainty there is also individual fluctuation around the average line. We must then use the posterior predictive distribution:&lt;/p&gt;

\[y_{\text{new}} \sim \mathcal{N}(\mu_{\text{new}}, \sigma).\]

&lt;p&gt;If we keep propagating both the uncertainty of \(\alpha,\beta,\sigma\) and this new noise, we can obtain a wider 89% prediction interval, for example:&lt;/p&gt;

\[y_{\text{new}} \in [66,\ 87]\ \text{kg}.\]

&lt;p&gt;This interval is much wider than the one for \(\mu_{\text{new}}\) because it answers for &lt;strong&gt;one specific person&lt;/strong&gt;, not for the average of the whole group of people of the same height.&lt;/p&gt;

&lt;p&gt;This is the point that many regression beginners often skip:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the interval for \(\mu_{\text{new}}\) answers about the average trend,&lt;/li&gt;
  &lt;li&gt;the interval for \(y_{\text{new}}\) answers about a truly new observation,&lt;/li&gt;
  &lt;li&gt;the second interval is always wider because it keeps individual variability too.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the generative spirit, the Bayesian prediction procedure is essentially:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Draw a sample from the posterior of \(\alpha,\beta,\sigma\).&lt;/li&gt;
  &lt;li&gt;Compute \(\mu_{\text{new}}^{(s)} = \alpha^{(s)} + \beta^{(s)} x_{\text{new}}\).&lt;/li&gt;
  &lt;li&gt;Generate a new value \(y_{\text{new}}^{(s)} \sim \mathcal{N}(\mu_{\text{new}}^{(s)}, \sigma^{(s)})\).&lt;/li&gt;
  &lt;li&gt;Repeat many times to build the posterior predictive distribution.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So Bayesian regression makes predictions not by “plugging numbers into a single line”, but by producing a whole distribution of plausible new values after having seen the data.&lt;/p&gt;

&lt;h3 id=&quot;82-a-bridge-from-one-variable-to-multi-variable-regression-matrix-form&quot;&gt;8.2. A bridge from one-variable to multi-variable regression (matrix form)&lt;/h3&gt;

&lt;p&gt;With several explanatory variables, we write:&lt;/p&gt;

\[y=X\mathbf w+\varepsilon,\]

&lt;p&gt;where \(\mathbf w=(\alpha,\beta_1,\dots,\beta_p)^\top\) and \(X\) is the design matrix.&lt;/p&gt;

&lt;p&gt;Then, Bayesian inference moves from “one slope” to “a vector of coefficients”, but the thinking does not change: a prior on \(\mathbf w\), a likelihood from the data-generating model, and a posterior for the whole parameter vector.&lt;/p&gt;

&lt;h2 id=&quot;9-an-important-habit-from-this-lesson&quot;&gt;9. An important habit from this lesson&lt;/h2&gt;

&lt;p&gt;Each time you see a regression problem, force yourself to go through a very concrete series of questions: how the data is being generated, where the average trend is, where the noise part is, which parameters are still unknown, and when producing a new prediction which uncertainties need to be kept. If you can do that, you have started to think like someone doing Bayesian modeling rather than just someone running a regression.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; Bayesian linear regression is a generative model in which data is generated around a noisy average trend; the intercept, slope and noise are all unknown quantities to be inferred rather than estimated by a single point value; and the strength of Bayesian regression lies in the fact that it keeps the uncertainty of both the parameters and the predictions instead of giving only a single straight line.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aFDOzpTeg0s&quot;&gt;The Essence of Linear Regression!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch regression as a story about a conditional mean plus noise, exactly how the lesson refuses to start from least squares.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=7ArmBVF2dCs&quot;&gt;Linear Regression, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch the intercept, slope and residuals on a straight line, supporting the part that names α, β and σ.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=tNOu-SEacNU&quot;&gt;Statistical Rethinking 2023 - 03 - Geocentric Models&lt;/a&gt; — Richard McElreath, English. Watch a regression model written as a generative model before being estimated, following the same order as the lesson.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Tell the generative story for the relationship between study hours and exam score.&lt;/li&gt;
  &lt;li&gt;Why is \(\sigma\) a very important parameter and not just an extra “residual”?&lt;/li&gt;
  &lt;li&gt;What is the biggest difference between “fit a line” and “model a process”?&lt;/li&gt;
  &lt;li&gt;In your own work, which regression problem should be viewed in the generative spirit?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 4.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Regression and Other Stories&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapters on regression.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter04/04_02_priors_for_regression/&quot;&gt;4.2 Priors for Regression - Choosing Priors in a Principled Way&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 2.6: Grid Approximation - Discrete Approximation to the Posterior</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_06_grid_approximation/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_06_grid_approximation</id>
   <content type="html">&lt;p&gt;Conjugate priors feel like magic—until the first time your real-world problem refuses to cooperate. The moment you impose a truncated prior, a multimodal prior, or a non-standard likelihood, the neat algebraic shortcut vanishes and you are staring at an integral in the denominator of Bayes’ rule that has no closed-form antiderivative. Before we ever touch fancy MCMC samplers, there is a disarmingly simple, transparent weapon that lets you compute &lt;em&gt;any&lt;/em&gt; 1D or 2D posterior with nothing more than arithmetic: &lt;strong&gt;grid approximation&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lesson Roadmap:&lt;/strong&gt; Why closed-form conjugacy breaks → Key ideas (Riemann sums, non-conjugate inference, curse of dimensionality) → Hand-worked 5-point grid check → Finer grids, non-conjugate priors, posterior summaries, and exercises.&lt;/p&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you should understand grid approximation as the bridge from hand-calculated Bayes to computational Bayes. You should know how to discretize a parameter space, compute a posterior on a grid, and explain why this method is excellent for learning but limited for high-dimensional models.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; You want to infer \(\theta\) after seeing 6 heads in 9 tosses, but instead of working over the entire interval \([0,1]\), you only test candidate values like \(0, 0.25, 0.5, 0.75, 1\). That is the basic idea of grid approximation.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If you increase the grid from 5 points to 100 or 1000 points, what do you expect to improve?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-what-grid-approximation-really-is&quot;&gt;Key ideas: What Grid Approximation Really Is&lt;/h2&gt;

&lt;h3 id=&quot;1-discrete-quadrature-for-bayes-denominator&quot;&gt;1. Discrete Quadrature for Bayes’ Denominator&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; Replacing the continuous marginal-likelihood integral \(P(D) = \int p(D \mid \theta)p(\theta)\,d\theta\) with a finite Riemann sum over \(M\) evenly spaced grid points \(\theta_1, \dots, \theta_M\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; How accurately a finite probability vector \(\mathbf{w}\) approximates a continuous posterior density \(p(\theta \mid D)\), and how posterior expectations \(\mathbb{E}[g(\theta) \mid D] \approx \sum_{j=1}^M w_j g(\theta_j)\) turn into simple weighted averages.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-breaking-free-from-conjugacy&quot;&gt;2. Breaking Free from Conjugacy&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; A model-agnostic numerical procedure that evaluates \(p(\theta_j) \cdot p(D \mid \theta_j)\) pointwise—requiring zero algebraic matching between prior and likelihood.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; Arbitrary priors (step functions, truncated intervals, mixture priors) and non-standard likelihoods, proving that Bayesian updating is fundamentally &lt;em&gt;multiply prior by likelihood, then normalize&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-the-curse-of-dimensionality-why-we-eventually-need-mcmc&quot;&gt;3. The Curse of Dimensionality (Why We Eventually Need MCMC)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;What it is:&lt;/strong&gt; The exponential explosion of grid size \(M^d\) as the number of parameters \(d\) grows.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What it studies:&lt;/strong&gt; The exact boundary where grid approximation shines (\(d \le 2\), teaching, sanity-checking MCMC) versus where it collapses (\(d \ge 4\)), motivating Hamiltonian Monte Carlo and NUTS in Chapter 4.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;explanation-a-5-point-grid-posterior-checked-by-hand&quot;&gt;Explanation: A 5-Point Grid Posterior Checked by Hand&lt;/h2&gt;

&lt;p&gt;Suppose you flip a coin \(n = 3\) times and observe \(k = 2\) heads, with a flat uniform prior over \(\theta \in [0, 1]\). Analytically, we know the exact posterior is \(\mathrm{Beta}(3, 2)\) with mean \(\frac{3}{3+2} = 0.600\). Now pretend you forgot the Beta formula and evaluate only 5 evenly spaced grid points \(\theta \in \{0.1, 0.3, 0.5, 0.7, 0.9\}\) (each with prior weight \(1/5\)). Ignoring the constant \(\binom{3}{2} = 3\) (which cancels on normalization), the unnormalized likelihood is \(L(\theta) = \theta^2(1 - \theta)\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Grid point \(\theta_j\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Unnormalized \(\theta_j^2(1-\theta_j)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Normalized weight \(w_j\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Contribution \(\theta_j w_j\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.01 \times 0.9 = 0.009\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.009 / 0.425 = 0.0212\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0021\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.09 \times 0.7 = 0.063\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.063 / 0.425 = 0.1482\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0445\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.25 \times 0.5 = 0.125\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.125 / 0.425 = 0.2941\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.1471\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.7\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.49 \times 0.3 = 0.147\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.147 / 0.425 = 0.3459\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.2421\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.9\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.81 \times 0.1 = 0.081\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.081 / 0.425 = 0.1906\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.1715\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Total&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.425\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(1.0000\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.6073\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Even with a crude 5-point grid, the posterior mean \(0.6073\) lands within \(0.007\) of the exact \(0.6000\)! Yet notice the scaling wall: with \(M = 100\) points per axis, \(d = 1\) takes \(100\) evaluations, \(d = 3\) takes \(10^6\), and a modest 10-parameter regression requires \(100^{10} = 10^{20}\) evaluations—longer than the age of the universe.&lt;/p&gt;

&lt;h2 id=&quot;opening-idea-what-if-the-posterior-has-no-clean-closed-form&quot;&gt;Opening idea: what if the posterior has no clean closed form?&lt;/h2&gt;

&lt;p&gt;Conjugate models are elegant, but real problems are not always so cooperative.&lt;/p&gt;

&lt;p&gt;For example, the prior may be a mixture of competing beliefs, the prior and likelihood may fail to combine into a convenient closed-form posterior, or we may simply want a computational approach transparent enough that every step can still be inspected directly.&lt;/p&gt;

&lt;p&gt;Grid approximation is the simplest way to start.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/grid_approximation_intro.png&quot; alt=&quot;A visual introduction to grid approximation&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-core-idea-replace-a-continuum-with-a-finite-set-of-points&quot;&gt;1. Core idea: replace a continuum with a finite set of points&lt;/h2&gt;

&lt;p&gt;Suppose \(\theta\) lies in \([0,1]\). Instead of considering every possible value continuously, choose grid points:&lt;/p&gt;

\[\theta_1,\theta_2,\dots,\theta_G.\]

&lt;p&gt;At each point, compute:&lt;/p&gt;

&lt;p&gt;the prior, the likelihood, and the unnormalized posterior.&lt;/p&gt;

&lt;p&gt;Then normalize the weights. The result is a discrete approximation to the posterior.&lt;/p&gt;

&lt;h2 id=&quot;2-a-tiny-hand-worked-example&quot;&gt;2. A tiny hand-worked example&lt;/h2&gt;

&lt;p&gt;Suppose the prior is uniform on \([0,1]\), the data are 6 heads in 9 tosses, and the grid is:&lt;/p&gt;

\[\theta \in \{0,\ 0.25,\ 0.5,\ 0.75,\ 1\}.\]

&lt;p&gt;The likelihood is proportional to:&lt;/p&gt;

\[\theta^6(1-\theta)^3.\]

&lt;p&gt;Evaluate that expression at each grid point, multiply by the prior, and normalize.&lt;/p&gt;

&lt;p&gt;The main lesson is not the exact numbers themselves, but the workflow: we score candidate values, compare them, and then normalize the resulting weights into a proper posterior approximation.&lt;/p&gt;

&lt;h3 id=&quot;21-reading-the-grid-posterior-numerically&quot;&gt;2.1. Reading the grid posterior numerically&lt;/h3&gt;

&lt;p&gt;The sum of the three nonzero weights above is approximately:&lt;/p&gt;

\[0.000103 + 0.001953 + 0.002781 = 0.004837.\]

&lt;p&gt;After normalization, the discrete posterior on this grid is approximately:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
\[P(\theta=0.25 \mid D) \approx 0.021\]
  &lt;/li&gt;
  &lt;li&gt;
\[P(\theta=0.50 \mid D) \approx 0.404\]
  &lt;/li&gt;
  &lt;li&gt;
\[P(\theta=0.75 \mid D) \approx 0.575\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So even on a very coarse grid, we can already answer questions like:&lt;/p&gt;

\[P(\theta \ge 0.5 \mid D) \approx 0.404 + 0.575 = 0.979.\]

&lt;p&gt;This is one of the nicest things about grid approximation: it turns the posterior into concrete probabilities that we can add, compare, and interpret directly.&lt;/p&gt;

&lt;h2 id=&quot;3-the-grid-algorithm&quot;&gt;3. The grid algorithm&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/grid_algorithm_steps.png&quot; alt=&quot;Grid approximation algorithm steps&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;step-1-build-the-grid&quot;&gt;Step 1. Build the grid&lt;/h3&gt;

&lt;p&gt;For example:&lt;/p&gt;

\[\theta_{\text{grid}} = \text{linspace}(0,1,G).\]

&lt;h3 id=&quot;step-2-compute-the-prior-on-the-grid&quot;&gt;Step 2. Compute the prior on the grid&lt;/h3&gt;

&lt;h3 id=&quot;step-3-compute-the-likelihood-on-the-grid&quot;&gt;Step 3. Compute the likelihood on the grid&lt;/h3&gt;

&lt;h3 id=&quot;step-4-multiply-prior-and-likelihood&quot;&gt;Step 4. Multiply prior and likelihood&lt;/h3&gt;

\[p(\theta_i \mid D) \propto p(D \mid \theta_i)p(\theta_i).\]

&lt;h3 id=&quot;step-5-normalize&quot;&gt;Step 5. Normalize&lt;/h3&gt;

&lt;p&gt;Divide by the total weight.&lt;/p&gt;

&lt;h3 id=&quot;try-it-grid-approximation-step-by-step&quot;&gt;Try it: grid approximation step by step&lt;/h3&gt;

&lt;p&gt;Lay a grid, compute prior and likelihood, multiply and normalise; add points to watch the error shrink.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;grid-explainer&quot; data-lang=&quot;en&quot; data-prior=&quot;flat&quot; data-k=&quot;6&quot; data-n=&quot;9&quot; data-points=&quot;10&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-finer-grids-improve-the-approximation&quot;&gt;4. Finer grids improve the approximation&lt;/h2&gt;

&lt;p&gt;Using 5 points gives a rough picture. Using 20, 100, or 1000 points gives a smoother and more accurate approximation.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_resolution_5.png&quot; alt=&quot;A very coarse 5-point grid&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_resolution_20.png&quot; alt=&quot;A medium 20-point grid&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_resolution_100.png&quot; alt=&quot;A finer 100-point grid&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_vs_exact_5.png&quot; alt=&quot;Comparing a 5-point grid with the exact posterior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_vs_exact_20.png&quot; alt=&quot;Comparing a 20-point grid with the exact posterior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_vs_exact_100.png&quot; alt=&quot;Comparing a 100-point grid with the exact posterior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/grid_size_comparison.png&quot; alt=&quot;Effect of grid size&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This creates a clear trade-off: a coarse grid is faster but rougher, while a fine grid is more accurate but also more computationally expensive.&lt;/p&gt;

&lt;h2 id=&quot;5-a-useful-case-non-conjugate-priors&quot;&gt;5. A useful case: non-conjugate priors&lt;/h2&gt;

&lt;p&gt;Suppose analysts have two competing prior beliefs about a return rate, with one mode near \(0.3\) and another mode near \(0.7\).&lt;/p&gt;

&lt;p&gt;That gives a mixture prior with two peaks. Closed-form algebra may no longer be convenient, but grid approximation still works naturally, because we only need to evaluate the mixture prior on the grid, evaluate the likelihood at the same points, and then normalize the resulting weights.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/grid_mixture_prior_example.png&quot; alt=&quot;Grid approximation with a mixture prior&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;try-it-a-non-conjugate-prior-skewed-triangle&quot;&gt;Try it: a non-conjugate prior (skewed triangle)&lt;/h3&gt;

&lt;p&gt;With no closed form the grid still gives an accurate posterior when fine enough.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;grid-explainer&quot; data-lang=&quot;en&quot; data-prior=&quot;tri&quot; data-k=&quot;8&quot; data-n=&quot;12&quot; data-points=&quot;100&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;6-what-can-we-do-with-a-grid-posterior&quot;&gt;6. What can we do with a grid posterior?&lt;/h2&gt;

&lt;p&gt;Quite a lot, and that is precisely why grid approximation is more than a toy example.&lt;/p&gt;

&lt;h3 id=&quot;61-posterior-mean&quot;&gt;6.1. Posterior mean&lt;/h3&gt;

\[E[\theta \mid D] \approx \sum_i \theta_i p(\theta_i \mid D).\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_stat_mean_median_mode.png&quot; alt=&quot;Posterior mean, median, and mode on the grid&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;62-interval-probabilities&quot;&gt;6.2. Interval probabilities&lt;/h3&gt;

&lt;p&gt;Add posterior weights over the relevant grid points.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_stat_interval_probability.png&quot; alt=&quot;An interval probability computed from the grid posterior&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;63-credible-intervals&quot;&gt;6.3. Credible intervals&lt;/h3&gt;

&lt;p&gt;Use the cumulative posterior mass on the grid.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_stat_credible_interval.png&quot; alt=&quot;A credible interval extracted from the discrete posterior&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;64-posterior-sampling&quot;&gt;6.4. Posterior sampling&lt;/h3&gt;

&lt;p&gt;Draw grid points according to their posterior weights.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_stat_sampling.png&quot; alt=&quot;Sampling directly from the grid posterior&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;7-posterior-predictive-with-a-grid&quot;&gt;7. Posterior predictive with a grid&lt;/h2&gt;

&lt;p&gt;Once the posterior is available on a grid, future-data prediction becomes easy, because prediction can be obtained by averaging conditional predictive distributions over the posterior weights on the grid:&lt;/p&gt;

\[P(y_{\text{new}} \mid D) = \sum_i P(y_{\text{new}} \mid \theta_i)p(\theta_i \mid D).\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_predictive_distribution.png&quot; alt=&quot;Posterior predictive distribution obtained from the grid posterior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_predictive_vs_exact.png&quot; alt=&quot;Grid posterior predictive compared with the exact solution&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This is where the method starts to feel practically useful, not just pedagogically useful.&lt;/p&gt;

&lt;h2 id=&quot;8-when-is-grid-approximation-especially-useful&quot;&gt;8. When is grid approximation especially useful?&lt;/h2&gt;

&lt;h3 id=&quot;81-when-learning-bayesian-inference&quot;&gt;8.1. When learning Bayesian inference&lt;/h3&gt;

&lt;p&gt;It makes every part of Bayes visible, because prior, likelihood, posterior, normalization, and prediction all appear as explicit computations on a finite set of candidate values.&lt;/p&gt;

&lt;h3 id=&quot;82-for-one-parameter-problems&quot;&gt;8.2. For one-parameter problems&lt;/h3&gt;

&lt;p&gt;It is often simple, fast enough, and easy to visualize, which makes it especially attractive as a first computational method.&lt;/p&gt;

&lt;h3 id=&quot;83-as-a-small-model-check&quot;&gt;8.3. As a small-model check&lt;/h3&gt;

&lt;p&gt;Even if you later use MCMC, grid approximation can still serve as a useful sanity check in tiny problems where an explicit approximation is cheap and easy to inspect.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/when_to_use_grid.png&quot; alt=&quot;When to use grid approximation&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;9-the-main-limitation-curse-of-dimensionality&quot;&gt;9. The main limitation: curse of dimensionality&lt;/h2&gt;

&lt;p&gt;If each parameter uses 100 grid points, then 1 parameter requires 100 points, 2 parameters require 10,000 points, 3 parameters require 1,000,000 points, and 4 parameters require 100,000,000 points; this explosive growth is exactly what the phrase curse of dimensionality is meant to capture.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_dimensionality_growth.png&quot; alt=&quot;Grid size grows explosively with parameter dimension&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_grid_dimensionality_table.png&quot; alt=&quot;A table view of the dimensionality explosion in grid methods&quot; /&gt;&lt;/p&gt;

&lt;p&gt;So grid approximation is excellent for very small models and quickly becomes impractical as dimension grows.&lt;/p&gt;

&lt;h2 id=&quot;10-where-does-grid-approximation-fit-in-the-bigger-picture&quot;&gt;10. Where does grid approximation fit in the bigger picture?&lt;/h2&gt;

&lt;p&gt;You can think of the main approaches this way: conjugate priors are ideal for exact closed-form updates in sufficiently simple problems, grid approximation is useful for small and transparent computational updates, and MCMC is the more general tool for complex high-dimensional models.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/grid_to_mcmc_bridge.png&quot; alt=&quot;From grid approximation to MCMC&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Grid approximation is the conceptual bridge to later computational methods.&lt;/p&gt;

&lt;h2 id=&quot;11-common-misunderstandings&quot;&gt;11. Common misunderstandings&lt;/h2&gt;

&lt;h3 id=&quot;111-grid-approximation-is-always-accurate&quot;&gt;11.1. “Grid approximation is always accurate”&lt;/h3&gt;

&lt;p&gt;No. It is only an approximation, and accuracy depends on resolution and parameter dimension.&lt;/p&gt;

&lt;h3 id=&quot;112-just-increase-the-grid-size-and-everything-is-solved&quot;&gt;11.2. “Just increase the grid size and everything is solved”&lt;/h3&gt;

&lt;p&gt;No. In higher dimensions, the number of grid points explodes.&lt;/p&gt;

&lt;h3 id=&quot;113-grid-approximation-is-too-simple-to-matter&quot;&gt;11.3. “Grid approximation is too simple to matter”&lt;/h3&gt;

&lt;p&gt;No. It is one of the best tools for building Bayesian intuition.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Grid approximation computes a posterior by discretizing the parameter space into a finite grid.&lt;/strong&gt; It is intuitive, flexible, and excellent for learning or for very small models, especially when conjugacy is unavailable but the parameter space is still simple enough to explore directly. Its main weakness is dimensionality, which is why more advanced methods such as MCMC are needed later. The main lesson to keep is that grid approximation turns a continuous posterior problem into a discrete weighted comparison over candidate values, works especially well for small models and non-conjugate examples, and fails to scale once the number of parameters becomes even moderately large.&lt;/p&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=w4fKaBCX02Q&quot;&gt;Introduction to the elements of Bayesian statistics. Week 3. Video 2. Grid approx. &amp;amp; probability.&lt;/a&gt; — Peter Blenis, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Watch a posterior computed on a grid and normalized by a sum, the algorithm this lesson wants you to implement.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2BhfFLATx8c&quot;&gt;Bayes Week 2, Lecture 1: Grid Approximation&lt;/a&gt; — Kevin James, English. Watch a second pass over building the grid, multiplying prior by likelihood, and reading the discrete posterior.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R1vcdhPBlXA&quot;&gt;Statistical Rethinking 2023 - 02 - The Garden of Forking Data&lt;/a&gt; — Richard McElreath, English. Watch Bayesian updating as counting, the idea a grid only discretizes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why does a 5-point grid only give a rough approximation?&lt;/li&gt;
  &lt;li&gt;Why is grid approximation such a good teaching tool for one-parameter models?&lt;/li&gt;
  &lt;li&gt;Why does the method break down so quickly in 4 or 5 dimensions?&lt;/li&gt;
  &lt;li&gt;Give one example of a non-conjugate prior where grid approximation is easier than exact algebra.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2-3.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 6.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 3.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;End of Chapter 02. Next chapter: &lt;a href=&quot;/contents/en/chapter04/&quot;&gt;Chapter 04 - Bayesian Linear Regression&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 2.5: Conjugate Priors and the Algebra of Bayesian Updating</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_05_conjugate_priors/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_05_conjugate_priors</id>
   <content type="html">&lt;p&gt;Before fast computers and MCMC samplers existed, computing the normalizing integral \(P(D) = \int P(D\mid\theta)P(\theta)\,d\theta\) was the great bottleneck of Bayesian statistics. Mathematicians discovered a breathtaking algebraic shortcut: &lt;strong&gt;conjugate priors&lt;/strong&gt;—special prior families whose functional form matches the likelihood so cleanly that multiplying prior \(\times\) likelihood lands you right back in the &lt;em&gt;exact same&lt;/em&gt; distribution family with updated parameters!&lt;/p&gt;

&lt;p&gt;This lesson builds a complete cheat sheet of the &lt;strong&gt;Big Four Conjugate Families&lt;/strong&gt; (Beta–Binomial, Gamma–Poisson, Normal–Normal, Dirichlet–Multinomial), explains &lt;em&gt;why&lt;/em&gt; they arise from the &lt;strong&gt;exponential family&lt;/strong&gt;, and clarifies exactly when to use them versus moving to MCMC.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-algebra-of-conjugacy--exponential-families&quot;&gt;Key ideas: The Algebra of Conjugacy &amp;amp; Exponential Families&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Definition of Conjugacy:&lt;/strong&gt; Prior \(p(\theta)\) is conjugate to likelihood \(p(y\mid\theta)\) if the posterior \(p(\theta\mid y)\) belongs to the &lt;strong&gt;same parametric family&lt;/strong&gt; as \(p(\theta)\)—turning integration into simple hyperparameter addition!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kernel Matching (Drop Constants, Match Exponents):&lt;/strong&gt; You never need to carry normalizing constants when deriving a conjugate posterior—simply multiply the \(\theta\)-dependent &lt;strong&gt;kernels&lt;/strong&gt; and read off the updated parameters!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Exponential Family Engine:&lt;/strong&gt; Every classical conjugate pair exists because Binomial, Poisson, Normal, and Multinomial all belong to the &lt;strong&gt;exponential family&lt;/strong&gt; \(p(y\mid\theta) = h(y)\exp(\eta(\theta)^T T(y) - A(\theta))\), whose sufficient statistics \(T(y)\) add linearly!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;When Conjugacy Ends (And MCMC Begins):&lt;/strong&gt; The moment you add logistic link functions, Student-\(t\) robust likelihoods, or hierarchical random effects, conjugacy breaks—and modern HMC/NUTS takes over seamlessly.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you should understand conjugate priors not as a memorization trick, but as prior-likelihood pairs that make Bayesian updating especially clean. You should also know when conjugacy is extremely useful and when it is better to move on to more flexible computational methods.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; If the prior for a pass rate is Beta\((2,2)\) and new data are 7 passes out of 10 students, the posterior becomes Beta\((9,5)\). We do not need a new family of distributions, only updated parameters.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; What exactly makes a prior “conjugate” to a likelihood?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;opening-idea-why-are-some-bayesian-models-so-easy-to-solve-by-hand&quot;&gt;Opening idea: why are some Bayesian models so easy to solve by hand?&lt;/h2&gt;

&lt;p&gt;Bayes’ theorem is conceptually simple:&lt;/p&gt;

\[P(\theta \mid D) \propto P(D \mid \theta)P(\theta).\]

&lt;p&gt;But exact computation is often hard because the posterior must be normalized. Some models are special: after multiplying prior and likelihood, the posterior still belongs to the &lt;strong&gt;same distribution family&lt;/strong&gt; as the prior. These are the conjugate cases.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/conjugate_pairs_intro.png&quot; alt=&quot;An introduction to conjugate pairs&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;a-30-second-map-before-the-formulas&quot;&gt;A 30-second map before the formulas&lt;/h2&gt;

&lt;p&gt;If conjugacy feels abstract at first reading, the most useful move is not to memorize formulas immediately, but to keep a compact chain of questions in mind: what the unknown parameter actually is, what form the data take, which likelihood matches that data story, and whether there is a prior with a matching structure such that the posterior remains in the same family after updating.&lt;/p&gt;

&lt;p&gt;Once you think in those terms, the standard conjugate pairs become much easier to organize. When the data story is “count the number of successes in \(n\) trials,” the natural likelihood is Binomial and the natural prior for the success probability is Beta; when the data story is “wait until the first success occurs,” the likelihood becomes Geometric while the prior can still be Beta; when the observations are event counts over time, Poisson is often the right likelihood and Gamma becomes the natural conjugate prior for the rate; and when the goal is to infer the mean of continuous data fluctuating around a central value, the relevant pair is Normal-Normal. You do not need to memorize every pair at once, because it is usually enough at the beginning to recognize whether the problem is about a probability, a waiting-time process, a count rate, or a continuous mean.&lt;/p&gt;

&lt;h2 id=&quot;1-what-is-a-conjugate-prior&quot;&gt;1. What is a conjugate prior?&lt;/h2&gt;

&lt;p&gt;A prior \(p(\theta)\) is conjugate to a likelihood \(p(y \mid \theta)\) if the posterior \(p(\theta \mid y)\) stays in the same family as the prior.&lt;/p&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;p&gt;Beta prior  \(\rightarrow\) Beta posterior, Gamma prior  \(\rightarrow\) Gamma posterior, and Normal prior  \(\rightarrow\) Normal posterior.&lt;/p&gt;

&lt;p&gt;The practical importance of this fact is that Bayesian updating becomes a matter of revising a few parameters inside a familiar family rather than inventing a completely new functional form after every observation, which is why conjugate models are so valuable pedagogically and computationally.&lt;/p&gt;

&lt;h2 id=&quot;2-why-does-conjugacy-happen&quot;&gt;2. Why does conjugacy happen?&lt;/h2&gt;

&lt;p&gt;Conjugacy appears when the prior and the likelihood have matching algebraic structure, meaning that once both are written as functions of the parameter, they are built from the same kinds of algebraic pieces. For example, a Binomial likelihood contributes powers of \(\theta\) and \(1-\theta\), while a Beta prior is built from exactly those same components; as a result, multiplying them does not change the family of shapes, but only changes the exponents, which is precisely why the posterior remains Beta.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/why_conjugacy_convenient.png&quot; alt=&quot;Why conjugacy is convenient&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-beta-binomial&quot;&gt;3. Beta-Binomial&lt;/h2&gt;

&lt;h3 id=&quot;31-real-world-story&quot;&gt;3.1. Real-world story&lt;/h3&gt;

&lt;p&gt;Suppose a teacher wants to infer the class pass rate \(\theta\). Out of 40 students, 31 pass.&lt;/p&gt;

&lt;p&gt;If:&lt;/p&gt;

\[Y \mid \theta \sim \text{Binomial}(n,\theta)\]

&lt;p&gt;and:&lt;/p&gt;

\[\theta \sim \text{Beta}(\alpha,\beta),\]

&lt;p&gt;then:&lt;/p&gt;

\[\theta \mid y \sim \text{Beta}(\alpha+y,\beta+n-y).\]

&lt;p&gt;To see the algebra directly, keep only the parts that depend on \(\theta\):&lt;/p&gt;

\[p(\theta)\propto \theta^{\alpha-1}(1-\theta)^{\beta-1}\]

&lt;p&gt;and:&lt;/p&gt;

\[p(y\mid \theta)\propto \theta^y(1-\theta)^{n-y}.\]

&lt;p&gt;Therefore:&lt;/p&gt;

\[p(\theta\mid y)\propto p(y\mid \theta)p(\theta)
\propto \theta^{\alpha+y-1}(1-\theta)^{\beta+n-y-1},\]

&lt;p&gt;so:&lt;/p&gt;

\[\theta\mid y\sim \text{Beta}(\alpha+y,\beta+n-y).\]

&lt;p&gt;If the data are written as Bernoulli observations \(y_1,\dots,y_n\) and \(s=\sum_{i=1}^n y_i\), then the same update becomes:&lt;/p&gt;

\[\theta\mid y_{1:n}\sim \text{Beta}(\alpha+s,\beta+n-s).\]

&lt;p&gt;The posterior mean is:&lt;/p&gt;

\[E[\theta\mid y]=\frac{\alpha+y}{\alpha+\beta+n}.\]

&lt;p&gt;If you want a one-line memory rule, read the update this way: the posterior success count equals the prior success count plus the observed successes, and the posterior failure count equals the prior failure count plus the observed failures.&lt;/p&gt;

&lt;h3 id=&quot;32-interpretation&quot;&gt;3.2. Interpretation&lt;/h3&gt;

&lt;p&gt;If the prior is Beta\((2,2)\) and the data are 31 passes out of 40, the posterior is Beta\((33,11)\).&lt;/p&gt;

&lt;p&gt;The intuition is simple but important: the prior acts like a small amount of pseudo-data, the real observations are added on top of it, and the posterior is the combined result of both sources of information.&lt;/p&gt;

&lt;h3 id=&quot;321-a-very-direct-sequential-update-example&quot;&gt;3.2.1. A very direct sequential update example&lt;/h3&gt;

&lt;p&gt;We can also see the beauty of conjugacy through step-by-step updating. Start with the prior Beta\((2,2)\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;After batch 1, if we observe 3 passes out of 4 students, the posterior is Beta\((5,3)\).&lt;/li&gt;
  &lt;li&gt;After batch 2, if we then observe 28 more passes out of 36 students, the new posterior is Beta\((33,11)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is exactly the same result we would get by updating once with the full dataset 31/40. That is why conjugate priors are so convenient: we do not need to solve the whole problem again from scratch; we can just keep adding new information into the distribution parameters.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/beta_binomial_conjugacy_visual.png&quot; alt=&quot;Beta-Binomial conjugacy&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;33-typical-applications&quot;&gt;3.3. Typical applications&lt;/h3&gt;

&lt;p&gt;Beta-Binomial is natural for settings such as conversion rates, pass rates, treatment success rates, email open rates, and defect proportions, because all of these contexts reduce to the same underlying data story: a count of successes out of a known number of trials, with an unknown success probability.&lt;/p&gt;

&lt;h3 id=&quot;try-it-betabinomial-flip-by-flip&quot;&gt;Try it: Beta–Binomial flip by flip&lt;/h3&gt;

&lt;p&gt;Flip one at a time, watch Beta(a + k, b + n − k) change, with the 95% interval and a grid check.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;conjugate-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;betabinom&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;4-beta-geometric&quot;&gt;4. Beta-Geometric&lt;/h2&gt;

&lt;h3 id=&quot;41-real-world-story&quot;&gt;4.1. Real-world story&lt;/h3&gt;

&lt;p&gt;Suppose a student keeps taking an exam until passing. We want to infer the pass probability \(\theta\) on each attempt. If the student passes on the third attempt, the data should not be read as “1 success in 3 trials” in the Binomial sense; rather, the meaningful story is that the first two attempts were failures and the third attempt was the first success, which is exactly the kind of ordered waiting-time structure captured by a Geometric likelihood:&lt;/p&gt;

\[Y \mid \theta \sim \text{Geometric}(\theta),\]

&lt;p&gt;with:&lt;/p&gt;

\[P(Y=y \mid \theta) = \theta(1-\theta)^{y-1}.\]

&lt;p&gt;If the prior is still:&lt;/p&gt;

\[\theta \sim \text{Beta}(\alpha,\beta),\]

&lt;p&gt;then the posterior is:&lt;/p&gt;

\[\theta \mid y \sim \text{Beta}(\alpha+1,\beta+y-1).\]

&lt;p&gt;For one waiting-time observation \(y\), the likelihood can be written as:&lt;/p&gt;

\[p(y\mid \theta)=\theta(1-\theta)^{y-1}\propto \theta^1(1-\theta)^{y-1}.\]

&lt;p&gt;The Beta prior contributes:&lt;/p&gt;

\[p(\theta)\propto \theta^{\alpha-1}(1-\theta)^{\beta-1}.\]

&lt;p&gt;Multiplying them gives:&lt;/p&gt;

\[p(\theta\mid y)\propto \theta^{\alpha}(1-\theta)^{\beta+y-2},\]

&lt;p&gt;so:&lt;/p&gt;

\[\theta\mid y\sim \text{Beta}(\alpha+1,\beta+y-1).\]

&lt;p&gt;If we have \(m\) independent waiting times \(y_1,\dots,y_m\), then:&lt;/p&gt;

\[p(y_{1:m}\mid \theta)=\prod_{i=1}^m \theta(1-\theta)^{y_i-1}
=\theta^m(1-\theta)^{\sum_{i=1}^m y_i-m},\]

&lt;p&gt;which leads to:&lt;/p&gt;

\[\theta\mid y_{1:m}\sim \text{Beta}\left(\alpha+m,\beta+\sum_{i=1}^m y_i-m\right).\]

&lt;p&gt;The corresponding posterior mean is:&lt;/p&gt;

\[E[\theta\mid y_{1:m}]=\frac{\alpha+m}{\alpha+\beta+\sum_{i=1}^m y_i}.\]

&lt;h3 id=&quot;42-interpretation&quot;&gt;4.2. Interpretation&lt;/h3&gt;

&lt;p&gt;The logic is that the observation contributes one realized success together with \(y-1\) realized failures, so the Beta prior still works because the likelihood is still built from powers of \(\theta\) and \(1-\theta\).&lt;/p&gt;

&lt;h3 id=&quot;43-do-not-confuse-it-with-beta-binomial&quot;&gt;4.3. Do not confuse it with Beta-Binomial&lt;/h3&gt;

&lt;p&gt;This distinction matters because &lt;strong&gt;Binomial&lt;/strong&gt; asks how many successes occurred in a fixed number of trials, whereas &lt;strong&gt;Geometric&lt;/strong&gt; asks on which trial the first success occurred. The data stories are therefore different at a structural level, even though both models keep a Beta prior in the same family after updating.&lt;/p&gt;

&lt;h2 id=&quot;5-gamma-poisson&quot;&gt;5. Gamma-Poisson&lt;/h2&gt;

&lt;h3 id=&quot;51-real-world-story&quot;&gt;5.1. Real-world story&lt;/h3&gt;

&lt;p&gt;Suppose a call center wants to infer the mean call rate \(\lambda\) per hour.&lt;/p&gt;

&lt;p&gt;If:&lt;/p&gt;

\[Y_i \mid \lambda \sim \text{Poisson}(\lambda)\]

&lt;p&gt;and:&lt;/p&gt;

\[\lambda \sim \text{Gamma}(\alpha,\beta),\]

&lt;p&gt;then under the shape-rate parameterization:&lt;/p&gt;

\[\lambda \mid y_{1:n} \sim \text{Gamma}\left(\alpha + \sum_i y_i,\beta + n\right).\]

&lt;p&gt;Under the shape-rate parameterization, the prior kernel is:&lt;/p&gt;

\[p(\lambda)\propto \lambda^{\alpha-1}e^{-\beta\lambda}.\]

&lt;p&gt;For \(n\) Poisson observations, the likelihood kernel is:&lt;/p&gt;

\[p(y_{1:n}\mid \lambda)=\prod_{i=1}^n \frac{e^{-\lambda}\lambda^{y_i}}{y_i!}
\propto \lambda^{\sum_{i=1}^n y_i}e^{-n\lambda}.\]

&lt;p&gt;Therefore:&lt;/p&gt;

\[p(\lambda\mid y_{1:n})\propto p(y_{1:n}\mid \lambda)p(\lambda)
\propto \lambda^{\alpha+\sum_i y_i-1}e^{-(\beta+n)\lambda},\]

&lt;p&gt;which is why:&lt;/p&gt;

\[\lambda\mid y_{1:n}\sim \text{Gamma}\left(\alpha+\sum_i y_i,\beta+n\right).\]

&lt;p&gt;The posterior mean is:&lt;/p&gt;

\[E[\lambda\mid y]=\frac{\alpha+\sum_i y_i}{\beta+n}.\]

&lt;p&gt;If each observation has exposure \(t_i\) and \(Y_i\mid \lambda\sim \text{Poisson}(t_i\lambda)\), the same logic gives:&lt;/p&gt;

\[\lambda\mid y_{1:n}\sim \text{Gamma}\left(\alpha+\sum_i y_i,\beta+\sum_i t_i\right).\]

&lt;h3 id=&quot;52-interpretation&quot;&gt;5.2. Interpretation&lt;/h3&gt;

&lt;p&gt;The observed counts add to the shape parameter, while the number of observation periods adds to the rate parameter, so the update simultaneously reflects how much activity was seen and how long the process was observed.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_gamma_poisson_prior_posterior.png&quot; alt=&quot;Gamma prior and posterior after count data are observed&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_gamma_poisson_formula_summary.png&quot; alt=&quot;A compact formula summary for the Gamma-Poisson update&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_gamma_poisson_posterior_predictive.png&quot; alt=&quot;Posterior predictive reasoning in the Gamma-Poisson model&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_gamma_poisson_sequential_updates.png&quot; alt=&quot;Sequential updating in the Gamma-Poisson model&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;53-typical-applications&quot;&gt;5.3. Typical applications&lt;/h3&gt;

&lt;p&gt;Typical applications include calls per hour, failures per day, hospital arrivals per shift, orders per minute, and absences per week, because these are all examples of event counts attached to some unit of time or exposure.&lt;/p&gt;

&lt;h3 id=&quot;54-quick-memory-rule&quot;&gt;5.4. Quick memory rule&lt;/h3&gt;

&lt;p&gt;Read the update as bookkeeping: the posterior shape equals the prior shape plus the total number of observed events, while the posterior rate equals the prior rate plus the number of observed time periods.&lt;/p&gt;

&lt;h3 id=&quot;try-it-gammapoisson-observation-by-observation&quot;&gt;Try it: Gamma–Poisson observation by observation&lt;/h3&gt;

&lt;p&gt;A Gamma prior on the rate λ, updated after each interval.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;conjugate-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;gammapoisson&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;6-normal-normal&quot;&gt;6. Normal-Normal&lt;/h2&gt;

&lt;h3 id=&quot;61-real-world-story&quot;&gt;6.1. Real-world story&lt;/h3&gt;

&lt;p&gt;Suppose you want to infer the mean height \(\mu\) of a group of students, assuming the observation standard deviation \(\sigma\) is known.&lt;/p&gt;

&lt;p&gt;If:&lt;/p&gt;

\[Y_i \mid \mu \sim \mathcal{N}(\mu,\sigma^2)\]

&lt;p&gt;and:&lt;/p&gt;

\[\mu \sim \mathcal{N}(\mu_0,\tau_0^2),\]

&lt;p&gt;then the posterior for \(\mu\) is also Normal.&lt;/p&gt;

&lt;p&gt;Writing everything as a function of \(\mu\), the likelihood kernel for \(n\) observations is:&lt;/p&gt;

\[p(y_{1:n}\mid \mu)\propto \exp\left(-\frac{1}{2\sigma^2}\sum_{i=1}^n (y_i-\mu)^2\right)
\propto \exp\left(-\frac{n}{2\sigma^2}(\mu-\bar y)^2\right),\]

&lt;p&gt;where:&lt;/p&gt;

\[\bar y=\frac{1}{n}\sum_{i=1}^n y_i.\]

&lt;p&gt;The Normal prior contributes:&lt;/p&gt;

\[p(\mu)\propto \exp\left(-\frac{(\mu-\mu_0)^2}{2\tau_0^2}\right).\]

&lt;p&gt;After multiplying the prior and likelihood and completing the square, we get:&lt;/p&gt;

\[\mu\mid y_{1:n}\sim \mathcal{N}(\mu_n,\tau_n^2),\]

&lt;p&gt;with:&lt;/p&gt;

\[\tau_n^2=\left(\frac{1}{\tau_0^2}+\frac{n}{\sigma^2}\right)^{-1}\]

&lt;p&gt;and:&lt;/p&gt;

\[\mu_n=\tau_n^2\left(\frac{\mu_0}{\tau_0^2}+\frac{n\bar y}{\sigma^2}\right)
=\frac{\mu_0/\tau_0^2+n\bar y/\sigma^2}{1/\tau_0^2+n/\sigma^2}.\]

&lt;p&gt;Equivalently:&lt;/p&gt;

\[E[\mu\mid y]=\mu_n,\qquad \mathrm{Var}(\mu\mid y)=\tau_n^2.\]

&lt;h3 id=&quot;62-interpretation&quot;&gt;6.2. Interpretation&lt;/h3&gt;

&lt;p&gt;The posterior mean becomes a weighted compromise between the prior mean and the sample mean, and the balance between the two depends on the strength of the prior, the size of the sample, and the amount of observation noise.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_normal_normal_prior_posterior.png&quot; alt=&quot;Normal prior and posterior after combining with continuous data&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_normal_normal_formula_summary.png&quot; alt=&quot;A compact formula summary for the Normal-Normal update&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_normal_normal_sample_size_effect.png&quot; alt=&quot;How sample size changes the Normal-Normal posterior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_normal_normal_prior_data_weights.png&quot; alt=&quot;Relative prior and data weights in the Normal-Normal model&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;63-quick-memory-rule&quot;&gt;6.3. Quick memory rule&lt;/h3&gt;

&lt;p&gt;Even if you forget the exact formula, the right intuition is that the more precise source of information receives more weight, while the posterior variance shrinks as the data become more informative.&lt;/p&gt;

&lt;h3 id=&quot;try-it-normalnormal-and-precision-weighting&quot;&gt;Try it: Normal–Normal and precision weighting&lt;/h3&gt;

&lt;p&gt;Drag μ₀, τ₀, σ to see the posterior as a weighted average of prior and data.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;conjugate-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;normalnormal&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;7-sequential-updating&quot;&gt;7. Sequential updating&lt;/h2&gt;

&lt;p&gt;One of the nicest features of conjugate models is how naturally they support sequential learning. You can update with today’s data, use the resulting posterior as tomorrow’s prior, and continue the process without having to restart the derivation from scratch each time new data arrive.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/sequential_updating_story.png&quot; alt=&quot;Sequential updating with conjugate priors&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This is useful for dashboards, quality monitoring, and streaming observations.&lt;/p&gt;

&lt;h2 id=&quot;why-learn-conjugacy-if-we-later-use-mcmc&quot;&gt;Why learn conjugacy if we later use MCMC?&lt;/h2&gt;

&lt;p&gt;Conjugacy remains worth learning even if we later rely on MCMC, and the reasons go beyond mere computational convenience. First, it builds strong intuition for how Bayesian updating works, because the effect of prior information and observed data can usually be read directly from the updated parameters. Second, it gives exact answers that are extremely useful when we want to check whether numerical methods such as grid approximation or MCMC are behaving sensibly. Third, it remains genuinely practical for many simple one-parameter models, where an exact and interpretable solution is often more valuable than a more elaborate computational approach.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/conjugacy_vs_mcmc.png&quot; alt=&quot;Conjugacy versus broader computational methods&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;8-limits-of-conjugacy&quot;&gt;8. Limits of conjugacy&lt;/h2&gt;

&lt;p&gt;Conjugacy is about convenience, not truth. We should not force a conjugate prior if it is a poor description of prior knowledge, and this becomes especially important when the realistic prior is multimodal, when the model is hierarchical, when the parameter space has complex constraints, or when the dependence structure is richer than a simple one-parameter setup can express.&lt;/p&gt;

&lt;p&gt;Support matters too. Sometimes the algebra looks familiar, but the posterior no longer fits a standard family on the correct parameter domain. In those cases the model can still be valid, but it is no longer a clean “same family in, same family out” conjugate case.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_conjugate_limit_truncated_prior.png&quot; alt=&quot;A conjugate prior can poorly represent a truncated or constrained ideal prior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_conjugate_limit_overview.png&quot; alt=&quot;A compact overview of when conjugacy stops being a good fit&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_conjugate_limit_mixture_prior.png&quot; alt=&quot;Mixture priors are a common case where conjugate families become too restrictive&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_conjugate_limit_decision_tree.png&quot; alt=&quot;A quick decision tree for staying with conjugacy or moving to MCMC&quot; /&gt;&lt;/p&gt;

&lt;p&gt;In such cases, we turn to grid approximation or MCMC.&lt;/p&gt;

&lt;h2 id=&quot;9-quick-guide-to-common-conjugate-pairs&quot;&gt;9. Quick guide to common conjugate pairs&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/conjugate_pairs_table.png&quot; alt=&quot;Table of common conjugate pairs&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Think in terms of data stories rather than isolated formulas. If the parameter is a probability of success, Beta with Binomial is the natural pair; if the problem is about waiting until the first success, Beta with Geometric is the right mental model; if the target is an event rate, Gamma with Poisson is the standard pair; and if the unknown quantity is the mean of continuous data, Normal with Normal is the natural starting point.&lt;/p&gt;

&lt;h2 id=&quot;10-common-misunderstandings&quot;&gt;10. Common misunderstandings&lt;/h2&gt;

&lt;h3 id=&quot;101-a-conjugate-prior-is-always-the-best-prior&quot;&gt;10.1. “A conjugate prior is always the best prior”&lt;/h3&gt;

&lt;p&gt;No. It is only the most convenient one computationally.&lt;/p&gt;

&lt;h3 id=&quot;102-memorizing-formulas-is-enough&quot;&gt;10.2. “Memorizing formulas is enough”&lt;/h3&gt;

&lt;p&gt;No. Without the generative story, the formulas become easy to misuse.&lt;/p&gt;

&lt;h3 id=&quot;103-conjugacy-is-obsolete-because-of-mcmc&quot;&gt;10.3. “Conjugacy is obsolete because of MCMC”&lt;/h3&gt;

&lt;p&gt;No. It is still foundational for intuition and for simple exact solutions.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Conjugate priors are priors that keep the posterior in the same family after updating.&lt;/strong&gt; That property makes Bayesian inference easier to compute, easier to explain, and easier to update sequentially, which is why the four basic pairs in this lesson, namely Beta-Binomial, Beta-Geometric, Gamma-Poisson, and Normal-Normal, are worth remembering. Even so, the more important principle is that computational convenience should never replace good modeling judgment. In condensed form, the lesson is this: conjugacy happens when the algebra of the prior and likelihood matches so that the posterior stays in the same family, conjugate pairs are exceptionally useful for building intuition and checking simple exact updates, and a conjugate prior remains only a convenient choice rather than an automatically superior one.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-exact-kernel-matching-for-a-dirichletmultinomial-3-class-update&quot;&gt;Worked Numerical Example: Exact Kernel Matching for a Dirichlet–Multinomial (3-Class) Update&lt;/h3&gt;

&lt;p&gt;Suppose a website tests 3 button colors (Red, Blue, Green) with unknown click shares \(\mathbf{p} = (p_1, p_2, p_3)\) summing to 1. Start with a symmetric &lt;strong&gt;Dirichlet&lt;/strong&gt; prior \(\mathrm{Dirichlet}(\alpha_1=2,\; \alpha_2=2,\; \alpha_3=2)\) (6 pseudo-clicks total, prior mean \([1/3, 1/3, 1/3]\)).&lt;/p&gt;

&lt;p&gt;Now observe \(n = 14\) clicks: &lt;strong&gt;9 Red, 3 Blue, 2 Green&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Multiply kernels (drop all normalizing constants!):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Prior kernel: \(p_1^{2-1} p_2^{2-1} p_3^{2-1}\).&lt;/li&gt;
      &lt;li&gt;Multinomial likelihood kernel: \(p_1^{9} p_2^{3} p_3^{2}\).&lt;/li&gt;
      &lt;li&gt;Posterior kernel: \(p_1^{(2+9)-1} p_2^{(2+3)-1} p_3^{(2+2)-1} = p_1^{11-1} p_2^{5-1} p_3^{4-1}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Read off the exact conjugate posterior:&lt;/strong&gt; \(\mathbf{\mathrm{Dirichlet}(11,\; 5,\; 4)}\) (total concentration \(11+5+4 = 20\))!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exact posterior means:&lt;/strong&gt;
\(\mathbb{E}[p_{\text{Red}}\mid D] = \frac{11}{20} = \mathbf{55\%}, \qquad \mathbb{E}[p_{\text{Blue}}\mid D] = \frac{5}{20} = \mathbf{25\%}, \qquad \mathbb{E}[p_{\text{Green}}\mid D] = \frac{4}{20} = \mathbf{20\%}!\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-mastering-conjugate-priors&quot;&gt;Explanation: Four Rules for Mastering Conjugate Priors&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Memorize the Big Four updating rules—they cover 80% of rapid back-of-the-envelope Bayes:&lt;/strong&gt; Beta–Binomial (add successes/failures), Gamma–Poisson (add counts/exposure), Normal–Normal (add precisions), Dirichlet–Multinomial (add category counts).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never distort your scientific model just to force conjugacy:&lt;/strong&gt; Conjugacy is a convenience, not a law of nature—if your data has outliers or hierarchical groups, use MCMC with the &lt;em&gt;right&lt;/em&gt; likelihood instead!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use conjugate models as exact ground-truth unit tests for your MCMC code:&lt;/strong&gt; Whenever you write a custom sampler, test it on a Beta–Binomial or Normal–Normal case where you know the exact analytical posterior!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Streaming online systems still love conjugacy:&lt;/strong&gt; Ad-ranking bandits (Thompson Sampling) and real-time sensor filters update conjugate parameters in &lt;strong&gt;nanoseconds&lt;/strong&gt; with \(O(1)\) memory.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; For a Gamma–Poisson conjugate model with prior \(\mathrm{Gamma}(\alpha = 3,\; \beta = 1)\) (shape–rate), if you observe counts &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[5, 2, 4, 1]&lt;/code&gt; over \(n = 4\) equal time periods, what is the exact conjugate posterior Gamma distribution and its posterior mean?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=aPNrhR0dFi8&quot;&gt;What is a conjugate prior?&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Watch conjugacy defined as a prior-likelihood pair that keeps the posterior in the same family.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=GqSX-8AQL90&quot;&gt;Bayesian Updates and Conjugate Priors&lt;/a&gt; — Steve Brunton, English. Watch several conjugate updates side by side, supporting the lesson’s catalogue of practical pairs.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=hKYvZF9wXkk&quot;&gt;20 - Beta conjugate prior to Binomial and Bernoulli likelihoods&lt;/a&gt; — Ox educ, English. Watch the Beta–Binomial update add successes and failures to the prior parameters.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Give one real-world example that fits Beta-Binomial.&lt;/li&gt;
  &lt;li&gt;What is the key data-story difference between Beta-Binomial and Beta-Geometric?&lt;/li&gt;
  &lt;li&gt;Why is Gamma-Poisson so natural for count data over time?&lt;/li&gt;
  &lt;li&gt;In the Normal-Normal model, what makes the posterior mean stay closer to the prior mean or move closer to the sample mean?&lt;/li&gt;
  &lt;li&gt;When would you avoid a conjugate prior even though it is convenient?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 2.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 6-7.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2-3.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter02/02_06_grid_approximation/&quot;&gt;2.6 Grid Approximation - Discrete Approximation to the Posterior&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 2.4: Posterior - Updating Beliefs with Data</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_04_posterior/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_04_posterior</id>
   <content type="html">&lt;p&gt;The &lt;strong&gt;posterior distribution \(p(\theta \mid y)\)&lt;/strong&gt; is the crown jewel of Bayesian inference—it is not a single guess, not a p-value, and not a binary verdict, but a &lt;strong&gt;complete probability map of every parameter value consistent with both your prior knowledge and your observed data!&lt;/strong&gt; Once you hold the posterior (either as a closed-form formula or as 4,000 MCMC draws), you can answer &lt;em&gt;any&lt;/em&gt; practical question directly: &lt;em&gt;“What is the probability the new treatment improves survival by at least 5%?”&lt;/em&gt; or &lt;em&gt;“What is the narrowest 95% Highest Density Interval?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This lesson shows how the posterior blends prior and likelihood as a precision-weighted compromise, compares &lt;strong&gt;Equal-Tailed Intervals (ETI)&lt;/strong&gt; vs. &lt;strong&gt;Highest Density Intervals (HDI)&lt;/strong&gt;, and introduces the &lt;strong&gt;Posterior Predictive Distribution&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-reading-summarizing-and-predicting-from-a-posterior&quot;&gt;Key ideas: Reading, Summarizing, and Predicting From a Posterior&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Posterior as Precision-Weighted Compromise:&lt;/strong&gt; In Normal–Normal updating, \(\mu_{\text{post}} = \frac{\tau_0 \mu_0 + \tau_{\text{data}}\bar{y}}{\tau_0 + \tau_{\text{data}}}\)—the posterior sits strictly between the prior and the data, pulled closer to whichever source has higher precision (lower variance)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Equal-Tailed (ETI) vs. Highest Density Interval (HDI):&lt;/strong&gt; An ETI cuts 2.5% off each tail; an &lt;strong&gt;HDI&lt;/strong&gt; is the &lt;em&gt;narrowest&lt;/em&gt; interval containing 95% of probability mass (every point inside has higher density than every point outside—essential for skewed posteriors like \(\mathrm{Beta}(1, 14)\)!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Direct Hypothesis Probabilities:&lt;/strong&gt; Given posterior draws \(\theta^{(1)},\dots,\theta^{(S)}\), computing \(P(\theta &amp;gt; 0.5 \mid y)\) is literally just &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(draws &amp;gt; 0.5).mean()&lt;/code&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior Predictive Distribution \(p(\tilde{y}\mid y) = \int p(\tilde{y}\mid\theta)p(\theta\mid y)\,d\theta\):&lt;/strong&gt; Integrates over &lt;em&gt;both&lt;/em&gt; remaining parameter uncertainty and observation noise to predict genuinely new data points.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you should see the posterior as the central object of Bayesian inference, know how it combines prior and likelihood, and know how to read it through intervals, probabilities, and predictions.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; You start with a prior belief that a class pass rate is around \(60\%\). The new class has 31 passes out of 40 students. The posterior is the updated belief after combining those two sources of information.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Why does the posterior usually not match the prior exactly, but also not necessarily match the raw observed proportion exactly?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;opening-idea-after-seeing-data-what-should-we-believe&quot;&gt;Opening idea: after seeing data, what should we believe?&lt;/h2&gt;

&lt;p&gt;Suppose you are tracking the pass rate of a new class. Before grading, you already have a prior based on previous semesters. Once the current data arrive, you should not ignore the old knowledge, but you should not ignore the new evidence either.&lt;/p&gt;

&lt;p&gt;The posterior is the principled answer to that tension, because it is the place where prior knowledge and new evidence are forced to meet under a coherent probabilistic rule rather than through ad hoc judgment.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/bayesian_update_machine_intro.png&quot; alt=&quot;Posterior as an updating machine&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-what-is-the-posterior&quot;&gt;1. What is the posterior?&lt;/h2&gt;

&lt;p&gt;The posterior is the distribution of \(\theta\) after observing data \(D\):&lt;/p&gt;

\[P(\theta \mid D).\]

&lt;p&gt;Bayes’ theorem gives:&lt;/p&gt;

\[P(\theta \mid D) = \frac{P(D \mid \theta)P(\theta)}{P(D)}.\]

&lt;p&gt;Or more compactly:&lt;/p&gt;

\[\text{posterior} \propto \text{likelihood} \times \text{prior}.\]

&lt;h2 id=&quot;2-a-step-by-step-example&quot;&gt;2. A step-by-step example&lt;/h2&gt;

&lt;p&gt;Suppose the prior is Beta\((2,2)\) and the data are 7 heads out of 10 tosses.&lt;/p&gt;

&lt;p&gt;The Binomial likelihood contributes:&lt;/p&gt;

\[P(D \mid \theta) \propto \theta^7(1-\theta)^3.\]

&lt;p&gt;The prior contributes:&lt;/p&gt;

\[P(\theta) \propto \theta^{2-1}(1-\theta)^{2-1}.\]

&lt;p&gt;Multiplying gives:&lt;/p&gt;

\[P(\theta \mid D) \propto \theta^8(1-\theta)^4,\]

&lt;p&gt;which is Beta\((9,5)\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/prior_to_posterior.png&quot; alt=&quot;From prior to posterior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The key interpretation is simple but important: the prior centered the inference around \(0.5\), the data pushed it toward \(0.7\), and the posterior ended up in between, around \(0.643\), as a principled compromise rather than a casual average.&lt;/p&gt;

&lt;h2 id=&quot;3-what-is-the-posterior-telling-us&quot;&gt;3. What is the posterior telling us?&lt;/h2&gt;

&lt;p&gt;When reading a posterior, it is useful to ask four connected questions: where its center lies, how wide it is, whether it is skewed, and what its tails imply about meaningful kinds of risk.&lt;/p&gt;

&lt;h2 id=&quot;4-why-the-posterior-is-richer-than-a-point-estimate&quot;&gt;4. Why the posterior is richer than a point estimate&lt;/h2&gt;

&lt;p&gt;With the posterior, we can answer questions such as the probability that \(0.6 \le \theta \le 0.7\), the probability that \(\theta &amp;gt; 0.5\), or whether values above \(0.8\) are still plausible enough to matter in practice.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/combining_information.png&quot; alt=&quot;How prior and likelihood combine&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_posterior_probability_interval.png&quot; alt=&quot;Posterior probability for a specific interval&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_posterior_probability_above_half.png&quot; alt=&quot;Posterior probability above the 0.5 threshold&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_posterior_probability_above_eighty.png&quot; alt=&quot;Posterior probability for a fairly demanding threshold above 0.8&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;5-common-summaries-of-the-posterior&quot;&gt;5. Common summaries of the posterior&lt;/h2&gt;

&lt;h3 id=&quot;51-posterior-mean&quot;&gt;5.1. Posterior mean&lt;/h3&gt;

\[E[\theta \mid D].\]

&lt;p&gt;This is often the natural summary when we want one representative value and the decision problem treats squared error as especially costly.&lt;/p&gt;

&lt;h3 id=&quot;52-posterior-median&quot;&gt;5.2. Posterior median&lt;/h3&gt;

&lt;p&gt;The value that splits posterior mass into two equal halves.&lt;/p&gt;

&lt;p&gt;It is often a more stable summary when the posterior is skewed and a central point is still needed.&lt;/p&gt;

&lt;h3 id=&quot;53-posterior-mode-or-map&quot;&gt;5.3. Posterior mode or MAP&lt;/h3&gt;

&lt;p&gt;The value with highest posterior density.&lt;/p&gt;

&lt;p&gt;It answers the question of which single value is most strongly supported at the peak of the posterior density.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/posterior_point_estimates.png&quot; alt=&quot;Posterior summary statistics&quot; /&gt;&lt;/p&gt;

&lt;p&gt;These summaries can be close, but they need not be identical.&lt;/p&gt;

&lt;h2 id=&quot;6-credible-intervals&quot;&gt;6. Credible intervals&lt;/h2&gt;

&lt;p&gt;A Bayesian \(95\%\) credible interval \([a,b]\) satisfies:&lt;/p&gt;

\[P(a \le \theta \le b \mid D) = 0.95.\]

&lt;p&gt;That means:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Given the data and the prior, there is a \(95\%\) probability that \(\theta\) lies in that interval.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_credible_interval_95.png&quot; alt=&quot;The 95% credible interval on the posterior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_credible_interval_90.png&quot; alt=&quot;The 90% credible interval on the posterior&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;try-it-coverage-of-confidence-and-credible-intervals&quot;&gt;Try it: coverage of confidence and credible intervals&lt;/h3&gt;

&lt;p&gt;Repeat the experiment and count how often each interval contains the true value.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;interval-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;7-credible-interval-versus-confidence-interval&quot;&gt;7. Credible interval versus confidence interval&lt;/h2&gt;

&lt;h3 id=&quot;71-bayesian-credible-interval&quot;&gt;7.1. Bayesian credible interval&lt;/h3&gt;

&lt;p&gt;Directly about the parameter:&lt;/p&gt;

\[P(a \le \theta \le b \mid D) = 0.95.\]

&lt;h3 id=&quot;72-frequentist-confidence-interval&quot;&gt;7.2. Frequentist confidence interval&lt;/h3&gt;

&lt;p&gt;About the long-run behavior of an interval-generating procedure, not the probability that the specific parameter lies in the specific interval.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/credible_intervals_vs_confidence.png&quot; alt=&quot;Credible intervals versus confidence intervals&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This is why credible intervals usually feel more natural to interpret.&lt;/p&gt;

&lt;h2 id=&quot;8-how-prior-and-data-negotiate&quot;&gt;8. How prior and data negotiate&lt;/h2&gt;

&lt;p&gt;An important intuition is that the posterior always reflects a negotiation between prior strength and data strength: a strong prior with little data tends to keep the posterior closer to the prior, a weak prior with abundant data lets the posterior move closer to the likelihood, and a strong prior confronted with strong data often produces a narrow posterior located in a compromise region.&lt;/p&gt;

&lt;h3 id=&quot;81-a-concrete-example-same-prior-small-data-versus-large-data&quot;&gt;8.1. A concrete example: same prior, small data versus large data&lt;/h3&gt;

&lt;p&gt;Suppose the starting prior is Beta\((20,80)\), so before seeing data we believe the success rate is around \(0.2\).&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;If the new data are 8 successes out of 20 trials, the posterior becomes Beta\((28,92)\) with posterior mean about \(0.233\).&lt;/li&gt;
  &lt;li&gt;If the new data are 80 successes out of 200 trials, the posterior becomes Beta\((100,200)\) with posterior mean about \(0.333\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both datasets have the same raw rate of \(0.4\), but the larger dataset pulls the posterior much more strongly toward the data. This is exactly what it means to say that prior and data “negotiate”: with little data, the prior still has a strong voice; with more data, the posterior moves more clearly toward the new evidence and also becomes narrower.&lt;/p&gt;

&lt;h3 id=&quot;try-it-todays-posterior-is-tomorrows-prior&quot;&gt;Try it: today’s posterior is tomorrow’s prior&lt;/h3&gt;

&lt;p&gt;Each flip updates Beta(a + heads, b + tails); check against the grid approximation.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;conjugate-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;betabinom&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;9-sequential-updating&quot;&gt;9. Sequential updating&lt;/h2&gt;

&lt;p&gt;Bayesian updating is consistent over time. You can update once using all data at once, or update in stages by using today’s posterior as tomorrow’s prior, and the final result is the same so long as the model itself stays the same.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_sequential_update_step1.png&quot; alt=&quot;Sequential Bayesian updating step 1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_sequential_update_step2.png&quot; alt=&quot;Sequential Bayesian updating step 2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_sequential_update_step3.png&quot; alt=&quot;Sequential Bayesian updating step 3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_sequential_update_step4.png&quot; alt=&quot;Sequential Bayesian updating step 4&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;10-posterior-predictive-distributions&quot;&gt;10. Posterior predictive distributions&lt;/h2&gt;

&lt;p&gt;The posterior does not only tell us about the parameter. It also supports prediction for future data.&lt;/p&gt;

&lt;p&gt;Examples include future sales, future pass counts, and future call volumes, which is why posterior predictive reasoning is often closer to the actual decisions people care about than the posterior of a parameter alone.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/posterior_predictive.png&quot; alt=&quot;Posterior predictive distribution&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This is where Bayesian inference becomes immediately useful for decision-making.&lt;/p&gt;

&lt;h2 id=&quot;11-common-misunderstandings&quot;&gt;11. Common misunderstandings&lt;/h2&gt;

&lt;h3 id=&quot;111-the-posterior-is-just-the-normalized-likelihood&quot;&gt;11.1. “The posterior is just the normalized likelihood”&lt;/h3&gt;

&lt;p&gt;Not necessarily. The prior matters too, especially with limited data.&lt;/p&gt;

&lt;h3 id=&quot;112-the-posterior-mean-is-the-one-true-answer&quot;&gt;11.2. “The posterior mean is the one true answer”&lt;/h3&gt;

&lt;p&gt;Not always. Sometimes intervals, threshold probabilities, or predictive distributions matter more.&lt;/p&gt;

&lt;h3 id=&quot;113-once-the-posterior-looks-nice-we-are-done&quot;&gt;11.3. “Once the posterior looks nice, we are done”&lt;/h3&gt;

&lt;p&gt;No. A nice posterior cannot rescue a poor model. Model checking still matters.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The posterior is the updated belief after combining prior knowledge and data.&lt;/strong&gt; It is central because it lets us compute probabilities about parameters, build credible intervals, summarize uncertainty, and make predictions about future observations. The lasting lesson is that the posterior is not merely an intermediate formula, but the main object from which Bayesian reasoning becomes actionable: it combines old knowledge with new evidence, supports direct probability statements about parameters, and becomes most useful when it is used to answer practical questions about intervals, thresholds, and future outcomes.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-exact-precision-weighted-normalnormal-posterior-by-hand&quot;&gt;Worked Numerical Example: Exact Precision-Weighted Normal–Normal Posterior by Hand&lt;/h3&gt;

&lt;p&gt;Suppose your prior for a battery’s true life \(\mu\) is \(\mathcal{N}(\mu_0 = 10.0\text{ hr},\; \sigma_0^2 = 4.0)\) (prior precision \(\tau_0 = 1/4 = 0.25\)). You test \(n = 4\) batteries (known measurement variance \(\sigma^2 = 4.0\)) and observe sample mean \(\bar{y} = 13.0\text{ hr}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Data precision:&lt;/strong&gt; \(\tau_{\text{data}} = \frac{n}{\sigma^2} = \frac{4}{4.0} = \mathbf{1.00}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior precision &amp;amp; variance (precisions simply ADD!):&lt;/strong&gt;
\(\tau_{\text{post}} = \tau_0 + \tau_{\text{data}} = 0.25 + 1.00 = \mathbf{1.25} \implies \sigma_{\text{post}}^2 = \frac{1}{1.25} = \mathbf{0.80} \quad (\sigma_{\text{post}} \approx 0.894\text{ hr}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior mean (precision-weighted average!):&lt;/strong&gt;
\(\mu_{\text{post}} = \frac{0.25(10.0) + 1.00(13.0)}{1.25} = \frac{2.5 + 13.0}{1.25} = \mathbf{12.40\text{ hr}}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;95% Credible Interval:&lt;/strong&gt; \(12.40 \pm 1.96(0.894) = \mathbf{[10.65,\; 14.15]\text{ hr}}\).
Notice how the posterior variance (\(0.80\)) is strictly &lt;em&gt;smaller&lt;/em&gt; than both the prior variance (\(4.0\)) and the data-only variance (\(1.0\))—combining two independent sources of information always increases total precision!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-communicating-posterior-results-clearly&quot;&gt;Explanation: Four Rules for Communicating Posterior Results Clearly&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Never reduce a rich posterior to only its mean:&lt;/strong&gt; Always report at least a central estimate + 90% or 95% credible interval (and plot the density whenever skewed or multimodal!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use HDI for strongly skewed or boundary-hugging posteriors:&lt;/strong&gt; For \(\mathrm{Beta}(1, 14)\), the 95% HDI is \([0.000,\; 0.193]\) (containing the mode at 0!), whereas the ETI \([0.002,\; 0.232]\) wastes width on the right tail and excludes the most probable value &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Separate posterior parameter intervals from posterior predictive intervals:&lt;/strong&gt; Predicting the &lt;em&gt;mean&lt;/em&gt; battery life uses \(\sigma_{\text{post}} = 0.894\); predicting the &lt;em&gt;next single battery&lt;/em&gt; adds \(\sigma^2 = 4.0 \implies \mathrm{SD}_{\text{pred}} = \sqrt{4.0 + 0.80} \approx 2.19\text{ hr}\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check ROPE (Region of Practical Equivalence):&lt;/strong&gt; Asking &lt;em&gt;“what is \(P(\lvert\theta\rvert &amp;lt; 0.01 \mid y)\)?”&lt;/em&gt; turns raw posteriors into actionable business or clinical decisions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the battery Normal–Normal example above, if we test \(n = 16\) batteries instead of \(4\) (same \(\bar{y} = 13.0, \sigma^2 = 4.0\)), what is the new data precision \(\tau_{\text{data}}\), total posterior precision \(\tau_{\text{post}}\), and posterior mean \(\mu_{\text{post}}\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Watch prior and likelihood combine into a normalized posterior, the central object of this lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R1vcdhPBlXA&quot;&gt;Statistical Rethinking 2023 - 02 - The Garden of Forking Data&lt;/a&gt; — Richard McElreath, English. Watch a posterior updated by counting compatible data stories, supporting intervals and probabilities read off the posterior.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YPceDssQFWo&quot;&gt;Bayesian Statistics: Credible vs Confidence Intervals&lt;/a&gt; — Academia Elevated, English. Watch a credible interval stated as a posterior probability, the reporting language of the lesson.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why does the posterior in the 7-out-of-10 coin example not sit exactly at \(0.7\)?&lt;/li&gt;
  &lt;li&gt;Explain the difference between a credible interval and a confidence interval.&lt;/li&gt;
  &lt;li&gt;In your own work, what threshold probability matters more than a simple average?&lt;/li&gt;
  &lt;li&gt;Why is posterior predictive often more useful than the posterior of a parameter alone?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 2.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 5-6.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2-3.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter02/02_05_conjugate_priors/&quot;&gt;2.5 Conjugate Priors and the Algebra of Bayesian Updating&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 2.3: Prior - Encoding What We Know Before Data</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_03_prior/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_03_prior</id>
   <content type="html">&lt;p&gt;Nothing sparks more anxiety among newcomers to Bayesian statistics than choosing a &lt;strong&gt;prior distribution \(p(\theta)\)&lt;/strong&gt;: &lt;em&gt;“Isn’t picking a prior just making things up? Shouldn’t I always use a completely flat Uniform prior to stay ‘objective’?”&lt;/em&gt; Surprisingly, a “flat” prior is often the &lt;em&gt;worst&lt;/em&gt; possible choice! Put a flat \(\mathrm{Uniform}(-\infty, \infty)\) prior on a regression slope or an improper flat prior in 20 dimensions, and you imply that a slope of \(+1{,}000{,}000\) is just as plausible as \(+0.5\)—inviting wild overfitting and broken sampling!&lt;/p&gt;

&lt;p&gt;This lesson replaces fear of priors with disciplined engineering: &lt;strong&gt;weakly informative priors&lt;/strong&gt;, &lt;strong&gt;prior predictive checks&lt;/strong&gt;, &lt;strong&gt;sensitivity analysis&lt;/strong&gt;, and understanding &lt;em&gt;why&lt;/em&gt; flat priors aren’t even invariant under simple parameter transformations.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-spectrum-of-priors-in-modern-bayesian-workflow&quot;&gt;Key ideas: The Spectrum of Priors in Modern Bayesian Workflow&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Flat / Uninformative Priors (Handle With Care!):&lt;/strong&gt; A flat prior on \(p \in (0,1)\) is &lt;strong&gt;NOT&lt;/strong&gt; flat on log-odds \(\eta = \ln\frac{p}{1-p}\) (it becomes a bell-shaped logistic density!). Flat priors on unbounded scales can even yield &lt;em&gt;improper&lt;/em&gt; posteriors that fail to integrate to 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Weakly Informative Priors (Modern Default — Gelman/McElreath):&lt;/strong&gt; Broad enough to let reasonable data speak freely, yet tight enough to rule out physically absurd parameter values (e.g., \(\beta \sim \mathcal{N}(0, 2.5^2)\) on standardized predictors)—acting as principled regularization!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Informative / Domain Priors:&lt;/strong&gt; Encodes genuine prior scientific evidence (e.g., historical baseline conversion rates, physical constants, or yesterday’s posterior!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prior Sensitivity Analysis:&lt;/strong&gt; The honest scientific safeguard—refit your model with a weaker prior and a stronger prior; if your main conclusion barely moves, your result is driven by data, not prior assumptions!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you should see the prior as a natural part of inference, know how to translate verbal knowledge into a simple prior, and understand when weak or strong priors make sense.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; Before launching a new campaign, a marketing team believes the click-through rate is usually around \(2\%\) to \(5\%\) and rarely above \(10\%\). That is exactly the kind of information a prior is meant to encode.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If you already know a parameter cannot be negative or cannot exceed 1, is that already enough information to shape a prior?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;opening-idea-we-rarely-start-from-zero&quot;&gt;Opening idea: we rarely start from zero&lt;/h2&gt;

&lt;p&gt;Suppose you are evaluating a new ad campaign. Before seeing this week’s data, you already know that past campaigns usually had click rates around \(2\%\) to \(5\%\), rates above \(10\%\) are rare, and rates extremely close to 0 are also unlikely for a well-targeted audience.&lt;/p&gt;

&lt;p&gt;Bayesian inference says that ignoring all of that would be wasteful. The prior is the place where we encode that earlier knowledge clearly.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/what_is_prior.png&quot; alt=&quot;What a prior means&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-what-is-a-prior&quot;&gt;1. What is a prior?&lt;/h2&gt;

&lt;p&gt;The prior \(P(\theta)\) is the distribution describing what we believe about \(\theta\) before seeing the current data.&lt;/p&gt;

&lt;p&gt;In Bayes’ theorem:&lt;/p&gt;

\[P(\theta \mid D) \propto P(D \mid \theta)P(\theta),\]

&lt;p&gt;the prior is the starting point, the likelihood is the data’s voice, and the posterior is the updated belief.&lt;/p&gt;

&lt;h2 id=&quot;2-where-can-priors-come-from&quot;&gt;2. Where can priors come from?&lt;/h2&gt;

&lt;h3 id=&quot;21-previous-data&quot;&gt;2.1. Previous data&lt;/h3&gt;

&lt;p&gt;Priors can come from very ordinary sources such as pass rates from earlier semesters, defect rates from previous production batches, or conversion rates from earlier campaigns.&lt;/p&gt;

&lt;h3 id=&quot;22-domain-knowledge&quot;&gt;2.2. Domain knowledge&lt;/h3&gt;

&lt;p&gt;They can also come from domain knowledge, for example when a doctor knows what treatment success ranges are realistic, when an engineer knows that a sensor cannot drift too far, or when a teacher knows that a pass rate near \(99\%\) is unrealistic for a very hard course.&lt;/p&gt;

&lt;h3 id=&quot;23-logical-or-physical-constraints&quot;&gt;2.3. Logical or physical constraints&lt;/h3&gt;

&lt;p&gt;Another source is logical or physical constraint, such as the fact that probabilities must lie in \([0,1]\), variances must be positive, and waiting times cannot be negative.&lt;/p&gt;

&lt;h3 id=&quot;24-cautious-defaults-when-little-is-known&quot;&gt;2.4. Cautious defaults when little is known&lt;/h3&gt;

&lt;p&gt;Even when we do not know very much, we usually still know something minimal. We may know, for instance, that a probability cannot be negative, that a defect rate is unlikely to be as high as \(95\%\) if the product is still on the market, or that an extremely large regression coefficient would be implausible in the application domain. That is already information, and it is already enough to shape a prior.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/why_need_prior.png&quot; alt=&quot;Why we need priors&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-turning-words-into-a-prior&quot;&gt;3. Turning words into a prior&lt;/h2&gt;

&lt;p&gt;Suppose the marketing team says:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“The conversion rate is probably around \(20\%\), rarely below \(10\%\), and unlikely to exceed \(35\%\).”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Since the parameter is a probability, a Beta prior is natural. Beta\((8,32)\) has mean:&lt;/p&gt;

\[\frac{8}{8+32} = 0.2.\]

&lt;p&gt;This prior says that the center is around \(0.2\), that nearby values such as \(0.15\) and \(0.25\) remain plausible, and that very extreme values receive less support.&lt;/p&gt;

&lt;h2 id=&quot;4-same-mean-different-confidence&quot;&gt;4. Same mean, different confidence&lt;/h2&gt;

&lt;p&gt;Put four priors side by side and the message becomes clearer: Beta\((1,1)\) stays almost flat, Beta\((5,5)\) leans gently toward \(0.5\), Beta\((20,80)\) centers around \(0.2\) with moderate confidence, and Beta\((100,400)\) stays around \(0.2\) much more tightly.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_flat_uniform.png&quot; alt=&quot;An almost flat prior on [0,1]&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_centered_half.png&quot; alt=&quot;A prior gently centered around 0.5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_centered_low_moderate.png&quot; alt=&quot;A lower-centered prior with moderate concentration&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_centered_low_strong.png&quot; alt=&quot;A lower-centered prior with strong concentration&quot; /&gt;&lt;/p&gt;

&lt;p&gt;So a prior communicates two things at once: where the center is, and how strongly we believe in that center.&lt;/p&gt;

&lt;h3 id=&quot;41-a-concrete-example-same-mean-02-different-strength&quot;&gt;4.1. A concrete example: same mean \(0.2\), different strength&lt;/h3&gt;

&lt;p&gt;Suppose we observe 6 purchases out of 20 visits, so the raw data rate is \(0.30\).&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;If the prior is Beta\((8,32)\), the posterior becomes Beta\((14,46)\), with posterior mean about \(0.233\).&lt;/li&gt;
  &lt;li&gt;If the prior is Beta\((40,160)\), the posterior becomes Beta\((46,174)\), with posterior mean about \(0.209\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both priors start with the same prior mean of \(0.2\), but the second prior is much stronger, so the posterior moves less toward the data. This makes the main point very clear: a prior is not only about where we start, but also about how firmly we start there.&lt;/p&gt;

&lt;h2 id=&quot;5-common-types-of-priors&quot;&gt;5. Common types of priors&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/prior_types_spectrum.png&quot; alt=&quot;A spectrum from weak to strong priors&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;51-very-weak-or-flat-priors&quot;&gt;5.1. Very weak or flat priors&lt;/h3&gt;

&lt;p&gt;Example: Beta\((1,1)\) for a probability.&lt;/p&gt;

&lt;p&gt;This leaves a great deal of room for the data to dominate.&lt;/p&gt;

&lt;h3 id=&quot;52-weakly-informative-priors&quot;&gt;5.2. Weakly informative priors&lt;/h3&gt;

&lt;p&gt;Example: Beta\((2,2)\).&lt;/p&gt;

&lt;p&gt;These rule out unreasonable extremes without forcing a strong opinion.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/weakly_informative_prior_example.png&quot; alt=&quot;Weakly informative prior example&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;53-strongly-informative-priors&quot;&gt;5.3. Strongly informative priors&lt;/h3&gt;

&lt;p&gt;Example: Beta\((50,50)\).&lt;/p&gt;

&lt;p&gt;These carry substantial previous knowledge and can strongly influence the posterior when new data are scarce.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/strongly_informative_prior_example.png&quot; alt=&quot;Strong prior example&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-mixture-priors-when-one-prior-is-not-enough&quot;&gt;6. Mixture priors: when one prior is not enough&lt;/h2&gt;

&lt;p&gt;So far, we have mostly acted as if prior knowledge could be summarized by a single family with a single center. In practice, however, prior knowledge can sometimes reflect genuine uncertainty between multiple plausible scenarios rather than uncertainty inside only one scenario.&lt;/p&gt;

&lt;p&gt;Suppose a team is trying to infer a purchase rate \(\theta\) for a new campaign. The operations team believes the campaign may fall into one of two regimes: either it will be fairly weak, with a rate around \(10\%\), or it will be fairly strong, with a rate around \(30\%\), and before seeing current data both possibilities remain genuinely plausible.&lt;/p&gt;

&lt;p&gt;Instead of forcing that belief into one single Beta prior, we can use a mixture prior:&lt;/p&gt;

\[p(\theta) = w_1 p_1(\theta) + w_2 p_2(\theta), \qquad w_1 + w_2 = 1.\]

&lt;p&gt;For example,&lt;/p&gt;

\[p(\theta) = 0.6 \,\text{Beta}(2,18) + 0.4 \,\text{Beta}(6,14).\]

&lt;p&gt;Read in words, this means that before seeing the current data we place prior probability \(0.6\) on a weaker scenario and prior probability \(0.4\) on a stronger scenario, while still using a familiar Beta distribution inside each scenario to describe uncertainty about \(\theta\).&lt;/p&gt;

&lt;p&gt;Once data arrive, the posterior does two things at once: it updates each component prior in the usual way, and it also shifts the relative weights of the scenarios according to which one the data support more strongly. That is the key difference between a single prior and a mixture prior. With a single prior, the data update the parameter; with a mixture prior, the data update both the parameter and the relative credibility of competing prior stories about the world.&lt;/p&gt;

&lt;h2 id=&quot;7-why-priors-help-in-practice&quot;&gt;7. Why priors help in practice&lt;/h2&gt;

&lt;h3 id=&quot;71-they-stabilize-small-datasets&quot;&gt;7.1. They stabilize small datasets&lt;/h3&gt;

&lt;p&gt;If you flip a coin 3 times and get 3 heads, MLE gives \(\hat{\theta}=1\). That is too extreme for so little data. A reasonable prior pulls the inference back toward a more cautious conclusion.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_regularization_likelihood.png&quot; alt=&quot;Likelihood using only the observed 3 successes out of 3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_regularization_prior.png&quot; alt=&quot;A Beta(2,2) prior pulling the inference away from an extreme conclusion&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_prior_regularization_posterior.png&quot; alt=&quot;The posterior after combining the weak dataset with the prior&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;72-they-let-knowledge-accumulate&quot;&gt;7.2. They let knowledge accumulate&lt;/h3&gt;

&lt;p&gt;Yesterday’s posterior can become today’s prior. This matches how science and decision-making actually work.&lt;/p&gt;

&lt;h3 id=&quot;73-they-make-assumptions-visible&quot;&gt;7.3. They make assumptions visible&lt;/h3&gt;

&lt;p&gt;Instead of hiding assumptions, Bayesian analysis writes them down explicitly.&lt;/p&gt;

&lt;h2 id=&quot;8-prior-predictive-checks&quot;&gt;8. Prior predictive checks&lt;/h2&gt;

&lt;p&gt;A good prior should not only sound reasonable at the parameter level. It should also generate reasonable fake data.&lt;/p&gt;

&lt;p&gt;The idea is to draw \(\theta\) from the prior, simulate data from the model, and then check whether the resulting fake outcomes look plausible.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/prior_predictive_check.png&quot; alt=&quot;Prior predictive check&quot; /&gt;&lt;/p&gt;

&lt;p&gt;If a prior for a class pass rate keeps generating absurd outcomes, then the prior needs revision.&lt;/p&gt;

&lt;h3 id=&quot;try-it-prior-predictive--which-data-does-this-prior-expect&quot;&gt;Try it: prior predictive — which data does this prior expect?&lt;/h3&gt;

&lt;p&gt;Simulate data from the prior and compare with the closed form; pick an observed k to see whether the prior finds it surprising.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;likelihood-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;predictive&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;try-it-strong-versus-weak-priors&quot;&gt;Try it: strong versus weak priors&lt;/h3&gt;

&lt;p&gt;Pick Beta(1,1), Beta(2,2), Beta(10,10) or Beta(8,2) and watch the posterior move after each flip.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;conjugate-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;betabinom&quot; data-a=&quot;10&quot; data-b=&quot;10&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;9-sensitivity-analysis&quot;&gt;9. Sensitivity analysis&lt;/h2&gt;

&lt;p&gt;A healthy Bayesian habit is to ask:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If I change the prior a little, do my conclusions change a lot?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/prior_sensitivity_weak_data.png&quot; alt=&quot;Prior sensitivity with weak data&quot; /&gt;&lt;/p&gt;

&lt;p&gt;With little data, different reasonable priors can matter more.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/prior_sensitivity_strong_data.png&quot; alt=&quot;Prior sensitivity with strong data&quot; /&gt;&lt;/p&gt;

&lt;p&gt;With strong data, reasonable priors often lead to similar posteriors.&lt;/p&gt;

&lt;h2 id=&quot;10-common-objections&quot;&gt;10. Common objections&lt;/h2&gt;

&lt;h3 id=&quot;101-priors-are-too-subjective&quot;&gt;10.1. “Priors are too subjective”&lt;/h3&gt;

&lt;p&gt;All analyses contain assumptions. Priors simply make some of them visible and testable.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/addressing_subjectivity.png&quot; alt=&quot;On subjectivity and priors&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;102-let-the-data-speak-for-themselves&quot;&gt;10.2. “Let the data speak for themselves”&lt;/h3&gt;

&lt;p&gt;Data never speak without a model. Choosing the model is already an assumption.&lt;/p&gt;

&lt;h3 id=&quot;103-strong-priors-are-unfair&quot;&gt;10.3. “Strong priors are unfair”&lt;/h3&gt;

&lt;p&gt;They are only problematic when poorly justified or poorly reported. If strong prior information is real, using it can be entirely appropriate.&lt;/p&gt;

&lt;h2 id=&quot;11-practical-rules-for-choosing-priors&quot;&gt;11. Practical rules for choosing priors&lt;/h2&gt;

&lt;p&gt;A sensible workflow usually starts from the story of the problem rather than from a formula, then matches the distribution family to the parameter’s domain, explains the prior in words before fixing its parameters, runs prior predictive checks, performs sensitivity analysis, and finally reports the prior choice clearly enough that someone else could question or revise it.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;A prior is where Bayesian analysis stores background knowledge in a transparent way.&lt;/strong&gt; A good prior reflects what is known, respects the parameter’s domain, generates plausible fake data, and survives reasonable sensitivity checks.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key takeaways.&lt;/strong&gt; A prior is not a random guess, but a way to encode background knowledge, constraints, or uncertainty before the current data; a good prior should be understandable in plain language rather than only in mathematical notation; and prior predictive checks together with sensitivity analysis are essential habits for evaluating priors.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-comparing-three-priors-on-the-exact-same-10-flip-dataset-k7-n10&quot;&gt;Worked Numerical Example: Comparing Three Priors on the Exact Same 10-Flip Dataset (\(k=7, n=10\))&lt;/h3&gt;

&lt;p&gt;Watch how three different Beta priors update on \(k = 7\) heads in \(n = 10\) flips (sample proportion \(\hat{p} = 0.70\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Prior Family&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Prior Mean&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Prior Weight (\(\alpha+\beta\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Posterior Beta&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Posterior Mean&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Data Weight Share&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Flat \(\mathrm{Beta}(1, 1)\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.50\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mathrm{Beta}(8, 4)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(8/12 = \mathbf{0.667}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(10/12 = 83\%\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Weakly Informative \(\mathrm{Beta}(2, 2)\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.50\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(4\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mathrm{Beta}(9, 5)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(9/14 = \mathbf{0.643}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(10/14 = 71\%\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Strong Skeptical \(\mathrm{Beta}(20, 20)\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.50\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(40\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mathrm{Beta}(27, 23)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(27/50 = \mathbf{0.540}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(10/50 = 20\%\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Now scale the exact same 70% rate up to \(n = 1{,}000\) flips (\(k = 700\)): even the strong skeptical prior \(\mathrm{Beta}(20, 20)\) updates to \(\mathrm{Beta}(720, 320)\) with posterior mean &lt;strong&gt;\(0.692\)&lt;/strong&gt;—all three priors converge!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-defensible-prior-selection&quot;&gt;Explanation: Four Rules for Defensible Prior Selection&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always justify priors on the &lt;em&gt;outcome scale&lt;/em&gt; via Prior Predictive Checks:&lt;/strong&gt; Don’t guess whether \(\beta \sim \mathcal{N}(0, 10^2)\) is “weak”—simulate fake data from it! On a logistic link, \(\beta = 10\) forces probabilities to exact &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0000&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.0000&lt;/code&gt; (horribly informative!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Standardize predictors before setting default priors:&lt;/strong&gt; Putting \(x\) in units of SD (mean 0, SD 1) makes \(\mathcal{N}(0, 1)\) or \(\mathcal{N}(0, 2.5)\) clean, portable weakly informative priors across datasets.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never peek at your data to tune a tighter prior around \(\hat{\theta}\):&lt;/strong&gt; Using the same data twice (double-dipping) artificially shrinks your credible interval.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always run a 2-minute prior sensitivity check for key decisions:&lt;/strong&gt; Showing that conclusions hold across both skeptical and flat priors builds instant trust with reviewers and stakeholders.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If you put a flat prior \(\beta \sim \mathcal{N}(0, 10^2)\) on the intercept of a &lt;strong&gt;logistic regression&lt;/strong&gt; (where \(p = \sigma(\beta)\)), where does most of the prior probability mass land on the probability scale \(p \in (0, 1)\)—uniformly in the middle, or piled up at the extreme walls &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=brt2J5VgAHs&quot;&gt;Bayesian Statistics: What Are Priors?&lt;/a&gt; — Academia Elevated, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Watch a prior stated as belief before data, the translation from verbal knowledge to a distribution in this lesson.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Bayesian Priors Explained&lt;/td&gt;
          &lt;td&gt;Prior Modelling &amp;amp; Prior Predictive Checks](https://www.youtube.com/watch?v=G3ludfAUAng) — stats 4 good, English. Watch prior predictive checks catch a prior that generates impossible data, supporting the lesson’s weak-versus-strong discussion.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=UH6-9FU6bRg&quot;&gt;Keynote 2: Weakly Informative Priors – Andrew Gelman&lt;/a&gt; — AISTATS 2014, English. Watch Andrew Gelman on weakly informative priors, the default starting point this lesson recommends.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Think of one real problem and write three sentences describing your prior knowledge.&lt;/li&gt;
  &lt;li&gt;Why is Beta a natural prior for a pass rate?&lt;/li&gt;
  &lt;li&gt;When would you choose a weak prior rather than a strong one?&lt;/li&gt;
  &lt;li&gt;What exactly is a prior predictive check testing?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 2.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2-3.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 6.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter02/02_04_posterior/&quot;&gt;2.4 Posterior - Updating Beliefs with Data&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 2.2: Likelihood - The Data's Story Under a Model</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_02_likelihood/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_02_likelihood</id>
   <content type="html">&lt;p&gt;The single most subtle—and most important—distinction in all of statistical inference is the difference between &lt;strong&gt;probability&lt;/strong&gt; and &lt;strong&gt;likelihood&lt;/strong&gt;. They use the exact same mathematical formula \(p(y \mid \theta)\), yet they treat &lt;em&gt;opposite&lt;/em&gt; symbols as the variable! When \(\theta\) is fixed and \(y\) varies, \(p(y\mid\theta)\) is a &lt;strong&gt;probability distribution&lt;/strong&gt; over data (summing to 1). The instant you observe your actual data \(y\), freeze \(y\), and vary \(\theta\), that exact expression becomes the &lt;strong&gt;likelihood function \(L(\theta \mid y)\)&lt;/strong&gt;—and it does &lt;strong&gt;NOT&lt;/strong&gt; integrate to 1 over \(\theta\)!&lt;/p&gt;

&lt;p&gt;This lesson builds rock-solid intuition for the likelihood function, the &lt;strong&gt;Likelihood Principle&lt;/strong&gt;, why log-likelihoods sum across i.i.d. data, and how the curvature of the log-likelihood measures Fisher information.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-probability-vs-likelihood--the-likelihood-principle&quot;&gt;Key ideas: Probability vs. Likelihood &amp;amp; The Likelihood Principle&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Same Formula, Opposite Variable:&lt;/strong&gt; Probability fixes \(\theta\) and asks &lt;em&gt;“what data might occur?”&lt;/em&gt; Likelihood fixes observed data \(y\) and asks &lt;em&gt;“how well does each \(\theta\) explain what actually occurred?”&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Likelihood Is NOT a Probability Distribution Over \(\theta\):&lt;/strong&gt; Integrating \(L(\theta) = p(y\mid\theta)\) over \(\theta\) does &lt;em&gt;not&lt;/em&gt; equal 1—you must multiply by a prior \(p(\theta)\) and divide by \(p(y)\) to obtain a valid posterior probability over \(\theta\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Conditional Independence Factorizes the Likelihood:&lt;/strong&gt; Given \(\theta\), i.i.d. observations factor cleanly: \(L(\theta) = \prod_{i=1}^n p(y_i\mid\theta) \iff \ell(\theta) = \sum_{i=1}^n \log p(y_i\mid\theta)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sufficient Statistics:&lt;/strong&gt; Notice that for 10 coin flips, the Binomial likelihood \(p^7(1-p)^3\) depends on the data &lt;em&gt;only&lt;/em&gt; through \((n=10, k=7)\)—the exact order of heads and tails carries zero extra information about \(p\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you should understand likelihood as a tool for &lt;strong&gt;comparing parameter values using data&lt;/strong&gt;, avoid confusing it with the posterior, and know how to write a likelihood from a simple generative story.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; You flip a coin 10 times and observe 7 heads. Does this dataset sound more reasonable under \(\theta=0.5\) or under \(\theta=0.7\)?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Is likelihood about the probability of the data, or the probability of the parameter?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;opening-question-which-hypothesis-does-the-data-support&quot;&gt;Opening question: which hypothesis does the data support?&lt;/h2&gt;

&lt;p&gt;Suppose you flip a coin 10 times and observe 7 heads. The key questions are not vague questions about the data in isolation, but comparative questions of the following form: if \(\theta = 0.5\), how reasonable is this dataset; if \(\theta = 0.7\), how reasonable is it; and if \(\theta = 0.1\), does the same dataset now look highly implausible?&lt;/p&gt;

&lt;p&gt;Likelihood is exactly the tool that answers those questions.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/likelihood_data_story.png&quot; alt=&quot;Likelihood as the data&apos;s story under each hypothesis&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-what-is-likelihood&quot;&gt;1. What is likelihood?&lt;/h2&gt;

&lt;p&gt;With observed data \(D\), the likelihood of \(\theta\) is:&lt;/p&gt;

\[\mathcal{L}(\theta \mid D) = P(D \mid \theta).\]

&lt;p&gt;The important change in viewpoint is that the data are now treated as fixed, the parameter is allowed to vary, and we ask which values of the parameter make the observed data more plausible.&lt;/p&gt;

&lt;h2 id=&quot;2-coin-example-7-heads-out-of-10&quot;&gt;2. Coin example: 7 heads out of 10&lt;/h2&gt;

&lt;p&gt;If \(\theta\) is the probability of heads, then:&lt;/p&gt;

\[\mathcal{L}(\theta \mid D) = \binom{10}{7}\theta^7(1-\theta)^3.\]

&lt;p&gt;This tells us that values near \(0.7\) fit the data well, values near \(0.5\) fit the data moderately well, and values near \(0.1\) fit the data very poorly.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/likelihood_function.png&quot; alt=&quot;Likelihood for 7 heads out of 10 tosses&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;21-reading-this-example-numerically&quot;&gt;2.1. Reading this example numerically&lt;/h3&gt;

&lt;p&gt;If we compute a few values directly, we get:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
\[\mathcal{L}(0.7 \mid D) \approx 0.267\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathcal{L}(0.5 \mid D) \approx 0.117\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathcal{L}(0.9 \mid D) \approx 0.057\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This gives a very concrete interpretation. The data 7 heads out of 10 support \(\theta=0.7\) about \(2.28\) times more strongly than \(\theta=0.5\), and about \(4.65\) times more strongly than \(\theta=0.9\). In other words, observing 7/10 does not mean the true parameter must be exactly \(0.7\); it means values around that region explain the observed data much better than some other candidate values.&lt;/p&gt;

&lt;h2 id=&quot;3-likelihood-is-about-relative-support&quot;&gt;3. Likelihood is about relative support&lt;/h2&gt;

&lt;p&gt;The most useful way to read likelihood is comparatively.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

\[\frac{\mathcal{L}(0.7 \mid D)}{\mathcal{L}(0.5 \mid D)} \approx 2.28.\]

&lt;p&gt;So the observed data support \(\theta = 0.7\) about 2.28 times more strongly than \(\theta = 0.5\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/likelihood_ratio.png&quot; alt=&quot;Likelihood ratios compare hypotheses&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This is the key point: likelihood is not a probability distribution over the parameter, but rather a scoring rule for how well different parameter values explain the observed data.&lt;/p&gt;

&lt;h2 id=&quot;4-likelihood-is-not-the-probability-of-the-parameter&quot;&gt;4. Likelihood is not the probability of the parameter&lt;/h2&gt;

&lt;p&gt;This confusion is extremely common.&lt;/p&gt;

&lt;h3 id=&quot;41-probability-view&quot;&gt;4.1. Probability view&lt;/h3&gt;

&lt;p&gt;If \(\theta\) is fixed and the data vary, then \(P(D \mid \theta)\) is a probability for data.&lt;/p&gt;

&lt;h3 id=&quot;42-likelihood-view&quot;&gt;4.2. Likelihood view&lt;/h3&gt;

&lt;p&gt;If the data are fixed and \(\theta\) varies, then the same expression is read as likelihood.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_likelihood_concept.png&quot; alt=&quot;Likelihood as a function of the parameter with fixed data&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_posterior_probability_concept.png&quot; alt=&quot;Posterior probability is what lets us talk directly about parameter uncertainty&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Why is it not a probability distribution over \(\theta\)? Because its integral over \(\theta\) usually does &lt;strong&gt;not&lt;/strong&gt; equal 1.&lt;/p&gt;

&lt;p&gt;That is fine. Likelihood was never meant to be a probability distribution over the parameter.&lt;/p&gt;

&lt;h2 id=&quot;5-real-world-examples&quot;&gt;5. Real-world examples&lt;/h2&gt;

&lt;h3 id=&quot;51-recovery-after-treatment&quot;&gt;5.1. Recovery after treatment&lt;/h3&gt;

&lt;p&gt;Suppose 12 out of 15 patients recover. If \(\theta\) is the recovery probability:&lt;/p&gt;

\[\mathcal{L}(\theta \mid D) = \binom{15}{12}\theta^{12}(1-\theta)^3.\]

&lt;p&gt;Values of \(\theta\) near \(0.8\) are strongly supported, while values near \(0.2\) are not.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/binomial_likelihood_recovery.png&quot; alt=&quot;Likelihood for recovery data&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;52-calls-per-hour&quot;&gt;5.2. Calls per hour&lt;/h3&gt;

&lt;p&gt;Suppose a call center receives 8 calls in one hour. If \(\lambda\) is the mean number of calls per hour and the model is Poisson:&lt;/p&gt;

\[\mathcal{L}(\lambda \mid D) = \frac{\lambda^8 e^{-\lambda}}{8!}.\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/poisson_likelihood_calls.png&quot; alt=&quot;Likelihood for Poisson count data&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;try-it-poisson-likelihood-for-call-counts&quot;&gt;Try it: Poisson likelihood for call counts&lt;/h3&gt;

&lt;p&gt;Each observation multiplies in another factor; the peak around the sample mean narrows.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;likelihood-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;poisson&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;53-student-heights&quot;&gt;5.3. Student heights&lt;/h3&gt;

&lt;p&gt;Suppose you measure several student heights and want to infer the class mean \(\mu\) under a Normal model. The likelihood tells you which mean values make the observed measurements more plausible.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/normal_likelihood_heights.png&quot; alt=&quot;Likelihood for Normal measurement data&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-how-to-build-a-likelihood&quot;&gt;6. How to build a likelihood&lt;/h2&gt;

&lt;p&gt;A reliable way to build a likelihood is to move in three steps. First, tell the data story as clearly as possible: are you counting successes and failures, counting events over time, or measuring a continuous quantity with noise? Second, choose a generative model that actually matches that story, such as Binomial for successes out of \(n\) trials, Poisson for counts over time, or Normal for continuous noisy measurements. Third, write \(P(D \mid \theta)\) and then read it as a function of \(\theta\) rather than as a probability distribution over the parameter.&lt;/p&gt;

&lt;h2 id=&quot;7-when-the-data-generating-mechanism-matters&quot;&gt;7. When the data-generating mechanism matters&lt;/h2&gt;

&lt;p&gt;In many problems, writing the correct likelihood is not only about choosing a familiar distribution family. It also depends on how the information was generated or revealed.&lt;/p&gt;

&lt;h3 id=&quot;71-success-on-the-third-attempt&quot;&gt;7.1. Success on the third attempt&lt;/h3&gt;

&lt;p&gt;Suppose a student keeps taking an exam until passing, and the observed data are “the student passed on the third attempt.” If \(\theta\) is the pass probability on each attempt, the actual data story is that the first two attempts were failures and the third attempt was the first success. That means the likelihood is&lt;/p&gt;

\[P(Y=3 \mid \theta) = \theta(1-\theta)^2.\]

&lt;p&gt;If we incorrectly read this as a Binomial problem of “1 success in 3 trials,” we have already written the wrong likelihood. What matters is the temporal structure of the observation.&lt;/p&gt;

&lt;h3 id=&quot;72-sampling-without-replacement&quot;&gt;7.2. Sampling without replacement&lt;/h3&gt;

&lt;p&gt;Suppose balls are drawn from a box without replacement. Then the likelihood for the next draw depends not only on the hypothesis about the box, but also on the history of previous draws. The observations are no longer conditionally independent in the same way they would be under a Binomial model, because the probabilities change after each draw.&lt;/p&gt;

&lt;h3 id=&quot;73-information-revealed-strategically&quot;&gt;7.3. Information revealed strategically&lt;/h3&gt;

&lt;p&gt;In problems such as Monty Hall, the data are not merely “a door was opened.” What matters is that the host knows where the prize is and deliberately opens a door hiding a goat. If we ignore that mechanism, we write the wrong model. The general lesson is that likelihood depends not only on the final observed outcome, but also on the rule that generated or revealed that outcome.&lt;/p&gt;

&lt;h3 id=&quot;try-it-the-likelihood-flip-by-flip&quot;&gt;Try it: the likelihood flip by flip&lt;/h3&gt;

&lt;p&gt;Add one flip at a time and watch the relative likelihood, the MLE and the likelihood interval.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;likelihood-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;binom&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;8-multiple-observations&quot;&gt;8. Multiple observations&lt;/h2&gt;

&lt;p&gt;If observations are conditionally independent given the parameter, then the total likelihood is the product of the contribution from each observation:&lt;/p&gt;

\[\mathcal{L}(\theta \mid y_1,\dots,y_n) = \prod_{i=1}^n P(y_i \mid \theta).\]

&lt;p&gt;This means that each new observation contributes additional evidence, so as more data accumulate the likelihood often becomes sharper and more informative.&lt;/p&gt;

&lt;h2 id=&quot;9-why-do-we-use-log-likelihood&quot;&gt;9. Why do we use log-likelihood?&lt;/h2&gt;

&lt;p&gt;With many observations, likelihood becomes a product of many small numbers. So we often use&lt;/p&gt;

\[\ell(\theta \mid D) = \log \mathcal{L}(\theta \mid D)
= \sum_{i=1}^n \log P(y_i \mid \theta).\]

&lt;p&gt;This is easier to compute, easier to optimize, and numerically more stable.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_likelihood_curve_large_n.png&quot; alt=&quot;Likelihood values can become numerically tiny with larger datasets&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_log_likelihood_curve_large_n.png&quot; alt=&quot;Log-likelihood keeps the same comparison structure while staying easier to compute with&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;10-maximum-likelihood-estimation&quot;&gt;10. Maximum likelihood estimation&lt;/h2&gt;

&lt;p&gt;The value that maximizes likelihood is the maximum likelihood estimate:&lt;/p&gt;

\[\hat{\theta}_{MLE} = \arg\max_{\theta}\mathcal{L}(\theta \mid D).\]

&lt;p&gt;For Binomial data:&lt;/p&gt;

\[\hat{\theta}_{MLE} = \frac{k}{n}.\]

&lt;p&gt;MLE is useful, but it gives only a point estimate and does not include prior information, which is exactly why Bayesian analysis refuses to stop there.&lt;/p&gt;

&lt;h2 id=&quot;11-likelihood-inside-bayes-theorem&quot;&gt;11. Likelihood inside Bayes’ theorem&lt;/h2&gt;

&lt;p&gt;In Bayesian inference,&lt;/p&gt;

\[P(\theta \mid D) \propto P(D \mid \theta)P(\theta).\]

&lt;p&gt;Likelihood is the part that lets the data speak, prior is the part that brings in background knowledge, and posterior is the result of combining the two. If likelihood remains conceptually unclear, posterior will almost always remain unclear as well.&lt;/p&gt;

&lt;h2 id=&quot;12-common-misunderstandings&quot;&gt;12. Common misunderstandings&lt;/h2&gt;

&lt;h3 id=&quot;121-high-likelihood-means-high-probability-of-the-parameter&quot;&gt;12.1. “High likelihood means high probability of the parameter”&lt;/h3&gt;

&lt;p&gt;Not yet. You need the posterior for a probability statement about the parameter.&lt;/p&gt;

&lt;h3 id=&quot;122-likelihood-is-only-a-bayesian-idea&quot;&gt;12.2. “Likelihood is only a Bayesian idea”&lt;/h3&gt;

&lt;p&gt;No. Frequentist methods also rely heavily on likelihood, especially MLE.&lt;/p&gt;

&lt;h3 id=&quot;123-the-highest-likelihood-value-is-the-whole-answer&quot;&gt;12.3. “The highest likelihood value is the whole answer”&lt;/h3&gt;

&lt;p&gt;No. It is only a point summary. Bayesian inference keeps the full updated distribution.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Likelihood is how the data score competing parameter values.&lt;/strong&gt; It is not the posterior, and it is not a probability distribution over the parameter. It is the data’s contribution to Bayesian updating.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key takeaways.&lt;/strong&gt; Likelihood fixes the data and varies the parameter to see which values explain the observed data better; the most useful reading of likelihood is relative comparison rather than an absolute number; and likelihood is a core ingredient of Bayes, but it is not yet the posterior.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-proving-a-likelihood-function-does-not-integrate-to-1&quot;&gt;Worked Numerical Example: Proving a Likelihood Function Does NOT Integrate to 1&lt;/h3&gt;

&lt;p&gt;Suppose you flip a coin &lt;strong&gt;once&lt;/strong&gt; (\(n=1\)) and observe &lt;strong&gt;1 Head&lt;/strong&gt; (\(y = 1\)).&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;As a probability over data&lt;/strong&gt; (fixing \(p = 0.7\)): \(P(y=1\mid 0.7) + P(y=0\mid 0.7) = 0.7 + 0.3 = \mathbf{1.0}\) (valid PMF!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;As a likelihood over \(p \in [0, 1]\)&lt;/strong&gt; (fixing observed \(y = 1\)): \(L(p) = P(y=1\mid p) = p\). Integrate over all \(p \in [0, 1]\):
\(\int_0^1 L(p)\,dp = \int_0^1 p\,dp = \left[\frac{p^2}{2}\right]_0^1 = \mathbf{0.5} \neq 1!\)
Now multiply by a flat prior \(p(\theta) = 1\) and divide by the evidence \(P(y=1) = 0.5\):
\(p(\theta \mid y=1) = \frac{1 \cdot \theta}{0.5} = \mathbf{2\theta} \quad \text{(which integrates to } 1\text{ — }\mathrm{Beta}(2,1)\text{!)}.\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-rules-for-thinking-clearly-about-likelihoods&quot;&gt;Explanation: Four Rules for Thinking Clearly About Likelihoods&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always say “likelihood of parameter \(\theta\) given data \(y\)”, never “probability of \(\theta\)”:&lt;/strong&gt; Only the &lt;em&gt;posterior&lt;/em&gt; is a probability over \(\theta\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare likelihoods by &lt;em&gt;ratios&lt;/em&gt;, not raw magnitudes:&lt;/strong&gt; For \(n=500\) data points, \(L(\hat{\theta})\) might be \(10^{-180}\), which sounds tiny—what matters is \(\frac{L(\theta_1)}{L(\theta_2)} = e^{\ell(\theta_1)-\ell(\theta_2)}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Only multiply likelihoods when data points are conditionally independent:&lt;/strong&gt; If observations are correlated (e.g., repeated measurements on one patient), multiplying i.i.d. likelihoods double-counts information and makes posteriors dangerously overconfident!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Look at the width of the log-likelihood curve:&lt;/strong&gt; A narrow, sharp log-likelihood peak means your data strongly pins down \(\theta\); a flat ridge means the data barely distinguishes those parameter values (non-identifiability).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If you observe \(n = 2\) Heads in 2 flips (\(L(p) = p^2\) on \([0,1]\)), what is the integral \(\int_0^1 L(p)\,dp\), and what normalized posterior density do you get under a flat prior?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pYxNSUDSFH4&quot;&gt;In Statistics, Probability is not Likelihood.&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Watch the separation of likelihood from the probability of a parameter, the confusion this lesson is written to prevent.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=XepXtl9YKwc&quot;&gt;Maximum Likelihood, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch a likelihood built from a sampling model and used to compare parameter values.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R1vcdhPBlXA&quot;&gt;Statistical Rethinking 2023 - 02 - The Garden of Forking Data&lt;/a&gt; — Richard McElreath, English. Watch the globe-tossing likelihood change with the assumed water proportion, a worked generative story for this lesson.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;A cafe sells 18 drinks in one hour. If you use a Poisson model, what question does the likelihood of \(\lambda\) answer?&lt;/li&gt;
  &lt;li&gt;Why is \(\theta = 0.8\) usually more strongly supported than \(\theta = 0.3\) when the data are 8 successes out of 10?&lt;/li&gt;
  &lt;li&gt;Explain in words the difference between \(P(D \mid \theta)\) and \(P(\theta \mid D)\).&lt;/li&gt;
  &lt;li&gt;In your own field, where would a likelihood ratio be useful?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 2.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 5.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter02/02_03_prior/&quot;&gt;2.3 Prior - Encoding What We Know Before Data&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 2.1: Probability Distributions - The Language of Uncertainty</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_01_probability_distributions/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter02/02_01_probability_distributions</id>
   <content type="html">&lt;p&gt;Picking a probability distribution in Bayesian modeling is like choosing the right architectural blueprint for a building: use a Normal distribution for strictly positive server latencies and your model will predict &lt;em&gt;negative&lt;/em&gt; response times; use a Poisson for overdispersed retail sales and your inventory buffer will constantly run dry! Every distribution family encodes a specific set of &lt;strong&gt;domain constraints and maximum-entropy assumptions&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This Chapter 2 opener organizes the essential discrete and continuous distributions into a clean &lt;strong&gt;Bayesian Modeling Periodic Table&lt;/strong&gt;—matching each data type (binary, counts, bounded proportions, positive continuous, unbounded) to its natural likelihood and prior families.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-matching-data-domains-to-distribution-families&quot;&gt;Key ideas: Matching Data Domains to Distribution Families&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Domain &amp;amp; Support First:&lt;/strong&gt; Binary \(\{0,1\} \to\) Bernoulli/Binomial; unbounded counts \(\{0,1,2,\dots\} \to\) Poisson / Negative Binomial; proportions \((0,1) \to\) Beta; positive continuous \((0,\infty) \to\) Exponential / Gamma / Log-Normal / Half-Normal; unbounded \(\mathbb{R} \to\) Normal / Student-\(t\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Maximum Entropy Principle (Jaynes):&lt;/strong&gt; Among all distributions with fixed mean and variance on \(\mathbb{R}\), the &lt;strong&gt;Gaussian&lt;/strong&gt; has maximum entropy (makes the fewest extra assumptions). Knowing only a positive mean gives the &lt;strong&gt;Exponential&lt;/strong&gt;; knowing only bounds \([a,b]\) gives the &lt;strong&gt;Uniform&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Location–Scale vs. Shape–Rate Parameterizations:&lt;/strong&gt; Always check how a library parameterizes a family (e.g., Normal by SD \(\sigma\) vs. variance \(\sigma^2\) vs. precision \(\tau=1/\sigma^2\); Gamma by rate \(\beta\) vs. scale \(\theta=1/\beta\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mixture &amp;amp; Hierarchical Extensions:&lt;/strong&gt; When real data doesn’t match one textbook family (e.g., bimodal incomes or zero-inflated counts), Bayesian models compose simple distributions into mixtures or hierarchical layers.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you should be able to read a probability distribution as a story about uncertainty, distinguish discrete from continuous settings, and explain why Bayesian analysis keeps the &lt;strong&gt;full distribution&lt;/strong&gt; instead of only a single point estimate.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; Two classes both have a pass rate of \(75\%\), but one class has 8 students and the other has 800 students. The rate is the same, but the certainty is not.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If you report only the single number \(75\%\), what important information are you losing?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;opening-question-why-is-one-number-often-not-enough&quot;&gt;Opening question: why is one number often not enough?&lt;/h2&gt;

&lt;p&gt;Suppose you are tracking the conversion rate of a new button on a website.&lt;/p&gt;

&lt;p&gt;In Week 1, you see 25 purchases out of 100 visits, while in Week 2 you again see 25 purchases, but this time out of 1000 visits.&lt;/p&gt;

&lt;p&gt;Both weeks give the same point estimate: \(25\%\). But they do not give the same level of certainty. In Week 2, we are much more confident that the true rate is close to \(25\%\). In Week 1, values like \(18\%\) or \(32\%\) are still quite plausible.&lt;/p&gt;

&lt;p&gt;That is the reason Bayesian statistics does not stop at a single number. It keeps a richer object: a &lt;strong&gt;probability distribution&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/distribution_belief_map.png&quot; alt=&quot;A distribution as a belief map&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-what-is-a-probability-distribution&quot;&gt;1. What is a probability distribution?&lt;/h2&gt;

&lt;p&gt;A probability distribution is a &lt;strong&gt;map of belief&lt;/strong&gt; over possible values.&lt;/p&gt;

&lt;p&gt;If a value gets high probability or high density, it means that value is more compatible with what we know, what the data suggest, or both.&lt;/p&gt;

&lt;p&gt;In Bayesian work, distributions appear everywhere: for unknown parameters, for observed data, and for future predictions. In practice, when you look at a distribution, it helps to ask where its center is, how wide it is, whether it is skewed, and how much probability still remains in the tails, because those questions together turn a graph into an interpretable summary of uncertainty.&lt;/p&gt;

&lt;h2 id=&quot;2-discrete-and-continuous-uncertainty&quot;&gt;2. Discrete and continuous uncertainty&lt;/h2&gt;

&lt;h3 id=&quot;21-discrete-distributions&quot;&gt;2.1. Discrete distributions&lt;/h3&gt;

&lt;p&gt;Use a discrete distribution when the variable takes countable values.&lt;/p&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;p&gt;number of absent students, number of spam emails in one hour, or number of heads in 10 coin flips.&lt;/p&gt;

&lt;p&gt;Then we work with probabilities of exact outcomes:&lt;/p&gt;

\[P(X = x).\]

&lt;h3 id=&quot;22-continuous-distributions&quot;&gt;2.2. Continuous distributions&lt;/h3&gt;

&lt;p&gt;Use a continuous distribution when the variable can take any value in an interval.&lt;/p&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;p&gt;height, delivery time, temperature, or the true conversion rate of an ad.&lt;/p&gt;

&lt;p&gt;Then we work with density \(p(x)\) and probabilities over intervals:&lt;/p&gt;

\[P(a &amp;lt; X &amp;lt; b) = \int_a^b p(x)\,dx.\]

&lt;h2 id=&quot;3-same-center-different-certainty&quot;&gt;3. Same center, different certainty&lt;/h2&gt;

&lt;p&gt;Suppose two analysts both say the true conversion rate is around \(0.25\). One uses Beta\((3,9)\) and the other uses Beta\((30,90)\).&lt;/p&gt;

&lt;p&gt;Both have mean:&lt;/p&gt;

\[\frac{\alpha}{\alpha+\beta} = \frac{1}{4}.\]

&lt;p&gt;But they say different things.&lt;/p&gt;

&lt;p&gt;Beta\((3,9)\) is fairly wide, which corresponds to saying, “I think \(0.25\) is a reasonable center, but I am still quite open to nearby possibilities,” whereas Beta\((30,90)\) is much tighter and therefore corresponds to saying, “I think \(0.25\) is reasonable, and I am fairly confident the true value should stay close to it.”&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_narrow_distribution.png&quot; alt=&quot;A narrow distribution indicating high certainty&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/chapter02_wide_distribution.png&quot; alt=&quot;A wide distribution indicating greater uncertainty&quot; /&gt;&lt;/p&gt;

&lt;p&gt;That difference disappears if you keep only the mean. The full distribution keeps it.&lt;/p&gt;

&lt;h2 id=&quot;4-the-three-roles-of-distributions-in-bayesian-inference&quot;&gt;4. The three roles of distributions in Bayesian inference&lt;/h2&gt;

&lt;h3 id=&quot;41-prior&quot;&gt;4.1. Prior&lt;/h3&gt;

&lt;p&gt;The prior \(P(\theta)\) describes what we believe about the parameter before seeing the current data.&lt;/p&gt;

&lt;h3 id=&quot;42-likelihood&quot;&gt;4.2. Likelihood&lt;/h3&gt;

&lt;p&gt;The likelihood \(P(D \mid \theta)\) describes how compatible the observed data are with each possible value of \(\theta\).&lt;/p&gt;

&lt;h3 id=&quot;43-posterior&quot;&gt;4.3. Posterior&lt;/h3&gt;

&lt;p&gt;The posterior \(P(\theta \mid D)\) is the updated belief after combining prior knowledge and data:&lt;/p&gt;

\[P(\theta \mid D) = \frac{P(D \mid \theta)P(\theta)}{P(D)}.\]

&lt;p&gt;Read together, these three objects define the basic rhythm of Bayesian inference: the prior states where we begin, the likelihood tells us what the data have to say, and the posterior records what remains after those two sources of information are combined coherently.&lt;/p&gt;

&lt;h2 id=&quot;5-how-to-read-the-shape-of-a-distribution&quot;&gt;5. How to read the shape of a distribution&lt;/h2&gt;

&lt;h3 id=&quot;51-center&quot;&gt;5.1. Center&lt;/h3&gt;

&lt;p&gt;The center tells you the most reasonable region for the quantity of interest.&lt;/p&gt;

&lt;h3 id=&quot;52-width&quot;&gt;5.2. Width&lt;/h3&gt;

&lt;p&gt;The width tells you how uncertain you still are.&lt;/p&gt;

&lt;p&gt;A narrow distribution means greater certainty, whereas a wide distribution means greater remaining uncertainty.&lt;/p&gt;

&lt;h3 id=&quot;53-skewness&quot;&gt;5.3. Skewness&lt;/h3&gt;

&lt;p&gt;The distribution may lean left or right, especially for probabilities near 0 or 1 and for count data.&lt;/p&gt;

&lt;h3 id=&quot;54-tails&quot;&gt;5.4. Tails&lt;/h3&gt;

&lt;p&gt;The tails tell you how much extreme risk is still on the table.&lt;/p&gt;

&lt;h2 id=&quot;6-distribution-families-you-will-see-often&quot;&gt;6. Distribution families you will see often&lt;/h2&gt;

&lt;h3 id=&quot;61-beta&quot;&gt;6.1. Beta&lt;/h3&gt;

&lt;p&gt;Natural for quantities between 0 and 1:&lt;/p&gt;

&lt;p&gt;success probabilities, pass rates, defect rates, and click-through rates.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter02/beta_distribution_family.png&quot; alt=&quot;The Beta family&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;62-binomial&quot;&gt;6.2. Binomial&lt;/h3&gt;

&lt;p&gt;Natural for counting the number of successes in \(n\) trials.&lt;/p&gt;

&lt;h3 id=&quot;63-poisson&quot;&gt;6.3. Poisson&lt;/h3&gt;

&lt;p&gt;Natural for counting events over time or space:&lt;/p&gt;

&lt;p&gt;calls per hour, orders per minute, and system failures per day.&lt;/p&gt;

&lt;h3 id=&quot;64-normal&quot;&gt;6.4. Normal&lt;/h3&gt;

&lt;p&gt;Natural for continuous quantities varying around a center:&lt;/p&gt;

&lt;p&gt;height, measurement error, test scores, and processing time.&lt;/p&gt;

&lt;h2 id=&quot;7-why-bayesian-analysis-keeps-the-full-distribution&quot;&gt;7. Why Bayesian analysis keeps the full distribution&lt;/h2&gt;

&lt;p&gt;Once you keep the full distribution, you can answer practical questions such as:&lt;/p&gt;

&lt;p&gt;what the probability is that the conversion rate is above \(5\%\), what interval is reasonable for the pass rate, and what might happen for the next 100 customers.&lt;/p&gt;

&lt;p&gt;A single point estimate cannot answer those questions well.&lt;/p&gt;

&lt;h2 id=&quot;8-everyday-examples&quot;&gt;8. Everyday examples&lt;/h2&gt;

&lt;h3 id=&quot;81-business&quot;&gt;8.1. Business&lt;/h3&gt;

&lt;p&gt;In an A/B test, we care not only about the average lift, but also about uncertainty and downside risk.&lt;/p&gt;

&lt;h3 id=&quot;82-education&quot;&gt;8.2. Education&lt;/h3&gt;

&lt;p&gt;A pass rate of \(75\%\) means something very different in a class of 8 students versus a class of 800 students.&lt;/p&gt;

&lt;h3 id=&quot;83-medicine&quot;&gt;8.3. Medicine&lt;/h3&gt;

&lt;p&gt;With only a handful of patients, a single estimate is often too fragile. A distribution gives a more honest summary.&lt;/p&gt;

&lt;h2 id=&quot;9-common-misunderstandings&quot;&gt;9. Common misunderstandings&lt;/h2&gt;

&lt;h3 id=&quot;91-a-distribution-is-just-a-pretty-graph&quot;&gt;9.1. “A distribution is just a pretty graph”&lt;/h3&gt;

&lt;p&gt;No. It stores the whole story about uncertainty.&lt;/p&gt;

&lt;h3 id=&quot;92-the-mean-is-enough&quot;&gt;9.2. “The mean is enough”&lt;/h3&gt;

&lt;p&gt;No. Two distributions can share the same mean but lead to very different decisions.&lt;/p&gt;

&lt;h3 id=&quot;93-if-data-are-large-distributions-are-unnecessary&quot;&gt;9.3. “If data are large, distributions are unnecessary”&lt;/h3&gt;

&lt;p&gt;No. Even with lots of data, distributions still matter for risk communication and prediction.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Probability distributions are the core language of Bayesian statistics.&lt;/strong&gt; They tell us not only which values are plausible, but also how certain we are, how much risk remains, and how future outcomes might behave.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key takeaways.&lt;/strong&gt; A distribution always carries more information than a point estimate because it keeps uncertainty visible; two distributions can share the same center and still imply very different levels of certainty; and in Bayesian inference, prior, likelihood, and posterior are all distributions playing different roles.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-selecting-the-right-family-for-4-real-datasets&quot;&gt;Worked Numerical Example: Selecting the Right Family for 4 Real Datasets&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Observed Variable \(Y\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Legal Support&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Wrong Naive Choice&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Proper Bayesian Likelihood&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Natural Prior for Key Param&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Conversions in \(n\) clicks&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\{0,\dots,n\}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Normal&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Binomial(\(n, p\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mathrm{Beta}(\alpha,\beta)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Daily ER arrivals (Var &amp;gt; Mean)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\{0,1,2,\dots\}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Poisson&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Negative Binomial(\(\mu, \phi\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mathrm{Gamma} / \mathrm{HalfNormal}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;API latency (ms, right-skew)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((0,\infty)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Normal&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Log-Normal(\(\mu, \sigma\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mu\sim\mathcal{N},\; \sigma\sim\mathrm{HalfNormal}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Test scores with wild outliers&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mathbb{R}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Normal&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Student-\(t(\nu, \mu, \sigma)\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\nu\sim\mathrm{Gamma}(2,0.1)\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Check the Log-Normal latency numbers: if \(\log(\text{latency}) \sim \mathcal{N}(\ln 100,\; 0.5^2)\), the &lt;strong&gt;median&lt;/strong&gt; latency is \(e^{\ln 100} = 100\text{ ms}\), while the &lt;strong&gt;mean&lt;/strong&gt; is \(100 \cdot e^{0.5^2/2} = 100 \cdot e^{0.125} \approx \mathbf{113.3\text{ ms}}\)—and latency can &lt;em&gt;never&lt;/em&gt; go negative!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-choosing-distributions-like-a-bayesian-modeler&quot;&gt;Explanation: Four Rules for Choosing Distributions Like a Bayesian Modeler&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Let the physical/data-generating constraints pick the support:&lt;/strong&gt; Never use an unbounded Gaussian when zeros or negatives are physically impossible—unless the mean sits many SDs above zero.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check mean–variance relationships:&lt;/strong&gt; In Binomial and Poisson models, variance is locked to the mean; when real data varies more widely, introduce a dispersion parameter (Beta-Binomial, Negative Binomial).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use Half-Normal or Exponential priors for scale parameters (\(\sigma &amp;gt; 0\)):&lt;/strong&gt; Avoid old textbook flat &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;InverseGamma(0.001, 0.001)&lt;/code&gt; priors, which put bizarre spikes near zero.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify your choice with Prior Predictive Simulation:&lt;/strong&gt; Plot 20 simulated datasets from your chosen distribution—if they look alien compared to domain reality, swap the family before fitting!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Why is a Normal likelihood a poor choice for modeling daily e-commerce order counts when the average is only \(\mu = 1.5\) orders/day?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=oI3hZJqXJuc&quot;&gt;The Main Ideas behind Probability Distributions&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;xem trước&lt;/strong&gt;. Watch the main ideas of a probability distribution so a distribution reads as a story about uncertainty, as this lesson asks.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pvkhK03aFDM&quot;&gt;Random variables and probability distributions.&lt;/a&gt; — Ben Lambert, English. Watch discrete and continuous random variables separated cleanly, supporting the lesson’s choice of distribution family.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Why “probability of 0” does not mean “impossible”&lt;/td&gt;
          &lt;td&gt;Probabilities of probabilities, part 2](https://www.youtube.com/watch?v=ZA4JkHKZM50) — 3Blue1Brown, English. Watch why a single point is not a substitute for the whole distribution, the reason the lesson keeps the full posterior later.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why does the same pass rate of \(75\%\) mean different things in a class of 8 students and a class of 800 students?&lt;/li&gt;
  &lt;li&gt;Give three discrete examples and three continuous examples from your own context.&lt;/li&gt;
  &lt;li&gt;Beta\((4,16)\) and Beta\((40,160)\) have the same mean. How do they differ in interpretation?&lt;/li&gt;
  &lt;li&gt;What business or scientific quantity would you rather describe with a full distribution than with a single number?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 1-2.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 4-5.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 2.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter02/02_02_likelihood/&quot;&gt;2.2 Likelihood - The Data’s Story Under a Model&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 1.4: Bayesian vs Frequentist - Comparison and Choice</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_04_bayesian_vs_frequentist/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_04_bayesian_vs_frequentist</id>
   <content type="html">&lt;p&gt;Online debates often portray &lt;strong&gt;Bayesian&lt;/strong&gt; and &lt;strong&gt;Frequentist&lt;/strong&gt; statistics as two warring religions. In real data science, they are two complementary toolkits built on two different mathematical definitions of uncertainty—and knowing &lt;em&gt;exactly&lt;/em&gt; when they agree, when they diverge, and why a 95% &lt;strong&gt;Confidence Interval&lt;/strong&gt; does &lt;em&gt;not&lt;/em&gt; mean the same thing as a 95% &lt;strong&gt;Credible Interval&lt;/strong&gt; is a hallmark of statistical maturity.&lt;/p&gt;

&lt;p&gt;This lesson compares both paradigms side by side on the exact same dataset so you can choose the right tool pragmatically instead of dogmatically.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-four-core-contrasts-between-bayes-and-frequentism&quot;&gt;Key ideas: The Four Core Contrasts Between Bayes and Frequentism&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;What Is Random?&lt;/strong&gt; Frequentists treat parameters \(\theta\) as fixed constants and data \(D\) as random across hypothetical repeats; Bayesians condition on the &lt;em&gt;observed&lt;/em&gt; data \(D\) and treat unknown parameters \(\theta\) as random variables.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;95% Confidence Interval vs. 95% Credible Interval:&lt;/strong&gt; A frequentist 95% CI guarantees that &lt;em&gt;95% of intervals generated by this procedure&lt;/em&gt; cover \(\theta\); a Bayesian 95% Credible Interval directly says &lt;em&gt;there is a 95% posterior probability that \(\theta\) lies inside this specific interval&lt;/em&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Priors &amp;amp; Small-Sample Regularization:&lt;/strong&gt; Frequentists rely solely on the likelihood (or add ad-hoc L2/L1 penalties); Bayesians encode domain knowledge and regularization transparently inside the prior \(p(\theta)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Large-Sample Convergence (Bernstein–von Mises):&lt;/strong&gt; With large \(n\) and regular models, frequentist CIs and Bayesian Credible Intervals converge numerically—the biggest practical differences appear at &lt;strong&gt;small \(n\)&lt;/strong&gt;, &lt;strong&gt;hierarchical/grouped data&lt;/strong&gt;, and &lt;strong&gt;decision-making under asymmetric costs&lt;/strong&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to understand that the difference between the two schools lies not only in computational tools, but in the very question each side chooses to answer. You also need to know why the Bayesian approach often gives a more direct interpretation, yet the frequentist approach still has a role in many practical contexts.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; With the same data of 7 heads in 10 tosses, a frequentist asks “if the coin is fair, how unusual is this data?”, while a Bayesian asks “after seeing this data, where does the true probability likely lie?”.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Do these two schools differ mainly in computational formulas, or in the very question they choose to answer?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;1-why-compare-these-two-schools&quot;&gt;1. Why compare these two schools?&lt;/h2&gt;

&lt;p&gt;Many people learning statistics feel confused because frequentists and Bayesians sometimes use the same data, the same model, even some of the same mathematical tools, but interpret the results very differently. The difference lies deeper than the technical level. It lies in how probability is understood, in what the parameter is taken to be, and in the kind of final answer each side aims for.&lt;/p&gt;

&lt;h2 id=&quot;2-the-same-problem-two-different-ways-of-asking&quot;&gt;2. The same problem, two different ways of asking&lt;/h2&gt;

&lt;p&gt;Consider the coin example again: we toss 10 times, see 7 heads, and want to know whether the coin is biased.&lt;/p&gt;

&lt;h3 id=&quot;a-frequentist-usually-asks&quot;&gt;A Frequentist usually asks:&lt;/h3&gt;

&lt;p&gt;If the coin is truly balanced, is data like this unusual?&lt;/p&gt;

&lt;h3 id=&quot;a-bayesian-usually-asks&quot;&gt;A Bayesian usually asks:&lt;/h3&gt;

&lt;p&gt;After seeing this data, what is the plausible range of values for the probability of heads?&lt;/p&gt;

&lt;p&gt;The difference in the question alone already leads to a big difference in interpretation.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_frequentist_vs_bayesian_frequentist.png&quot; alt=&quot;The Frequentist view in a general comparison&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_frequentist_vs_bayesian_bayesian.png&quot; alt=&quot;The Bayesian view in a general comparison&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-differing-in-the-definition-of-probability&quot;&gt;3. Differing in the definition of probability&lt;/h2&gt;

&lt;h3 id=&quot;frequentist&quot;&gt;Frequentist&lt;/h3&gt;

&lt;p&gt;For a frequentist, probability is the long-run frequency of an outcome over many repetitions.&lt;/p&gt;

&lt;h3 id=&quot;bayesian&quot;&gt;Bayesian&lt;/h3&gt;

&lt;p&gt;For a Bayesian, probability is the degree of reasonable belief in a proposition, based on the available information.&lt;/p&gt;

&lt;p&gt;This leads to a very important difference.&lt;/p&gt;

&lt;h3 id=&quot;for-the-frequentist&quot;&gt;For the Frequentist&lt;/h3&gt;

&lt;p&gt;The parameter is fixed but unknown, while the data is random.&lt;/p&gt;

&lt;h3 id=&quot;for-the-bayesian&quot;&gt;For the Bayesian&lt;/h3&gt;

&lt;p&gt;The observed data is already fixed, while the unknown parameter is described by a probability distribution.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_philosophy_frequentist.png&quot; alt=&quot;Frequentist: fixed parameter, random data&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_philosophy_bayesian.png&quot; alt=&quot;Bayesian: data already seen, parameter still uncertain&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;4-how-do-the-confidence-interval-and-the-credible-interval-differ&quot;&gt;4. How do the confidence interval and the credible interval differ?&lt;/h2&gt;

&lt;p&gt;This is the point that confuses learners the most.&lt;/p&gt;

&lt;p&gt;Suppose you have an interval \([0.46, 0.86]\).&lt;/p&gt;

&lt;h3 id=&quot;frequentist-confidence-interval&quot;&gt;Frequentist confidence interval&lt;/h3&gt;

&lt;p&gt;The correct interpretation is that if we repeat this procedure very many times, 95% of the intervals produced will contain the true value. This does &lt;strong&gt;not&lt;/strong&gt; mean “there is a 95% probability that the parameter lies in that interval”.&lt;/p&gt;

&lt;h3 id=&quot;bayesian-credible-interval&quot;&gt;Bayesian credible interval&lt;/h3&gt;

&lt;p&gt;The Bayesian interpretation speaks more directly: given the current data and the current prior, there is a 95% probability that the parameter lies in that interval.&lt;/p&gt;

&lt;p&gt;This is close to the kind of question that users really want to ask.&lt;/p&gt;

&lt;h3 id=&quot;experiment-confidence-intervals-and-credible-intervals-over-repeated-experiments&quot;&gt;Experiment: confidence intervals and credible intervals over repeated experiments&lt;/h3&gt;

&lt;p&gt;Each row is one experiment; see the 95% confidence interval cover the fixed μ exactly 95% of the time, while the credible interval depends on the prior.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;interval-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;5-how-do-the-p-value-and-the-posterior-probability-differ&quot;&gt;5. How do the p-value and the posterior probability differ?&lt;/h2&gt;

&lt;h3 id=&quot;frequentist-1&quot;&gt;Frequentist&lt;/h3&gt;

&lt;p&gt;The p-value asks, if the null hypothesis is true, how unusual is this data.&lt;/p&gt;

&lt;h3 id=&quot;bayesian-1&quot;&gt;Bayesian&lt;/h3&gt;

&lt;p&gt;The posterior probability speaks about where the hypothesis or parameter is likely to be after seeing the data.&lt;/p&gt;

&lt;p&gt;This is the difference between talking about the &lt;strong&gt;unusualness of the data&lt;/strong&gt; and talking about the &lt;strong&gt;credibility of the hypothesis&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_vs_posterior_frequentist.png&quot; alt=&quot;The p-value from the Frequentist view&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_vs_posterior_bayesian.png&quot; alt=&quot;The posterior probability from the Bayesian view&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-a-medical-example-to-see-the-difference-more-clearly&quot;&gt;6. A medical example to see the difference more clearly&lt;/h2&gt;

&lt;p&gt;Suppose a test returns a positive result.&lt;/p&gt;

&lt;h3 id=&quot;frequentist-style&quot;&gt;Frequentist style&lt;/h3&gt;

&lt;p&gt;One might say: if the patient does not have the disease, what is the probability of a positive result?&lt;/p&gt;

&lt;h3 id=&quot;bayesian-style&quot;&gt;Bayesian style&lt;/h3&gt;

&lt;p&gt;One asks more directly: after a positive result, what is the probability that the patient really has the disease?&lt;/p&gt;

&lt;p&gt;In medicine, clearly the second question is closer to what doctors and patients need.&lt;/p&gt;

&lt;h3 id=&quot;a-numerical-example&quot;&gt;A numerical example&lt;/h3&gt;

&lt;p&gt;Suppose the disease rate in the population is only \(1\%\), the test has sensitivity \(99\%\), and the false positive rate is \(5\%\). When a patient gets a positive result, a Bayesian will compute:&lt;/p&gt;

\[P(\text{disease}\mid +)
=\frac{0.99\times 0.01}{0.99\times 0.01 + 0.05\times 0.99}
\approx 0.167.\]

&lt;p&gt;That is, after a positive result, the probability of really having the disease is only about \(16.7\%\), not close to \(99\%\). This example shows the difference very clearly: a frequentist usually reports the properties of the test under a hypothesis, while a Bayesian answers directly the question that doctors and patients really care about.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_clinical_trial_frequentist.png&quot; alt=&quot;Clinical trial analysis, Frequentist style&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_clinical_trial_bayesian.png&quot; alt=&quot;Clinical trial analysis, Bayesian style&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;7-where-is-the-frequentist-strong&quot;&gt;7. Where is the Frequentist strong?&lt;/h2&gt;

&lt;p&gt;It would not be fair to view the frequentist approach as “completely wrong”.&lt;/p&gt;

&lt;p&gt;The frequentist approach is strong in contexts such as standardized trial design with fixed decision rules, problems with very large sample sizes, fields or regulatory agencies familiar with the language of traditional testing, and procedures that need to guarantee the long-run properties of the procedure. Typical examples are many late-phase clinical trials, manufacturing quality control, or situations where the decision process must be standardized very tightly.&lt;/p&gt;

&lt;h2 id=&quot;8-where-is-the-bayesian-strong&quot;&gt;8. Where is the Bayesian strong?&lt;/h2&gt;

&lt;p&gt;The Bayesian approach is especially strong when we need direct interpretation about a parameter or hypothesis, when there is trustworthy prior knowledge, when data is scarce, when sequential updating is needed, when the model has hierarchical or complex structure, or when forecasts with uncertainty are needed. Very typical examples are startups running A/B tests with modest traffic, doctors making decisions based on multiple sources of information, recommendation systems, time series forecasting, or scientific analyses with priors from earlier research.&lt;/p&gt;

&lt;h2 id=&quot;9-typical-weaknesses-of-each-side&quot;&gt;9. Typical weaknesses of each side&lt;/h2&gt;

&lt;h3 id=&quot;frequentists-usually-struggle-with&quot;&gt;Frequentists usually struggle with:&lt;/h3&gt;

&lt;p&gt;Frequentists usually struggle with interpreting p-values and confidence intervals, with incorporating prior knowledge, with speaking directly about the probability of a parameter, and with updating naturally when data arrives in batches.&lt;/p&gt;

&lt;h3 id=&quot;bayesians-usually-struggle-with&quot;&gt;Bayesians usually struggle with:&lt;/h3&gt;

&lt;p&gt;Bayesians usually struggle with having to choose a prior, computation that is sometimes heavier, and needing the reader to accept the interpretation of probability as a degree of belief.&lt;/p&gt;

&lt;p&gt;But with modern tools such as PyMC and Stan, the computational barrier has dropped considerably.&lt;/p&gt;

&lt;h2 id=&quot;10-it-is-not-always-a-war&quot;&gt;10. It is not always a “war”&lt;/h2&gt;

&lt;p&gt;In modern practice, many analysts use frequentist thinking for some checks or baselines, but use Bayesian methods for the main model and interpretation of results. What matters is not choosing a side dogmatically, but whether you are using a tool suited to the question, and whether the interpretation of the results is honest with respect to the method actually chosen.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/decision_tree_freq_vs_bayes.png&quot; alt=&quot;Decision tree: when to think Frequentist, when to think Bayesian&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;11-why-does-this-course-focus-on-bayes&quot;&gt;11. Why does this course focus on Bayes?&lt;/h2&gt;

&lt;p&gt;Because in most of the modern problems that learners of this course care about, Bayes answers more directly questions such as where the parameter is likely to lie, how much uncertainty remains, what the probability is that this hypothesis is greater than that one, and how the future forecast should be understood.&lt;/p&gt;

&lt;p&gt;In short, Bayes usually says exactly what end users, researchers, doctors, engineers or product analysts want to hear.&lt;/p&gt;

&lt;h2 id=&quot;12-an-easy-to-remember-conclusion&quot;&gt;12. An easy-to-remember conclusion&lt;/h2&gt;

&lt;p&gt;If you had to remember it in the shortest way, the frequentist usually evaluates data under a hypothesis, while the Bayesian usually evaluates the hypothesis after seeing data.&lt;/p&gt;

&lt;p&gt;That is why the Bayesian approach often feels “more natural” for practical questions.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt;&lt;/p&gt;
  &lt;ol&gt;
    &lt;li&gt;Frequentist and Bayesian differ at the philosophical foundation: who is random, who is fixed, and what probability is talking about.&lt;/li&gt;
    &lt;li&gt;The frequentist usually answers questions about hypothetical data under a hypothesis, while the Bayesian answers directly about the parameter or hypothesis after seeing the data.&lt;/li&gt;
    &lt;li&gt;In many practical problems, the Bayesian answer is often closer to the question the user really wants to ask.&lt;/li&gt;
  &lt;/ol&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-same-data-0-defects-in-5-units-two-very-different-answers&quot;&gt;Worked Numerical Example: Same Data (0 Defects in 5 Units), Two Very Different Answers&lt;/h3&gt;

&lt;p&gt;Suppose a new factory line produces \(n = 5\) widgets and &lt;strong&gt;0 are defective&lt;/strong&gt; (\(k = 0\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Frequentist MLE:&lt;/strong&gt; \(\hat{p}_{\text{MLE}} = \frac{0}{5} = \mathbf{0.000}\), naive Wald SE \(= \sqrt{\frac{0(1)}{5}} = \mathbf{0.000}\) \(\implies\) degenerate 95% CI \([0, 0]\) (absurdly claiming 0% defect rate is 100% certain!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Update&lt;/strong&gt; with a gentle prior \(\mathrm{Beta}(1, 9)\) (prior mean 10% defects):
    &lt;ul&gt;
      &lt;li&gt;Posterior: \(\mathrm{Beta}(1 + 0,\; 9 + 5) = \mathbf{\mathrm{Beta}(1,\; 14)}\).&lt;/li&gt;
      &lt;li&gt;Posterior mean: \(\frac{1}{15} \approx \mathbf{6.67\%}\).&lt;/li&gt;
      &lt;li&gt;Exact 95% upper credible bound: solve \((1 - u)^{14} = 0.05 \implies u = 1 - 0.05^{1/14} \approx \mathbf{19.3\%}\)!&lt;/li&gt;
      &lt;li&gt;Honest Bayesian statement: &lt;em&gt;“Given 0 defects in 5 units, the expected defect rate is 6.7%, and there is a 95% probability it is below 19.3%.”&lt;/em&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-pragmatic-rules-for-choosing-between-paradigms&quot;&gt;Explanation: Four Pragmatic Rules for Choosing Between Paradigms&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Reach for Bayes when sample sizes are small, data is hierarchical, or you need direct probabilities for decisions:&lt;/strong&gt; E.g., &lt;em&gt;“what is the probability Variant B beats Variant A by at least +1%?”&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Reach for Frequentist tools when you need ultra-fast, standardized regulatory checks on huge flat datasets:&lt;/strong&gt; E.g., quick two-sample tests or massive industrial A/B platforms with \(n = 10^6\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check frequentist calibration of your Bayesian models too (Box’s Loop):&lt;/strong&gt; Good Bayesians still run simulation checks to verify their 95% credible intervals achieve ~95% empirical coverage!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Recognize the hidden unity:&lt;/strong&gt; Ridge regression = Gaussian prior MAP; Lasso = Laplace prior MAP; Empirical Bayes bridges both worlds seamlessly.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the 0-defects-in-5-units example above, if we instead used a flat \(\mathrm{Beta}(1, 1)\) prior, what would the posterior Beta distribution and posterior mean be?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qJcv7VHwqcA&quot;&gt;Bayesian vs. Frequentist Statistics … MADE EASY!!!&lt;/a&gt; — Stats with Brian, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the two schools pose two different questions on the same data, exactly the distinction the lesson pursues.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=GEFxFVESQXc&quot;&gt;Are you Bayesian or Frequentist?&lt;/a&gt; — Cassie Kozyrkov, English. Watch one way of choosing the language of probability according to the decision to be made, supporting the part of the lesson that does not turn the difference into factions.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YPceDssQFWo&quot;&gt;Bayesian Statistics: Credible vs Confidence Intervals&lt;/a&gt; — Academia Elevated, English. Watch that a confidence interval and a Bayesian credible interval do not read as the same sentence, used for the part comparing how results are interpreted.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Explain in words the difference between a confidence interval and a credible interval.&lt;/li&gt;
  &lt;li&gt;In the 7/10 coin example, how are the frequentist and the Bayesian asking two different questions?&lt;/li&gt;
  &lt;li&gt;For a medical diagnosis problem, why is the Bayesian interpretation usually more natural?&lt;/li&gt;
  &lt;li&gt;Give a situation where the frequentist approach is still a reasonable choice.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 1-4.&lt;/li&gt;
  &lt;li&gt;Dienes, Z. (2011). Bayesian versus orthodox statistics.&lt;/li&gt;
  &lt;li&gt;Wasserstein, R. L., &amp;amp; Lazar, N. A. (2016). ASA Statement on p-values.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;End of Chapter 1. Next lesson: &lt;a href=&quot;/contents/en/chapter02/&quot;&gt;Chapter 2 - Fundamentals of Bayesian Data Analysis&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 1.3: Bayes' Theorem - A Tool for Updating Beliefs</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_03_bayes_theorem_posterior/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_03_bayes_theorem_posterior</id>
   <content type="html">&lt;p&gt;Every learning algorithm in science—whether a doctor narrowing down a diagnosis, a radar tracking a satellite, or a data scientist evaluating an A/B test—follows one universal law of evidence: &lt;strong&gt;start with what was plausible before, multiply by how well each hypothesis explains the new data, and renormalize so total plausibility sums to 1.&lt;/strong&gt; That single equation is &lt;strong&gt;Bayes’ Theorem&lt;/strong&gt;:&lt;/p&gt;

\[P(\theta \mid D) = \frac{P(D \mid \theta)\,P(\theta)}{P(D)}.\]

&lt;p&gt;This lesson turns Bayes’ theorem into concrete muscle memory by walking step by step through &lt;strong&gt;prior \(\times\) likelihood \(\to\) unnormalized posterior \(\to\) normalized posterior&lt;/strong&gt;, both in discrete tables and continuous curves.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-four-named-parts-of-bayes-theorem&quot;&gt;Key ideas: The Four Named Parts of Bayes’ Theorem&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Prior \(P(\theta)\):&lt;/strong&gt; Your belief distribution over hypotheses &lt;em&gt;before&lt;/em&gt; observing the current dataset \(D\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Likelihood \(P(D \mid \theta)\):&lt;/strong&gt; How probable the observed data \(D\) would be &lt;em&gt;if&lt;/em&gt; hypothesis \(\theta\) were true (the bridge from model to data!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Marginal Likelihood / Evidence \(P(D) = \sum_\theta P(D\mid\theta)P(\theta)\):&lt;/strong&gt; The total probability of seeing data \(D\) averaged across all hypotheses—ensures the posterior sums/integrates to 1 (and powers Bayesian model comparison!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior \(P(\theta \mid D)\):&lt;/strong&gt; Your updated belief distribution &lt;em&gt;after&lt;/em&gt; seeing data \(D\)—ready to become tomorrow’s prior when the next batch of data arrives!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to understand Bayes’ theorem as a rule for updating beliefs and not just a memorized formula. You must be able to read the roles of the prior, likelihood and posterior in a real example, and know why Bayes becomes natural in diagnosis, forecasting and learning from data.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; A doctor knows that flu is common this season, but when a patient shows up with a set of symptoms very characteristic of COVID-19, the initial belief needs to be updated. Bayes’ theorem is exactly the tool for doing that in a principled way.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If the prior is what you believe before the data, and the likelihood is how well the data fits each hypothesis, how should the posterior be understood?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;1-bayes-starts-from-a-very-everyday-question&quot;&gt;1. Bayes starts from a very everyday question&lt;/h2&gt;

&lt;p&gt;Every day, we do something very Bayesian: we first believe something at a moderate level, then see new information, and then adjust the belief. This appears when we hear a weather forecast and update plans, when we look at test results to update a diagnosis, or when we look at first-week sales to adjust beliefs about market demand. Bayes’ theorem simply turns this seemingly intuitive process into a clear mathematical rule.&lt;/p&gt;

&lt;h2 id=&quot;2-an-easy-example-a-doctor-diagnosing-a-disease&quot;&gt;2. An easy example: a doctor diagnosing a disease&lt;/h2&gt;

&lt;p&gt;Suppose a doctor is weighing three possibilities: flu, COVID-19, and bacterial pneumonia. Before looking closely at the patient’s specific symptoms, the doctor already has an initial belief based on which disease is circulating this season, the regional epidemiology, and prior experience; that is the &lt;strong&gt;prior&lt;/strong&gt;. Then, the doctor looks at new data such as fever, cough, loss of taste, X-ray images, or test results; that is the information that goes into the &lt;strong&gt;likelihood&lt;/strong&gt;. Combining these two parts, the doctor has an updated belief about the most plausible diagnosis; that is the &lt;strong&gt;posterior&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_doctor_diagnosis_symptoms.png&quot; alt=&quot;The patient&apos;s initial symptoms&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_doctor_diagnosis_prior.png&quot; alt=&quot;The diagnostic prior before strong evidence&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_doctor_diagnosis_new_data.png&quot; alt=&quot;New data changes the plausibility of each hypothesis&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_doctor_diagnosis_posterior.png&quot; alt=&quot;The posterior after updating with evidence&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-the-bayes-formula&quot;&gt;3. The Bayes formula&lt;/h2&gt;

&lt;p&gt;Bayes’ theorem is written as follows:&lt;/p&gt;

\[P(\theta \mid D) = \frac{P(D \mid \theta)\,P(\theta)}{P(D)}.\]

&lt;p&gt;Here, \(P(\theta \mid D)\) is the &lt;strong&gt;posterior&lt;/strong&gt;, \(P(D \mid \theta)\) is the &lt;strong&gt;likelihood&lt;/strong&gt;, \(P(\theta)\) is the &lt;strong&gt;prior&lt;/strong&gt;, and \(P(D)\) is the &lt;strong&gt;evidence&lt;/strong&gt; or normalizing constant.&lt;/p&gt;

&lt;p&gt;If we only need to look at the structure, we usually remember the short form:&lt;/p&gt;

\[\text{posterior} \propto \text{likelihood} \times \text{prior}.\]

&lt;h3 id=&quot;31-quick-review-of-conditional-probability-and-total-probability&quot;&gt;3.1. Quick review of conditional probability and total probability&lt;/h3&gt;

&lt;p&gt;Before using Bayes, we need two very short pieces:&lt;/p&gt;

\[P(A\mid B)=\frac{P(A\cap B)}{P(B)}\]

&lt;p&gt;and&lt;/p&gt;

\[P(B)=\sum_i P(B\mid A_i)P(A_i)\]

&lt;p&gt;where \(\{A_i\}\) are mutually exclusive cases that cover all possibilities.&lt;/p&gt;

&lt;p&gt;For a binary problem (disease/no disease), the total probability formula is usually written:&lt;/p&gt;

\[P(B)=P(B\mid A)P(A)+P(B\mid A&apos;)P(A&apos;).\]

&lt;p&gt;This is exactly the normalizing denominator in Bayes’ theorem.&lt;/p&gt;

&lt;h2 id=&quot;4-reading-the-formula-in-words&quot;&gt;4. Reading the formula in words&lt;/h2&gt;

&lt;p&gt;Don’t rush to see Bayes as a scary formula. Read it in plain English:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;My new belief about a hypothesis is proportional to how strongly the data supports that hypothesis, multiplied by how strongly I believed that hypothesis beforehand.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is an extremely natural idea.&lt;/p&gt;

&lt;p&gt;If a hypothesis has a high prior and the data also fits it, its posterior will be high. Conversely, if the prior is already low and the data does not support it either, the posterior will be low.&lt;/p&gt;

&lt;h2 id=&quot;5-a-classic-example-the-biased-coin&quot;&gt;5. A classic example: the biased coin&lt;/h2&gt;

&lt;p&gt;Suppose we want to know what the probability \(\theta\) of heads for a coin is.&lt;/p&gt;

&lt;h3 id=&quot;before-the-data&quot;&gt;Before the data&lt;/h3&gt;

&lt;p&gt;We think the coin may be nearly balanced, but are not sure; that is the prior.&lt;/p&gt;

&lt;h3 id=&quot;the-data&quot;&gt;The data&lt;/h3&gt;

&lt;p&gt;We toss 10 times and see 7 heads.&lt;/p&gt;

&lt;h3 id=&quot;the-update&quot;&gt;The update&lt;/h3&gt;

&lt;p&gt;Bayes combines the initial prior with the 7/10 data to produce the posterior for \(\theta\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/coin_bayes_visualization.png&quot; alt=&quot;Bayes with the coin example&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The important point is that the posterior is not simply equal to the prior, nor just equal to the observed proportion 0.7. It is a compromise between what we believed before and what the data is saying.&lt;/p&gt;

&lt;h2 id=&quot;6-what-are-the-prior-likelihood-and-posterior-really&quot;&gt;6. What are the prior, likelihood and posterior, really?&lt;/h2&gt;

&lt;h3 id=&quot;61-prior&quot;&gt;6.1. Prior&lt;/h3&gt;

&lt;p&gt;The prior is what we believe before the current data. For example, we may know that the pass rate of a course has usually been around 70%, that a similar drug is usually only moderately effective, or that a coin bought from a shop is usually nearly balanced.&lt;/p&gt;

&lt;h3 id=&quot;62-likelihood&quot;&gt;6.2. Likelihood&lt;/h3&gt;

&lt;p&gt;The likelihood measures how well the current data fits each parameter value. For example, if the coin is truly balanced how plausible is the data of 7/10 heads, or if the true pass rate is 0.9 is the current data still plausible.&lt;/p&gt;

&lt;h3 id=&quot;63-posterior&quot;&gt;6.3. Posterior&lt;/h3&gt;

&lt;p&gt;The posterior is the belief after updating. It is the central object of Bayesian inference because from the posterior we can answer where the parameter is likely to lie, what the probability is that it exceeds a threshold, or what its most plausible range of values is.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayes_theorem_prior.png&quot; alt=&quot;The prior before looking at the data&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayes_theorem_likelihood.png&quot; alt=&quot;The likelihood shows which parameter values the data supports&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayes_theorem_posterior.png&quot; alt=&quot;The posterior after updating with data&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayes_theorem_prior_vs_posterior.png&quot; alt=&quot;Comparing the prior and posterior to see where the data has pulled belief&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;experiment-count-people-instead-of-multiplying-probabilities&quot;&gt;Experiment: count people instead of multiplying probabilities&lt;/h3&gt;

&lt;p&gt;Drag the base rate, sensitivity and specificity; press Next step to see 1000 people split into sick/healthy, positive/negative and why a positive result is not necessarily a disease.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;bayesrule-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;tree&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;7-a-very-famous-example-a-medical-test&quot;&gt;7. A very famous example: a medical test&lt;/h2&gt;

&lt;p&gt;This is an example that helps learners see where Bayes is strong.&lt;/p&gt;

&lt;p&gt;Suppose there is a rare disease that only 1% of the population has, a test with high sensitivity and high specificity, and a person receives a positive result. The question the patient really cares about is: “So what is the probability that I really have the disease?”&lt;/p&gt;

&lt;p&gt;Many people mistakenly think that a positive result is almost synonymous with surely having the disease. But Bayes shows that if the disease is very rare then the initial prior is very low, so even a fairly good test does not necessarily push the posterior to an extremely high level.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/medical_test_paradox.png&quot; alt=&quot;The medical test paradox&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Here is one of the places where Bayes gives a much more natural answer than gut intuition.&lt;/p&gt;

&lt;h3 id=&quot;71-computing-concrete-numbers-for-the-rare-disease-test-problem-example-1&quot;&gt;7.1. Computing concrete numbers for the rare-disease test problem (Example 1)&lt;/h3&gt;

&lt;p&gt;Suppose \(P(D)=0.001\) is the initial disease rate, \(P(+\mid D)=0.9\) is the sensitivity, and \(P(+\mid D&apos;)=0.01\) is the false positive rate.&lt;/p&gt;

&lt;p&gt;We need:&lt;/p&gt;

\[P(D\mid +)=\frac{P(+\mid D)P(D)}{P(+)}.\]

&lt;p&gt;With total probability:&lt;/p&gt;

\[P(+)=P(+\mid D)P(D)+P(+\mid D&apos;)P(D&apos;)\]

\[=0.9\times 0.001+0.01\times 0.999=0.01089.\]

&lt;p&gt;Suy ra:&lt;/p&gt;

\[P(D\mid +)=\frac{0.9\times 0.001}{0.01089}\approx 0.0826.\]

&lt;p&gt;Even though the test is fairly good, the posterior is still only about \(8.26\%\) because the disease is too rare (low base rate).&lt;/p&gt;

&lt;h3 id=&quot;72-reading-the-problem-through-the-confusion-matrix&quot;&gt;7.2. Reading the problem through the confusion matrix&lt;/h3&gt;

&lt;p&gt;In a binary diagnostic problem, the &lt;strong&gt;confusion matrix&lt;/strong&gt; helps read the meaning of the quantities correctly: &lt;strong&gt;True Positive (TP)&lt;/strong&gt; is having the disease and testing positive, &lt;strong&gt;False Positive (FP)&lt;/strong&gt; is not having the disease but testing positive, &lt;strong&gt;False Negative (FN)&lt;/strong&gt; is having the disease but testing negative, and &lt;strong&gt;True Negative (TN)&lt;/strong&gt; is not having the disease and testing negative. Then, the sensitivity is \(P(+\mid D)=\frac{TP}{TP+FN}\), the specificity is \(P(-\mid D&apos;)=\frac{TN}{TN+FP}\), and the false positive rate is \(P(+\mid D&apos;)=1-\text{specificity}\).&lt;/p&gt;

&lt;p&gt;What the patient cares about is \(P(D\mid +)\), i.e. the PPV. This is the reason Bayes must be used: from the quantities along the rows/columns of the confusion matrix to infer the posterior probability truly needed for decisions.&lt;/p&gt;

&lt;h3 id=&quot;73-a-context-conditioning-example-example-2&quot;&gt;7.3. A context-conditioning example (Example 2)&lt;/h3&gt;

&lt;p&gt;Suppose \(P(\text{Icy})=0.7\) and \(P(\text{Not Icy})=0.3\), and also \(P(\text{One crashes}\mid \text{Icy})=0.8\) while \(P(\text{One crashes}\mid \text{Not Icy})=0.1\).&lt;/p&gt;

&lt;p&gt;First, use total probability:&lt;/p&gt;

\[P(\text{One crashes})=0.8\times 0.7+0.1\times 0.3=0.59.\]

&lt;p&gt;Suppose we have observed that Watson crashed. Then:&lt;/p&gt;

\[P(\text{Icy}\mid \text{Watson crashes})=\frac{0.8\times 0.7}{0.59}\approx 0.95.\]

&lt;p&gt;The probability that Holmes crashes after knowing Watson crashed:&lt;/p&gt;

\[P(\text{Holmes crashes}\mid \text{Watson crashes})=0.8\times 0.95+0.1\times 0.05=0.765.\]

&lt;p&gt;The important point: we update the belief about the environmental condition (the runway), and then infer the probability of the event of interest.&lt;/p&gt;

&lt;h2 id=&quot;8-what-role-does-the-evidence-play&quot;&gt;8. What role does the evidence play?&lt;/h2&gt;

&lt;p&gt;In the formula:&lt;/p&gt;

\[P(D)\]

&lt;p&gt;is the probability of observing the data under all possible values of the parameter.&lt;/p&gt;

&lt;p&gt;You can think of the evidence as a normalizing constant to ensure the posterior is a valid probability distribution.&lt;/p&gt;

&lt;p&gt;In practice, we usually remember:&lt;/p&gt;

\[P(\theta \mid D) \propto P(D \mid \theta)P(\theta)\]

&lt;p&gt;and leave the normalization for the next step.&lt;/p&gt;

&lt;h2 id=&quot;9-bayes-is-not-used-just-once&quot;&gt;9. Bayes is not used just once&lt;/h2&gt;

&lt;p&gt;A big beauty of Bayes is its &lt;strong&gt;sequential updating&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;For example, today you have week 1 data, tomorrow add week 2 data, and next week add week 3 data. You do not need to think of “starting over” in a completely separate way; the current posterior can become the prior for the next update.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_sequential_updating_prior.png&quot; alt=&quot;The starting step: the initial prior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_sequential_updating_step1.png&quot; alt=&quot;After the first batch of data&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_sequential_updating_step2.png&quot; alt=&quot;After the second batch of data&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_sequential_updating_batch_comparison.png&quot; alt=&quot;Comparing sequential updating with a one-shot update&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This is extremely natural for business dashboards, operational monitoring, and every situation of continually learning from data arriving over time.&lt;/p&gt;

&lt;h3 id=&quot;91-sequential-updating-example-with-two-tests-example-3&quot;&gt;9.1. Sequential updating example with two tests (Example 3)&lt;/h3&gt;

&lt;p&gt;Suppose:&lt;/p&gt;

\[P(\theta=1)=0.7,\quad P(\theta=0)=0.3,\]

&lt;p&gt;with \(\theta=1\) meaning having the disease.&lt;/p&gt;

&lt;p&gt;The first test \(Y\) satisfies \(P(Y=1\mid \theta=1)=0.95\) and \(P(Y=1\mid \theta=0)=0.40\), and we observe \(Y=1\).&lt;/p&gt;

&lt;p&gt;Then:&lt;/p&gt;

\[P(\theta=1\mid Y=1)=\frac{0.95\times 0.7}{0.95\times 0.7+0.40\times 0.3}
=\frac{0.665}{0.785}\approx 0.847.\]

&lt;p&gt;Next, there is a second test \(W\) conditionally independent given \(\theta\), with \(P(W=1\mid \theta=1)=0.99\) so \(P(W=0\mid \theta=1)=0.01\), and \(P(W=1\mid \theta=0)=0.04\) so \(P(W=0\mid \theta=0)=0.96\), and we observe \(W=0\).&lt;/p&gt;

&lt;p&gt;Update 2:&lt;/p&gt;

\[P(\theta=1\mid Y=1,W=0)=
\frac{P(W=0\mid \theta=1)P(\theta=1\mid Y=1)}{P(W=0\mid Y=1)}
\approx 0.052.\]

&lt;p&gt;That is, the posterior changes strongly with new evidence: from \(0.7 \to 0.847 \to 0.052\).&lt;/p&gt;

&lt;h3 id=&quot;experiment-sequential-updating-toss-by-toss&quot;&gt;Experiment: sequential updating toss by toss&lt;/h3&gt;

&lt;p&gt;Three kinds of coins; at each toss, multiply the prior by the likelihood and then normalize; change the prior to see the data gradually dominate.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;bayesrule-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;sequential&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;10-what-about-a-strong-or-weak-prior&quot;&gt;10. What about a strong or weak prior?&lt;/h2&gt;

&lt;p&gt;If the prior is very strong, little data may not change the posterior much. If the prior is weak, the data will have a larger influence. This is not a flaw of Bayes but exactly what we want: when prior knowledge is very solid, we should not throw it away too easily; and when the prior is vague, the data should speak more strongly.&lt;/p&gt;

&lt;h3 id=&quot;101-a-concrete-example-same-data-different-priors&quot;&gt;10.1. A concrete example: same data, different priors&lt;/h3&gt;

&lt;p&gt;Suppose we observe 6 positive cases out of 10.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;If the weak prior is Beta\((1,1)\), the posterior will be Beta\((7,5)\) with a posterior mean of about \(0.583\).&lt;/li&gt;
  &lt;li&gt;If the prior is stronger and already leans toward a high rate, for example Beta\((20,5)\), the posterior will be Beta\((26,9)\) with a posterior mean of about \(0.743\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The same data but different posteriors because the prior brings real information into the problem. This is not “whimsical Bayes”, but Bayes’s way of stating clearly something that always exists in practice: new data is always read in the context of what we already knew.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_prior_strength_weak_prior.png&quot; alt=&quot;Weak prior: the initial belief is still fairly open&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_prior_strength_strong_prior.png&quot; alt=&quot;Strong prior: the initial belief is much more concentrated&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_prior_strength_weak_posterior.png&quot; alt=&quot;When the prior is weak, the posterior is pulled harder by the data&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_prior_strength_strong_posterior.png&quot; alt=&quot;When the prior is strong, the posterior changes less&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;11-what-bayes-really-teaches-us&quot;&gt;11. What Bayes really teaches us&lt;/h2&gt;

&lt;p&gt;Bayes does not only teach a formula. It teaches a way of thinking, in which data does not speak for itself without a model, initial belief is not taboo, new data must have the right to correct old belief, and the whole updating process needs to be presented transparently.&lt;/p&gt;

&lt;p&gt;Once you accept this, you will see the prior and posterior are no longer “strange”, but extremely natural.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; Bayes’ theorem is the rule for updating beliefs when new evidence arrives; the prior, likelihood and posterior are not three separate concepts but three parts of the same inference process; and the power of Bayes lies in the fact that it lets us combine old knowledge with new data transparently.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-identifying-a-mystery-coin-3-hypotheses-2-sequential-flips&quot;&gt;Worked Numerical Example: Identifying a Mystery Coin (3 Hypotheses, 2 Sequential Flips)&lt;/h3&gt;

&lt;p&gt;You pull a coin from a bag containing 3 equally likely coin types: &lt;strong&gt;Fair&lt;/strong&gt; (\(p=0.5\)), &lt;strong&gt;Biased-Heads&lt;/strong&gt; (\(p=0.8\)), and &lt;strong&gt;Biased-Tails&lt;/strong&gt; (\(p=0.2\)), each with prior \(1/3\). You flip it twice and observe &lt;strong&gt;2 Heads (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;HH&lt;/code&gt;)&lt;/strong&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hypothesis \(\theta\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Prior \(P(\theta)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Likelihood \(P(\text{HH}\mid\theta) = p^2\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Prior \(\times\) Likelihood&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Normalized Posterior \(P(\theta\mid\text{HH})\)&lt;/strong&gt;&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Biased-Tails (\(p=0.2\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1/3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.04\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0133\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.04 / 0.93 \approx \mathbf{4.3\%}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Fair (\(p=0.5\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1/3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.25\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0833\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.25 / 0.93 \approx \mathbf{26.9\%}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Biased-Heads (\(p=0.8\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1/3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.64\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.2133\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.64 / 0.93 \approx \mathbf{68.8\%}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Sum (Evidence \(P(D)\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1.00\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;—&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.3100\) (\(= 0.93/3\))&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(100.0\%\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Just two heads shifted belief in the Biased-Heads coin from \(33.3\%\) to &lt;strong&gt;\(68.8\%\)&lt;/strong&gt; while crashing belief in the Biased-Tails coin to \(4.3\%\)!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-of-bayesian-updating&quot;&gt;Explanation: Four Rules of Bayesian Updating&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Order of independent data does not matter (Sequential Invariance):&lt;/strong&gt; Updating on Flip 1 (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;H&lt;/code&gt;) and using that posterior as the prior for Flip 2 (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;H&lt;/code&gt;) gives the &lt;em&gt;exact same&lt;/em&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[4.3%, 26.9%, 68.8%]&lt;/code&gt; as updating on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;HH&lt;/code&gt; all at once!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never assign a prior of exact &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; unless logically impossible (Cromwell’s Rule):&lt;/strong&gt; Because \(0 \times \text{anything} = 0\), no finite amount of data can ever rescue a hypothesis given prior probability &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Proportionality (\(\propto\)) is your algebraic superpower:&lt;/strong&gt; You can drop any constant that doesn’t depend on \(\theta\) during intermediate steps and normalize &lt;em&gt;once&lt;/em&gt; at the very end.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stronger data overwhelms reasonable priors:&lt;/strong&gt; After 100 flips, the likelihood factor \(p^{k}(1-p)^{n-k}\) dominates any non-zero prior.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Using the posterior &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[4.3%, 26.9%, 68.8%]&lt;/code&gt; from the table above as your new prior, if Flip 3 comes up &lt;strong&gt;Tails (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;T&lt;/code&gt;)&lt;/strong&gt; (likelihoods \(0.8, 0.5, 0.2\)), which hypothesis now has the highest posterior probability?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zXtcZ-2adK0&quot;&gt;P01.007 — Định lý Bayes cập nhật niềm tin của mô hình ra sao?&lt;/a&gt; — Phạm Thông, Vietnamese. &lt;strong&gt;watch first&lt;/strong&gt;. Watch, in Vietnamese, how the prior and the data together rewrite belief, exactly the way the lesson wants Bayes’ theorem to be read.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Watch each component—prior, likelihood and normalizing constant—on a diagram, supporting the part that names their roles.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R1vcdhPBlXA&quot;&gt;Statistical Rethinking 2023 - 02 - The Garden of Forking Data&lt;/a&gt; — Richard McElreath, English. Watch the globe water-and-land example, where Bayes’ theorem becomes counting the ways the data could have been generated.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;In the doctor diagnosis example, where does the prior come from and where does the likelihood come from?&lt;/li&gt;
  &lt;li&gt;Why does a positive result on a test not necessarily mean a very high probability of having the disease?&lt;/li&gt;
  &lt;li&gt;Give an example from your own work where today’s posterior can become tomorrow’s prior.&lt;/li&gt;
  &lt;li&gt;Why does the posterior not necessarily coincide with the proportion observed directly from the data?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 1.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 5.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 1-2.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter01/01_04_bayesian_vs_frequentist/&quot;&gt;1.4 Bayesian vs Frequentist - Comparison and Choice&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 1.2: Probability as Plausibility - The Philosophical Foundation of Bayesian Statistics</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_02_probability_as_plausibility/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_02_probability_as_plausibility</id>
   <content type="html">&lt;p&gt;What is the probability that it will rain on your wedding day next month, or that a brand-new rocket design will succeed on its &lt;em&gt;very first&lt;/em&gt; launch? Under the strict frequentist definition (&lt;em&gt;“long-run relative frequency over infinite identical repetitions”&lt;/em&gt;), you cannot even assign a probability to a unique, one-time event! Yet every engineer, doctor, and human being reasons quantitatively about unique uncertain events every single day.&lt;/p&gt;

&lt;p&gt;This lesson introduces the philosophical bedrock of Bayesian statistics: &lt;strong&gt;probability as quantified plausibility (degree of rational belief given information)&lt;/strong&gt;—grounded mathematically by &lt;strong&gt;Cox’s theorem&lt;/strong&gt; and &lt;strong&gt;Dutch Book coherence&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-frequentist-frequency-vs-bayesian-plausibility&quot;&gt;Key ideas: Frequentist Frequency vs. Bayesian Plausibility&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Frequentist View (Long-Run Frequency):&lt;/strong&gt; Probability applies strictly to repeatable random sampling; parameters \(\theta\) are fixed unknown constants, so statements like “\(P(\theta &amp;gt; 0 \mid \text{data}) = 0.92\)” are syntactically illegal!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian View (Epistemic Plausibility):&lt;/strong&gt; Probability measures rational uncertainty about &lt;em&gt;any&lt;/em&gt; proposition—repeatable or one-off—given explicit background information \(I\), written \(P(A \mid I)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cox’s Theorem (1946):&lt;/strong&gt; Proved that &lt;em&gt;any&lt;/em&gt; quantitative system of plausible reasoning obeying three commonsense consistency axioms is mathematically &lt;strong&gt;isomorphic to the laws of probability and Bayes’ theorem&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Calibration &amp;amp; Betting Coherence (Dutch Book):&lt;/strong&gt; If your stated probabilities violate probability axioms (e.g., assigning 60% to Rain and 60% to No Rain), a bookmaker can construct a &lt;strong&gt;Dutch Book&lt;/strong&gt;—a guaranteed-loss set of bets regardless of the outcome!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to understand why Bayesian statistics sees probability as the &lt;strong&gt;degree of plausibility of a belief&lt;/strong&gt; and not just as long-run frequency. You also need to see the strength of this view on real problems, where we must talk about events that happen only once, about hypotheses, and about unknown parameters.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; When you hear “70% chance of rain tomorrow”, you understand it as the current level of confidence used to decide whether to bring an umbrella, not as a frequency observed from countless repetitions of “tomorrow”.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Why is the sentence “the probability of rain tomorrow is 70%” hard to interpret in the frequentist sense but very natural in the Bayesian sense?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;1-a-seemingly-simple-question-what-is-probability-really&quot;&gt;1. A seemingly simple question: what is probability, really?&lt;/h2&gt;

&lt;p&gt;In many traditional statistics courses, probability is usually introduced as the frequency with which an event occurs over very many repetitions. This definition works fairly well for examples such as tossing a coin, rolling dice, or drawing a card from a deck. But it begins to struggle when we ask very everyday questions such as what the probability of rain tomorrow is, what the probability is that this patient has disease A or B, or what the probability is that this model is better than that one.&lt;/p&gt;

&lt;p&gt;Those events are not easily understood as “infinitely repeated” in the mechanical sense.&lt;/p&gt;

&lt;h2 id=&quot;2-the-frequentist-view-probability-is-long-run-frequency&quot;&gt;2. The frequentist view: probability is long-run frequency&lt;/h2&gt;

&lt;p&gt;According to the frequentist view, the probability of an event is its relative frequency as the number of repetitions goes to a very large number.&lt;/p&gt;

&lt;p&gt;For example, if a coin is fair, then when tossed very many times, the proportion of heads will approach 0.5.&lt;/p&gt;

&lt;p&gt;This is a beautiful and important idea. But it has two big limitations.&lt;/p&gt;

&lt;h3 id=&quot;21-it-is-hard-to-apply-to-events-that-happen-only-once&quot;&gt;2.1. It is hard to apply to events that happen only once&lt;/h3&gt;

&lt;p&gt;For example, whether it rains tomorrow, whether this surgery succeeds, or whether the market goes up or down next week.&lt;/p&gt;

&lt;p&gt;You cannot “repeat infinitely many times” exactly the same tomorrow to define probability in the purely frequency sense.&lt;/p&gt;

&lt;h3 id=&quot;22-it-is-uncomfortable-when-talking-about-unknown-parameters&quot;&gt;2.2. It is uncomfortable when talking about unknown parameters&lt;/h3&gt;

&lt;p&gt;In frequentist statistics, the parameter \(\theta\) is considered fixed but unknown, while the data is random. So they do not like the sentence “the probability that \(\theta\) lies between 0.4 and 0.6 is 95%”.&lt;/p&gt;

&lt;p&gt;For them, \(\theta\) is not random, so there is nothing to assign a probability to.&lt;/p&gt;

&lt;h2 id=&quot;3-the-bayesian-view-probability-is-plausibility&quot;&gt;3. The Bayesian view: probability is plausibility&lt;/h2&gt;

&lt;p&gt;Bayesian statistics takes a more natural direction for many practical problems.&lt;/p&gt;

&lt;p&gt;Probability is not only long-run frequency. It is also a degree of belief, a degree of plausibility, or the degree to which we should bet on a proposition, based on the available information. So the sentence “70% chance of rain tomorrow” can be understood very naturally as: given the current information, the proposition “it rains tomorrow” is credible at the 70% level.&lt;/p&gt;

&lt;p&gt;This is not a loose way of speaking. It is the very foundation of Bayesian reasoning.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/linh_umbrella_story.png&quot; alt=&quot;The story of Linh and the umbrella&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;4-why-is-the-bayesian-view-closer-to-everyday-life&quot;&gt;4. Why is the Bayesian view closer to everyday life?&lt;/h2&gt;

&lt;p&gt;Because people think this way almost every day.&lt;/p&gt;

&lt;h3 id=&quot;41-weather-forecasts&quot;&gt;4.1. Weather forecasts&lt;/h3&gt;

&lt;p&gt;When you hear “70% chance of rain”, you do not think about countless parallel worlds, but simply think that it is quite likely to rain so it is better to bring an umbrella.&lt;/p&gt;

&lt;h3 id=&quot;42-medical-diagnosis&quot;&gt;4.2. Medical diagnosis&lt;/h3&gt;

&lt;p&gt;A doctor does not only look at the current symptoms. They also use the frequency of the disease in the community, age and medical history, as well as previous test results. That is exactly the thinking of updating beliefs based on information.&lt;/p&gt;

&lt;h3 id=&quot;43-business&quot;&gt;4.3. Business&lt;/h3&gt;

&lt;p&gt;A startup sees its first 3 customers all make a purchase. No one immediately concludes that the true purchase rate is 100%. We keep a reasonable level of uncertainty, and then continue updating as more data arrives.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayesian_daily_life_night_noise.png&quot; alt=&quot;Hearing a strange noise and then updating the hypothesis about its cause&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayesian_daily_life_restaurant.png&quot; alt=&quot;Reading restaurant reviews and then updating the rating&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayesian_daily_life_weather.png&quot; alt=&quot;Weather forecasting as a belief-updating process&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_bayesian_daily_life_medical.png&quot; alt=&quot;Medical diagnosis as a belief-updating process&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;5-an-intuitive-example-a-friends-coin&quot;&gt;5. An intuitive example: a friend’s coin&lt;/h2&gt;

&lt;p&gt;Suppose your friend hands you a coin and says: “I just tossed it 10 times and got 8 heads.” The question you really want to answer is what the probability of heads for this coin could be.&lt;/p&gt;

&lt;h3 id=&quot;what-would-a-frequentist-say&quot;&gt;What would a frequentist say?&lt;/h3&gt;

&lt;p&gt;They would say something like: the true parameter is a fixed constant, and we can only estimate it and then build a confidence interval.&lt;/p&gt;

&lt;h3 id=&quot;what-would-a-bayesian-say&quot;&gt;What would a Bayesian say?&lt;/h3&gt;

&lt;p&gt;A Bayesian would say that before the data, I have a prior about \(\theta\); after the data of 8/10, I update that prior into a posterior; and the posterior tells which region of \(\theta\) is currently more plausible.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_coin_flip_frequentist.png&quot; alt=&quot;How a frequentist statistician views the coin problem&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_coin_flip_bayesian.png&quot; alt=&quot;How a Bayesian statistician views the coin problem&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The strength here is that Bayes lets us speak directly about the unknown parameter, the current level of belief, and how that belief changes with data.&lt;/p&gt;

&lt;h3 id=&quot;reading-it-in-numbers&quot;&gt;Reading it in numbers&lt;/h3&gt;

&lt;p&gt;If we start with a uniform prior Beta\((1,1)\) and observe 8 heads in 10 tosses, the posterior will be Beta\((9,3)\). The posterior mean is then:&lt;/p&gt;

\[\frac{9}{9+3}=0.75.\]

&lt;p&gt;We can even directly ask questions like “what is the probability that the coin is biased toward heads rather than fair?”, i.e. \(P(\theta&amp;gt;0.5\mid D)\), and that value is then about \(0.97\). This is exactly the spirit of “probability is plausibility”: it lets us say outright how plausible the parameter values are after having looked at the data.&lt;/p&gt;

&lt;h2 id=&quot;6-is-subjective-a-weakness&quot;&gt;6. Is “subjective” a weakness?&lt;/h2&gt;

&lt;p&gt;Many people hear “degree of belief” and worry that Bayes is too subjective. But we need to distinguish between &lt;strong&gt;principled subjectivity&lt;/strong&gt; and arbitrariness. In Bayes, you are not allowed to assign probabilities absurdly; the probabilities must still be coherent, obey the rules of probability, and can be corrected by data. In other words, Bayes allows personal belief to appear, but forces that belief to have logical structure and to be accountable to the data.&lt;/p&gt;

&lt;h2 id=&quot;7-the-dutch-book-intuition-why-must-beliefs-be-coherent&quot;&gt;7. The Dutch book intuition: why must beliefs be coherent?&lt;/h2&gt;

&lt;p&gt;A very nice way to think about it is this: if your system of probabilities is not coherent, others can arrange bets that make you lose for sure.&lt;/p&gt;

&lt;p&gt;This idea is called the Dutch book argument.&lt;/p&gt;

&lt;p&gt;You do not need to dig into this philosophy right away. Just remember one thing:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bayesian probability is not “believe whatever you want”. It is disciplined belief.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/dutch_book_cartoon.png&quot; alt=&quot;Dutch book cartoon&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;8-cox-and-the-idea-of-probability-as-extended-logic&quot;&gt;8. Cox and the idea of “probability as extended logic”&lt;/h2&gt;

&lt;p&gt;A very beautiful way to put it is that classical logic handles what is certainly true or certainly false, while probability handles what is not completely certain.&lt;/p&gt;

&lt;p&gt;In that spirit, Bayesian probability can be seen as a form of &lt;strong&gt;extended logic for an uncertain world&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This explains why Bayes feels natural: when there is no data, we keep an initial level of belief; when new data arrives, we update it.&lt;/p&gt;

&lt;h2 id=&quot;9-who-is-random-who-is-fixed&quot;&gt;9. Who is random? Who is fixed?&lt;/h2&gt;

&lt;p&gt;This is the core difference between Frequentist and Bayesian.&lt;/p&gt;

&lt;h3 id=&quot;frequentist&quot;&gt;Frequentist&lt;/h3&gt;

&lt;p&gt;For a frequentist, the parameter is fixed but unknown, while the data is random.&lt;/p&gt;

&lt;h3 id=&quot;bayesian&quot;&gt;Bayesian&lt;/h3&gt;

&lt;p&gt;For a Bayesian, the observed data is already fixed, while the unknown parameter is described by a probability distribution.&lt;/p&gt;

&lt;p&gt;This leads to a very big difference in how results are interpreted.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_philosophy_frequentist.png&quot; alt=&quot;Frequentist views probability through repeated data&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_philosophy_bayesian.png&quot; alt=&quot;Bayesian views probability as uncertainty about the parameter&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;10-why-is-this-chapter-so-important-for-what-follows&quot;&gt;10. Why is this chapter so important for what follows?&lt;/h2&gt;

&lt;p&gt;If you cannot accept that probability can describe reasonable belief, then all of the Bayes that follows will look very strange. But once you see this, concepts such as prior, posterior, credible interval, or the probability of a hypothesis will become very natural.&lt;/p&gt;

&lt;h2 id=&quot;11-a-short-way-to-remember&quot;&gt;11. A short way to remember&lt;/h2&gt;

&lt;p&gt;If we had to sum it up in just two sentences, the Frequentist ties probability to the long-run frequency of repeatable data, while the Bayesian ties probability to the degree of plausibility of what we believe given the available information.&lt;/p&gt;

&lt;p&gt;Neither side is completely wrong and the other completely right in every situation. But Bayes is much more flexible for real scientific questions.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; Frequentist and Bayesian differ first of all in how they define probability, not only in computational technique; the Bayesian view treats probability as plausibility, so it applies naturally to hypotheses, parameters and events that happen only once; and “subjective” in Bayes does not mean arbitrary, because beliefs must still obey the coherent rules of probability.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-constructing-a-dutch-book-against-incoherent-beliefs&quot;&gt;Worked Numerical Example: Constructing a Dutch Book Against Incoherent Beliefs&lt;/h3&gt;

&lt;p&gt;Suppose a forecaster violates the sum rule by assigning \(P(\text{Rain}) = 0.60\) and \(P(\text{No Rain}) = 0.60\) (summing to \(1.20 &amp;gt; 1\)). That means they think $0.60 is a fair price to buy a ticket paying $1.00 if Rain occurs, &lt;em&gt;and&lt;/em&gt; $0.60 is a fair price for a ticket paying $1.00 if No Rain occurs!&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bookmaker sells both tickets&lt;/strong&gt; to the forecaster for \(0.60 + 0.60 = \mathbf{\$1.20}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;If it rains:&lt;/strong&gt; Forecaster collects $$1.00$ \(\implies\) &lt;strong&gt;net loss of $-$0.20$&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;If it stays dry:&lt;/strong&gt; Forecaster collects $$1.00$ \(\implies\) &lt;strong&gt;net loss of $-$0.20$&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The forecaster loses money with &lt;strong&gt;100% certainty&lt;/strong&gt;! Coherence forces probabilities of mutually exclusive exhaustive events to sum to exactly \(1.00\)—and forces belief updates to obey Bayes’ theorem!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-clarifications-on-subjective-bayesian-probability&quot;&gt;Explanation: Four Clarifications on “Subjective” Bayesian Probability&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;“Subjective” means &lt;em&gt;information-dependent&lt;/em&gt;, not arbitrary:&lt;/strong&gt; Two scientists with different background information \(I_1 \neq I_2\) rationally assign different probabilities—and once they share the same data, Bayes’ rule pulls their posteriors together!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Probability is a property of your &lt;em&gt;knowledge&lt;/em&gt;, not just the physical coin:&lt;/strong&gt; Before you peek under your hand at a coin already flipped, the physical coin is fixed, yet \(P(\text{Heads} \mid I) = 0.5\) accurately describes your uncertainty.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Frequentist and Bayesian probabilities agree on symmetric physical games:&lt;/strong&gt; On a known fair die, both views assign \(1/6\)—Bayesian probability strictly &lt;em&gt;generalizes&lt;/em&gt; frequency to parameters and unique events.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always make your conditioning information explicit:&lt;/strong&gt; Writing \(P(\theta \mid D, M)\) reminds you that every conclusion depends on both the data \(D\) and the modeling assumptions \(M\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If a model predicts 70% probability of Team A winning and 45% probability of Team B winning (no ties possible), how much guaranteed profit can a bookmaker lock in per $1 payout pair?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=R13BD8qKeTg&quot;&gt;The Bayesian Trap&lt;/a&gt; — Veritasium, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch probability used as a degree of belief in a hypothesis, exactly the shift in meaning from long-run frequency to plausibility.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=akClB1J6b28&quot;&gt;Bayes’ Theorem (with Example!)&lt;/a&gt; — Steve Brunton, English. Watch Bayes’ theorem as an inverse problem from symptoms back to causes, supporting the one-off situations in the lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Watch belief updated by area, used when the lesson needs a picture for probability as plausibility.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why is the forecast “70% chance of rain tomorrow” a very natural example for the Bayesian understanding of probability?&lt;/li&gt;
  &lt;li&gt;In the coin problem with 8/10 heads, what is the most important way in which a Frequentist and a Bayesian differ?&lt;/li&gt;
  &lt;li&gt;Give an example from work or life where understanding probability as plausibility is more useful than understanding it as frequency.&lt;/li&gt;
  &lt;li&gt;Why does Bayes still have logical discipline even though it allows initial beliefs to be brought into the model?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Jaynes, E. T. &lt;em&gt;Probability Theory: The Logic of Science&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 1.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 1.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter01/01_03_bayes_theorem_posterior/&quot;&gt;1.3 Bayes’ Theorem - A Tool for Updating Beliefs&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 1.1: The Scientific Crisis and the Limits of P-values</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_01_replication_crisis_pvalues/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter01/01_01_replication_crisis_pvalues</id>
   <content type="html">&lt;p&gt;In 2015, the Open Science Collaboration attempted to replicate 100 landmark psychology experiments published in top peer-reviewed journals—and &lt;strong&gt;more than 60% failed to replicate!&lt;/strong&gt; In medicine, economics, and online A/B testing, the exact same shock hit: hundreds of “statistically significant” results with \(p &amp;lt; 0.05\) vanished upon re-testing. How could so many peer-reviewed findings be false when the significance threshold was supposed to limit errors to 5%?&lt;/p&gt;

&lt;p&gt;The culprit wasn’t bad arithmetic—it was &lt;strong&gt;base-rate neglect, low statistical power, and researcher degrees of freedom (p-hacking)&lt;/strong&gt; colliding with a binary &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p &amp;lt; 0.05&lt;/code&gt; ritual. This opening Chapter 1 lesson diagnoses the replication crisis mathematically and shows why &lt;strong&gt;Bayesian updating&lt;/strong&gt; provides the missing vaccine.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-why-p--005-fails-without-base-rates-and-power&quot;&gt;Key ideas: Why &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p &amp;lt; 0.05&lt;/code&gt; Fails Without Base Rates and Power&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Positive Predictive Value (PPV) vs. p-value:&lt;/strong&gt; Even when \(\alpha = 0.05\) is obeyed honestly, if only 10% of tested hypotheses are actually true (low base rate) and power is 50%, &lt;strong&gt;almost half of all &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p &amp;lt; 0.05&lt;/code&gt; discoveries are false positives!&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Garden of Forking Paths (p-hacking &amp;amp; Optional Stopping):&lt;/strong&gt; Testing multiple subgroups, dropping outliers after seeing results, or peeking early inflates effective \(\alpha\) from 5% to 30%+.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Publication Bias (File-Drawer Effect):&lt;/strong&gt; Journals publish the 5% of noisy studies that cross &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p &amp;lt; 0.05&lt;/code&gt; and bury the 95% null studies—exaggerating reported effect sizes (&lt;em&gt;Type M error&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Bayesian Remedy:&lt;/strong&gt; Explicitly incorporates prior plausibility, updates continuously without optional-stopping penalties on the likelihood, and reports full posterior distributions rather than binary pass/fail cliffs.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you need to understand three things. First, why many published studies cannot be replicated. Second, why the p-value is often misunderstood and easily misused. Third, why those problems push the scientific community to look for other ways of inference, including Bayesian statistics.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Mini example.&lt;/strong&gt; A study reports p-value &amp;lt; 0.05, showing that a new drug is effective, but when another group repeats the exact same design, the effect is no longer seen. This is exactly the kind of situation that gives rise to the replication crisis.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Does a small p-value really mean the research hypothesis is true?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;1-what-is-the-replication-crisis&quot;&gt;1. What is the replication crisis?&lt;/h2&gt;

&lt;p&gt;In science, a trustworthy result does not only need to look “nice” in one paper. It needs to be &lt;strong&gt;repeatable&lt;/strong&gt; when another group redoes the experiment with a similar procedure.&lt;/p&gt;

&lt;p&gt;But in many fields such as psychology, preclinical medicine, or the social sciences, many prominent results have failed to replicate.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/replication_crisis_stats.png&quot; alt=&quot;Replication crisis statistics&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This does not mean every scientist is cheating. Most of the problem lies in the fact that data is often noisy, sample sizes are sometimes small, and the publishing system rewards very strongly the results labeled “statistically significant”.&lt;/p&gt;

&lt;h2 id=&quot;2-a-very-everyday-story-behind-this-crisis&quot;&gt;2. A very everyday story behind this crisis&lt;/h2&gt;

&lt;p&gt;Imagine 20 independent research groups all test a hypothesis that is actually false. If each group uses the threshold \(p &amp;lt; 0.05\), then by chance alone, we still expect about 1 group to find a “significant result”.&lt;/p&gt;

&lt;p&gt;If exactly the group that finds that “nice” result gets published, while the other 19 groups publish nothing, then the whole scientific literature will look as if the hypothesis had just been supported.&lt;/p&gt;

&lt;p&gt;That is one of the most dangerous mechanisms behind the replication crisis.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/publication_bias.png&quot; alt=&quot;Publication bias and the file drawer problem&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-what-is-a-p-value-really&quot;&gt;3. What is a p-value, really?&lt;/h2&gt;

&lt;p&gt;Here is the standard definition:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;The p-value is the probability of observing data at least as extreme as the data at hand, assuming the null hypothesis \(H_0\) is true.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Put more briefly, the p-value answers the question:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If the null hypothesis \(H_0\) is true, is this data unusual?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For example, if \(H_0\) says the drug has no effect, and the data show the drug group improved more than the control group, then a small p-value only means that data like this is quite unusual if the null hypothesis is really true.&lt;/p&gt;

&lt;p&gt;The problem starts here: that is &lt;strong&gt;not&lt;/strong&gt; the question the researcher really wants to know.&lt;/p&gt;

&lt;p&gt;Researchers usually want to know how likely the hypothesis is to be true, how strong the evidence is, whether the effect is large, and how trustworthy the result itself is. The p-value does not directly answer those questions.&lt;/p&gt;

&lt;h2 id=&quot;4-an-easier-way-to-read-the-p-value&quot;&gt;4. An easier way to read the p-value&lt;/h2&gt;

&lt;p&gt;Suppose a trial gives \(p = 0.03\). That does &lt;strong&gt;not&lt;/strong&gt; mean “the probability that the null hypothesis is true is 3%”, nor does it mean “the probability that the drug is effective is 97%”.&lt;/p&gt;

&lt;p&gt;It only means that if there truly is no effect, the probability of seeing this data or something more extreme is only about 3%.&lt;/p&gt;

&lt;p&gt;The difference sounds small, but is actually a large gap in logic.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_misconception_h0_probability.png&quot; alt=&quot;The p-value is not the probability that H0 is true&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Illustration: the p-value lies in the direction \(P(\\text{data} \\mid H_0)\), not in the direction \(P(H_0 \\mid \\text{data})\).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_misconception_one_minus_p.png&quot; alt=&quot;1 - p is also not the probability that the research hypothesis is true&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Illustration: taking &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1 - p&lt;/code&gt; and treating it as the probability that the research hypothesis is true is a wrong logical leap.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;5-the-most-common-misconceptions-about-the-p-value&quot;&gt;5. The most common misconceptions about the p-value&lt;/h2&gt;

&lt;p&gt;These are very common misconceptions, even in scientific papers.&lt;/p&gt;

&lt;h3 id=&quot;misconception-1-the-p-value-is-the-probability-that-the-null-hypothesis-is-true&quot;&gt;Misconception 1. The p-value is the probability that the null hypothesis is true&lt;/h3&gt;

&lt;p&gt;Wrong. The p-value is:&lt;/p&gt;

\[P(\text{data or more extreme} \mid H_0),\]

&lt;p&gt;not:&lt;/p&gt;

\[P(H_0 \mid \text{data}).\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_misconception_h0_probability.png&quot; alt=&quot;Misconception 1 about the p-value&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;misconception-2-a-small-p-value-means-a-large-effect&quot;&gt;Misconception 2. A small p-value means a large effect&lt;/h3&gt;

&lt;p&gt;Wrong. The p-value also depends strongly on sample size: with a very large sample, a very small effect can still give a small p-value; while with a small sample, a relatively large effect may still not be small enough to pass the 0.05 threshold.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_misconception_effect_size.png&quot; alt=&quot;Misconception 2: a small p does not mean a large effect&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;misconception-3-p-value--005-means-there-is-no-effect&quot;&gt;Misconception 3. P-value &amp;gt; 0.05 means there is no effect&lt;/h3&gt;

&lt;p&gt;Wrong. It may only say that the current data is not strong enough to detect the effect.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_misconception_large_p_no_effect.png&quot; alt=&quot;Misconception 3: a large p does not mean there is surely no effect&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;misconception-4-0049-and-0051-differ-in-nature&quot;&gt;Misconception 4. 0.049 and 0.051 differ in nature&lt;/h3&gt;

&lt;p&gt;In fact, they almost do not. But when 0.05 is turned into a rigid pass/fail line, people usually interpret them as two completely different worlds.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_misconception_alpha_threshold.png&quot; alt=&quot;Misconception 4: the 0.05 threshold as a magic boundary&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_misconception_summary.png&quot; alt=&quot;Summary of the major misconceptions about the p-value&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-why-is-the-p-value-easily-misused&quot;&gt;6. Why is the p-value easily misused?&lt;/h2&gt;

&lt;p&gt;When the publishing system rewards “statistically significant” results, researchers are easily pulled into behaviors such as trying many different outcome variables, trying many ways of filtering data, selectively removing outliers, stopping data collection as soon as the threshold is reached, or reporting only the nicest analysis.&lt;/p&gt;

&lt;p&gt;Those behaviors do not always stem from cheating. Often they stem from publication pressure and from researchers convincing themselves that they are only “exploring the data”.&lt;/p&gt;

&lt;p&gt;But the consequence is the same: the false discovery rate rises sharply.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/phacking_techniques.png&quot; alt=&quot;P-hacking techniques&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;7-optional-stopping-a-very-common-example&quot;&gt;7. Optional stopping: a very common example&lt;/h2&gt;

&lt;p&gt;Suppose you start with 20 participants and do not yet see a small enough p-value. You recruit 10 more people, then 10 more again, and stop when p &amp;lt; 0.05.&lt;/p&gt;

&lt;p&gt;It sounds harmless, but this is a quiet way of raising the probability of finding a “significant result” purely by luck.&lt;/p&gt;

&lt;p&gt;In Bayes, sequential updating is much more natural, whereas in classical frequentist testing, stopping when looking at the data can break the original interpretation of the p-value.&lt;/p&gt;

&lt;h3 id=&quot;71-a-numerical-example-keep-looking-until-p--005&quot;&gt;7.1. A numerical example: keep looking until p &amp;lt; 0.05&lt;/h3&gt;

&lt;p&gt;Suppose a study starts with 20 participants and gives \(p=0.18\). The researcher is not satisfied, so recruits 10 more people, and now \(p=0.09\). Still not “nice” enough, so they recruit 10 more and see \(p=0.047\), then stop immediately and publish the result as statistically significant.&lt;/p&gt;

&lt;p&gt;The problem is not in the number \(0.047\) alone, but in the fact that the stopping rule depended on the very data being observed. If from the start the plan had been to collect 60 people and only then test, the final p-value could well bounce back to a level like \(0.11\). Optional stopping therefore increases the chance of “luckily” hitting the threshold, even though the true effect may be very weak or nonexistent.&lt;/p&gt;

&lt;h2 id=&quot;8-publication-bias-what-distorts-the-scientific-picture&quot;&gt;8. Publication bias: what distorts the scientific picture&lt;/h2&gt;

&lt;p&gt;Even when each individual study does everything right, science can still be distorted if “positive” results are published while “negative” results are left in the drawer.&lt;/p&gt;

&lt;p&gt;Then readers only see “successful” studies, and easily think that the evidence for a hypothesis is stronger than it really is.&lt;/p&gt;

&lt;p&gt;This is why we cannot evaluate a finding from a single paper alone.&lt;/p&gt;

&lt;h2 id=&quot;9-a-famous-example-extrasensory-perception-and-extraordinary-findings&quot;&gt;9. A famous example: extrasensory perception and extraordinary findings&lt;/h2&gt;

&lt;p&gt;An example often mentioned is the studies claiming to have evidence for extrasensory perception. Looking only at p-values, some results look “noteworthy”. But scientific intuition says that the more extraordinary a claim is, the much stronger the evidence needed.&lt;/p&gt;

&lt;p&gt;The p-value cannot distinguish between a very ordinary claim like “aspirin reduces headaches” and an extremely extraordinary claim like “people can see the future”. It only scores how “unusual the data is under the null hypothesis”.&lt;/p&gt;

&lt;p&gt;Bayesian analysis is different in that it allows us to bring in &lt;strong&gt;prior plausibility&lt;/strong&gt;. A hypothesis that is very hard to believe from the start will need a much stronger amount of evidence for the posterior to become convincing.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_vs_posterior_frequentist.png&quot; alt=&quot;The Frequentist view: the p-value measures how unusual the data is&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter01/chapter01_pvalue_vs_posterior_bayesian.png&quot; alt=&quot;The Bayesian view: the posterior speaks directly about the probability we care about&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;10-the-deeper-problem-the-p-value-answers-the-wrong-question&quot;&gt;10. The deeper problem: the p-value answers the wrong question&lt;/h2&gt;

&lt;p&gt;This is the most important point of the lesson.&lt;/p&gt;

&lt;p&gt;Scientists usually want to know which hypothesis is more credible, where the parameter may lie, how strongly the data support this hypothesis, and how much uncertainty remains.&lt;/p&gt;

&lt;p&gt;The p-value asks a different question: if the null hypothesis \(H_0\) is true, is this data unusual or not.&lt;/p&gt;

&lt;p&gt;It can be useful in some testing contexts, but it is not the direct answer to the core scientific concern.&lt;/p&gt;

&lt;h2 id=&quot;11-why-does-this-lesson-pave-the-way-for-bayes&quot;&gt;11. Why does this lesson pave the way for Bayes?&lt;/h2&gt;

&lt;p&gt;Bayesian statistics is attractive not because it “hates p-values”, but because it tries to answer more directly the things we truly care about: the probability of a hypothesis after seeing data, the distribution of unknown parameters, the current level of uncertainty, and how to update beliefs when new information arrives.&lt;/p&gt;

&lt;p&gt;Chapter 1 will gradually lead you to exactly that point. This lesson only plays the role of a warm-up: pointing out why so many people have felt that the old way of inference is not enough.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;3 key ideas.&lt;/strong&gt; The replication crisis is not only the fault of individual researchers but also a problem of the whole system of inference and publication incentives; the p-value is easily misunderstood because it answers a different question from the scientific question we truly care about; and when p-values become a target to hit, p-hacking and publication bias appear almost inevitably.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-computing-the-true-false-discovery-rate-behind-p--005&quot;&gt;Worked Numerical Example: Computing the True False-Discovery Rate Behind &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p &amp;lt; 0.05&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;Suppose a lab tests &lt;strong&gt;1,000 hypotheses&lt;/strong&gt;, of which only &lt;strong&gt;10%&lt;/strong&gt; (100) are truly non-null and &lt;strong&gt;90%&lt;/strong&gt; (900) are truly null, using \(\alpha = 0.05\) and typical statistical power \(1 - \beta = 0.50\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hypothesis Reality&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Count&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Significant (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p &amp;lt; 0.05&lt;/code&gt;)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Not Significant&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;True Effect (\(H_1\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(100\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(100 \times 0.50 = \mathbf{50}\) (True Positives)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(50\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;No Effect (\(H_0\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(900\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(900 \times 0.05 = \mathbf{45}\) (False Positives)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(855\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Total Published (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p &amp;lt; 0.05&lt;/code&gt;)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1{,}000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(95\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(905\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Compute the probability that a published &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p &amp;lt; 0.05&lt;/code&gt; finding is actually a &lt;strong&gt;false alarm&lt;/strong&gt;:
\(\mathrm{FDR} = \frac{45}{50 + 45} = \frac{45}{95} \approx \mathbf{47.4\%}!\)
Nearly &lt;strong&gt;half&lt;/strong&gt; of all “statistically significant” findings are false—even with zero cheating!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-scientific-habits-that-prevent-false-discoveries&quot;&gt;Explanation: Four Scientific Habits That Prevent False Discoveries&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always ask “what was the prior base rate?”&lt;/strong&gt; Extraordinary claims (e.g., 1% base rate) require far stronger evidence than &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p = 0.04&lt;/code&gt; to become credible.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pre-register hypotheses and report effect sizes with uncertainty:&lt;/strong&gt; Replacing binary &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p &amp;lt; 0.05&lt;/code&gt; headlines with posterior intervals prevents cliff-chasing.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Shrink small-sample discoveries toward zero:&lt;/strong&gt; Hierarchical Bayesian models automatically guard against inflated Type M effect sizes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Value replication as sequential Bayesian updating:&lt;/strong&gt; Yesterday’s posterior becomes today’s prior—science accumulates evidence continuously instead of resetting to zero on every paper.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the 1,000-hypothesis table above, if researchers boost statistical power from \(50\%\) to \(80\%\) (keeping base rate 10% and \(\alpha = 0.05\)), how many True Positives do they find, and what does the False Discovery Rate drop to?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vemZtEM63GY&quot;&gt;p-values: What they are and how to interpret them&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch which question the p-value really answers, exactly the part of the lesson that points out the common misreadings.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HDCOUXE3HMM&quot;&gt;p-hacking: What it is and how to avoid it!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch p-hacking arise from flexible analysis choices, supporting the argument for why many results do not replicate.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[The reproducibility crisis and other problems in science&lt;/td&gt;
          &lt;td&gt;John Ioannidis](https://www.youtube.com/watch?v=vY9mGJQFdyE) — The Institute of Art and Ideas, English. Watch John Ioannidis discuss the replication crisis, used for the part of the lesson linking test misuse to belief in publications.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why can a study with a small p-value still fail to replicate?&lt;/li&gt;
  &lt;li&gt;Explain in words the difference between \(P(\text{data} \mid H_0)\) and \(P(H_0 \mid \text{data})\).&lt;/li&gt;
  &lt;li&gt;Why can a large sample size make an effect that is small and practically meaningless still give a very small p-value?&lt;/li&gt;
  &lt;li&gt;Give an everyday example of publication bias outside science.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A. et al. &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.), Chapter 1.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.), Chapter 11.&lt;/li&gt;
  &lt;li&gt;McElreath, R. &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.), Chapter 1.&lt;/li&gt;
  &lt;li&gt;Wasserstein, R. L., &amp;amp; Lazar, N. A. (2016). The ASA Statement on p-Values.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter01/01_02_probability_as_plausibility/&quot;&gt;1.2 Probability as Plausibility - The Bayesian View&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.21: Simulation to Test Statistical Intuition</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_19_simulation_for_statistical_intuition/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_19_simulation_for_statistical_intuition</id>
   <content type="html">&lt;p&gt;Whenever a probability puzzle or Bayesian model makes your head spin, stop staring at integrals and &lt;strong&gt;simulate it 10,000 times in 5 lines of Python!&lt;/strong&gt; Simulation is the ultimate truth serum of modern statistics: it lets you verify algebraic formulas in seconds, test whether an estimator actually recovers ground-truth parameters (&lt;em&gt;Simulation-Based Calibration&lt;/em&gt;), and see how prior choices behave before you ever touch real data.&lt;/p&gt;

&lt;p&gt;This lesson turns forward simulation into an everyday Bayesian habit—showing how to generate synthetic worlds from a known truth, test your inference code on them, and build unshakable intuition.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-four-ways-simulation-supercharges-bayesian-workflow&quot;&gt;Key ideas: Four Ways Simulation Supercharges Bayesian Workflow&lt;/h2&gt;

&lt;p&gt;In modern Bayesian data analysis (Gelman’s Bayesian Workflow), simulation is not a toy—it is a core validation tool:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Prior Predictive Simulation:&lt;/strong&gt; Sample \(\theta^{(s)} \sim p(\theta)\), then \(y^{(s)} \sim p(y\mid\theta^{(s)})\). Instantly reveals whether your prior implies physically plausible data!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter Recovery Testing:&lt;/strong&gt; Fix a known ground truth \(\theta_{\text{true}}\), simulate fake data \(y_{\text{sim}}\), fit your Bayesian model to \(y_{\text{sim}}\), and verify that the 95% credible interval recovers \(\theta_{\text{true}}\)—catching coding bugs &lt;em&gt;before&lt;/em&gt; analyzing real data!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Empirical Verification of Coverage &amp;amp; Power:&lt;/strong&gt; Repeat simulation 1,000 times to measure true Type I error, credible interval coverage, or sample size needed to achieve desired posterior precision.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Posterior Predictive Checks (PPC):&lt;/strong&gt; Draw \(y^{\text{rep}} \sim p(y\mid\theta^{(s)})\) from posterior draws \(\theta^{(s)}\) and compare simulated datasets against your real observed dataset.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will see simulation as an inference tool and not just an illustration, know how to use simulation to check formulas, detect misunderstood intuitions, and prepare well for a Bayesian workflow based on the generative story.&lt;/p&gt;

&lt;h2 id=&quot;introduction-simulation-as-the-laboratory-of-inference&quot;&gt;Introduction: simulation as the laboratory of inference&lt;/h2&gt;

&lt;p&gt;In many probability problems, verbal intuition easily leads to wrong conclusions, while closed-form formulas are sometimes hard to check quickly in a real context. Simulation provides an intermediate “laboratory”: we state an assumption, generate data according to that assumption, and then compare the consequences with what we believe to be true. This approach helps learning go deeper because it forces us to tie the theoretical model closely to the behavior of observed data.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/simulation_statistical_intuition_workflow.png&quot; alt=&quot;Quy trinh mo phong thong ke&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates the statistical simulation workflow. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;
&lt;em&gt;Figure 1: The 4-step simulation workflow: model assumptions -&amp;gt; set parameters -&amp;gt; generate data -&amp;gt; compare and update.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-why-do-we-need-simulation&quot;&gt;1) Why do we need simulation?&lt;/h2&gt;

&lt;p&gt;Many statistical problems are hard because intuition is easily wrong:&lt;/p&gt;

&lt;p&gt;We may confuse conditional probabilities, misjudge the level of uncertainty, or believe a “nice” result without checking the data-generating mechanism behind it.&lt;/p&gt;

&lt;p&gt;Simulation lets us look directly at the consequences of assumptions.&lt;/p&gt;

&lt;h2 id=&quot;2-the-4-step-simulation-workflow&quot;&gt;2) The 4-step simulation workflow&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;State the data-generating mechanism clearly (generative story).&lt;/li&gt;
  &lt;li&gt;Choose reasonable input parameters.&lt;/li&gt;
  &lt;li&gt;Generate data repeatedly.&lt;/li&gt;
  &lt;li&gt;Summarize the results and compare with the theoretical expectation.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If the simulation result contradicts intuition, it is usually our intuition that needs correcting.&lt;/p&gt;

&lt;h2 id=&quot;3-when-should-we-simulate&quot;&gt;3) When should we simulate?&lt;/h2&gt;

&lt;p&gt;Simulation is especially useful when a formula is too complicated or hard to check by hand, when we want to check sensitivity to parameters, when we need to teach or learn a probability concept visually, or when we need a sanity check for Bayesian inference code.&lt;/p&gt;

&lt;h2 id=&quot;4-a-short-example&quot;&gt;4) A short example&lt;/h2&gt;

&lt;p&gt;To understand the uncertainty interval of a proportion \(p\) when \(n\) is small:&lt;/p&gt;

&lt;p&gt;We can assume the true value \(p=0.2\), simulate many Binomial samples with \(n=20\) and \(n=200\), and then compare the fluctuation of \(\hat p\) between those two settings.&lt;/p&gt;

&lt;p&gt;You will see right away why small data fluctuates a lot and why the prior can matter in settings with little data.&lt;/p&gt;

&lt;h3 id=&quot;41-if-we-look-at-5-concrete-simulation-runs-what-will-we-see&quot;&gt;4.1) If we look at 5 concrete simulation runs, what will we see?&lt;/h3&gt;

&lt;p&gt;With the same true value \(p=0.2\), a typical simulation result might look as follows:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;If \(n=20\): \(\hat p = 0.10, 0.15, 0.20, 0.30, 0.35\)&lt;/li&gt;
  &lt;li&gt;If \(n=200\): \(\hat p = 0.17, 0.19, 0.20, 0.22, 0.24\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both groups revolve around the true value 0.2, but the \(n=20\) group fluctuates much more widely. Just by looking at a few such simulation runs, we already have a very clear intuition for why little data usually makes conclusions less stable.&lt;/p&gt;

&lt;h2 id=&quot;5-direct-connection-to-bayes&quot;&gt;5) Direct connection to Bayes&lt;/h2&gt;

&lt;p&gt;Simulation is the “laboratory” of the Bayesian workflow:&lt;/p&gt;

&lt;p&gt;It lets us check the prior predictive, the posterior predictive, and also the stability of decisions when the input assumptions change.&lt;/p&gt;

&lt;p&gt;In other words, simulation helps us learn the “model implies data” way of thinking.&lt;/p&gt;

&lt;h2 id=&quot;quick-summary&quot;&gt;Quick summary&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Simulation is an inference tool, not just an illustration.&lt;/li&gt;
  &lt;li&gt;The standard workflow: assumptions -&amp;gt; generate data -&amp;gt; repeat -&amp;gt; summarize.&lt;/li&gt;
  &lt;li&gt;Simulation is especially useful for sanity checking Bayesian models.&lt;/li&gt;
  &lt;li&gt;When intuition and simulation conflict, trust the simulated data first and then re-examine the assumptions.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-tracing-a-5-draw-prior-predictive-check-by-hand&quot;&gt;Worked Numerical Example: Tracing a 5-Draw Prior Predictive Check by Hand&lt;/h3&gt;

&lt;p&gt;Suppose your model for 10 user visits is \(\theta \sim \mathrm{Beta}(2, 8)\) (prior mean \(0.20\)) and \(y \mid \theta \sim \mathrm{Binomial}(10, \theta)\). Trace 5 simulated worlds step by step:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Simulation \(s\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Drawn Prior \(\theta^{(s)} \sim \mathrm{Beta}(2,8)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Simulated Clicks \(y^{(s)} \sim \mathrm{Bin}(10, \theta^{(s)})\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.12\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.28\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(3\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.09\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;4&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.35\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(4\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;5&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.18\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;From these simulated worlds, average simulated clicks \(\approx 2.0\) (matching \(\mathbb{E}[y] = 10 \times 0.20 = 2.0\)), and typical counts sit in \([0, 5]\). If your real domain routinely sees 8–9 clicks out of 10, this 5-second simulation immediately warns you that \(\mathrm{Beta}(2,8)\) is far too pessimistic!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-reliable-statistical-simulations&quot;&gt;Explanation: Four Rules for Reliable Statistical Simulations&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always test your inference code on simulated data with known \(\theta_{\text{true}}\) first:&lt;/strong&gt; If your sampler cannot recover \(\theta_{\text{true}} = 0.65\) from 500 clean simulated coin flips, never trust it on messy real-world data!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check Monte Carlo error of your simulation itself:&lt;/strong&gt; Running only 50 repetitions has \(\mathrm{SE} \approx 7\%\) for a coverage rate; use \(1{,}000\text{–}10{,}000\) vectorized repetitions for crisp answers.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Simulate the &lt;em&gt;exact&lt;/em&gt; messy features of your real data:&lt;/strong&gt; Include missing values, rounding, outliers, or group clustering in your simulator to see whether your model breaks gracefully or catastrophically.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Set explicit random seeds (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;default_rng(123)&lt;/code&gt;):&lt;/strong&gt; Reproducible simulations make debugging effortless.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If you run 1,000 independent parameter-recovery simulations of a well-calibrated 95% credible interval (drawing \(\theta_{\text{true}}\) from the prior each time), roughly how many of the 1,000 intervals should contain \(\theta_{\text{true}}\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=7TqhmX92P6U&quot;&gt;What is Monte Carlo Simulation?&lt;/a&gt; — IBM Technology, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch Monte Carlo simulation as a way of stating an assumption and then generating data under that assumption, exactly the role the lesson assigns to simulation.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=MntX3zWNWec&quot;&gt;Law of Large Numbers - Explained and Visualized&lt;/a&gt; — Jeremy Blitz-Jones, English. Watch a theorem being checked with a simulated plot, supporting the part about using simulation to detect wrong intuition.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zeJD6dqJ5lo&quot;&gt;But what is the Central Limit Theorem?&lt;/a&gt; — 3Blue1Brown, English. Watch many samples generated to see the distribution of the mean, used as a template for the data-generating workflow in the lesson.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Name a probability concept that you often misunderstand and propose a simulation to check it.&lt;/li&gt;
  &lt;li&gt;Why is simulation a good bridge between math and code?&lt;/li&gt;
  &lt;li&gt;When a simulation gives a surprising result, what should you check first?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Downey, A. (2014). &lt;em&gt;Think Bayes&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;McElreath, R. (2020). &lt;em&gt;Statistical Rethinking&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter01/&quot;&gt;Chapter 1: Fundamentals of Bayesian Inference&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.20: Basic Model Assumption Checks</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_18_basic_model_assumption_checks/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_18_basic_model_assumption_checks</id>
   <content type="html">&lt;p&gt;Every statistical model—frequentist or Bayesian—makes quiet promises about the world: observations are independent, noise variance is roughly constant, residuals have no leftover curved pattern, and there are no extreme heavy-tailed outliers. Violate those promises without checking, and your beautifully converged 95% credible interval can actually have only 60% real coverage!&lt;/p&gt;

&lt;p&gt;This lesson builds a fast, practical &lt;strong&gt;model-assumption diagnostic toolkit&lt;/strong&gt;—residual plots, Q-Q normality checks, heteroscedasticity checks, and lag-1 autocorrelation checks—creating the direct bridge to &lt;strong&gt;Posterior Predictive Checks (PPC)&lt;/strong&gt; later in the course.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-four-diagnostics-that-catch-broken-models-early&quot;&gt;Key ideas: Four Diagnostics That Catch Broken Models Early&lt;/h2&gt;

&lt;p&gt;Before trusting any posterior or confidence interval, check four core assumptions:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Linearity &amp;amp; Structural Fit (Residuals vs. Fitted):&lt;/strong&gt; If residuals form a U-shape or wave against \(\hat{y}\), your model is missing a nonlinear term or interaction—parameter estimates are biased!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Constant Variance (Homoscedasticity):&lt;/strong&gt; If residuals fan out like a megaphone as \(\hat{y}\) grows, uncertainty is understated for large values and overstated for small ones—consider log-transforming \(y\) or modeling \(\sigma_i\) as a function of \(x_i\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Distributional Shape &amp;amp; Outliers (Q-Q Plot):&lt;/strong&gt; Heavy tails or single wild points pull Gaussian means off target; swapping a Normal likelihood for a &lt;strong&gt;Student-\(t\)&lt;/strong&gt; likelihood fixes this cleanly in Bayesian models.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Independence (Lag-1 Autocorrelation \(r_1\)):&lt;/strong&gt; Time-series or grouped measurements often correlate from one observation to the next (\(r_1 &amp;gt; 0.3\)), artificially inflating effective sample size unless modeled with AR terms or hierarchical group effects.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will know how to quickly but systematically check the core assumptions of a model (distribution shape, independence, error structure), recognize signs of model misspecification, and turn the check results into actions that improve the model.&lt;/p&gt;

&lt;h2 id=&quot;1-what-are-model-assumptions-and-where-do-they-live&quot;&gt;1) What are model assumptions and where do they live?&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Every statistical model implicitly says that the data is generated by some mechanism, that the noise has a certain structure, and that the relationship between the input variables and the output variable has a specific geometric or probabilistic form.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In practice, assumptions usually appear in 3 places. First is the &lt;strong&gt;likelihood&lt;/strong&gt;, i.e., which distribution family the data belongs to, such as Gaussian, Poisson or Binomial. Second is the &lt;strong&gt;mean structure&lt;/strong&gt;, i.e., whether the average relationship between \(x\) and \(y\) is linear, nonlinear, or has interactions. Third is the &lt;strong&gt;noise structure&lt;/strong&gt;, where we ask whether the variance is constant or changes with the predicted level, and whether the data are dependent over time or across groups.&lt;/p&gt;

&lt;h2 id=&quot;2-the-minimum-set-of-checks-to-run&quot;&gt;2) The minimum set of checks to run&lt;/h2&gt;

&lt;h3 id=&quot;21-checking-the-output-distribution&quot;&gt;2.1 Checking the output distribution&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Plot the histogram/density of \(y\).&lt;/li&gt;
  &lt;li&gt;Compare intuition with the chosen likelihood.&lt;/li&gt;
  &lt;li&gt;Ask yourself: is the data strongly skewed, does it have many zeros, does it have natural bounds (0-1)?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For example, count data with too many zeros is usually not suited to a Gaussian, while proportion data lying in \([0,1]\) requires a model that respects that range instead of predicting outside the valid interval.&lt;/p&gt;

&lt;h3 id=&quot;22-checking-residuals&quot;&gt;2.2 Checking residuals&lt;/h3&gt;

&lt;p&gt;Residuals are usually written:&lt;/p&gt;

\[e_i = y_i - \hat y_i\]

&lt;p&gt;Here, \(e_i\) is the &lt;strong&gt;residual&lt;/strong&gt; of observation \(i\), i.e., the gap between the actually observed value \(y_i\) and the model’s predicted value \(\hat y_i\). If \(e_i &amp;gt; 0\) the model is predicting lower than reality; if \(e_i &amp;lt; 0\) the model is predicting higher than reality.&lt;/p&gt;

&lt;p&gt;Do not confuse \(e_i\) with \(\epsilon_i\). In the data-generating model, we usually write \(y_i = \mu_i + \epsilon_i\), where \(\epsilon_i\) is the &lt;strong&gt;true but not directly observed error&lt;/strong&gt; of the data-generating process. Meanwhile \(e_i = y_i - \hat y_i\) is the &lt;strong&gt;residual computed after fitting the model&lt;/strong&gt;, so it is just the practical version used to check how the model deviates from the data. If the model is reasonable, the behavior of \(e_i\) can be close to that of \(\epsilon_i\), but they do not fully coincide because \(\hat y_i\) is a value estimated from the very same data.&lt;/p&gt;

&lt;p&gt;The basic expectation for a passably good model is that the residuals fluctuate around 0, do not create a clear trend in \(\hat y\) or in \(x\), and do not reveal structured shapes such as curves, funnels, or clusters separated by group.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_residual_check.png&quot; alt=&quot;Residual check to see trends in the residuals&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1a: A residual plot helps quickly see whether the residuals hug 0 or are revealing unusual structure.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;23-checking-outliers-and-highly-influential-points&quot;&gt;2.3 Checking outliers and highly influential points&lt;/h3&gt;

&lt;p&gt;Not every outlier is “bad”. They can be data errors, rare but valid cases, or a signal that the model is missing a variable or using the wrong likelihood.&lt;/p&gt;

&lt;p&gt;The important thing is to check sensitivity: if we remove/reweight a few points, does the conclusion change significantly?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_fit_outliers.png&quot; alt=&quot;Linear fit and points that may be outliers&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1b: Looking at the fitted line together with points far from the general trend helps detect outliers and highly influential points before updating the model.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;24-checking-the-independence-assumption&quot;&gt;2.4 Checking the independence assumption&lt;/h3&gt;

&lt;p&gt;The independence assumption is fragile in real data. We may encounter dependence over &lt;strong&gt;time&lt;/strong&gt; due to autocorrelation, across &lt;strong&gt;groups&lt;/strong&gt; such as students in the same class or patients in the same hospital, and over &lt;strong&gt;space&lt;/strong&gt; when nearby measurement points are usually more similar.&lt;/p&gt;

&lt;p&gt;If dependence is ignored, uncertainty intervals are usually judged too optimistically (too narrow).&lt;/p&gt;

&lt;h2 id=&quot;3-the-sign---action-map&quot;&gt;3) The “sign -&amp;gt; action” map&lt;/h2&gt;

&lt;p&gt;This is not a table of “if you see A you must definitely use B”. The right way is:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Look at the signs in the data or residuals.&lt;/li&gt;
  &lt;li&gt;Infer which model assumption is in doubt.&lt;/li&gt;
  &lt;li&gt;Choose the smallest but most on-target update to re-check.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You can read this map quickly with the pattern: &lt;strong&gt;sign -&amp;gt; what is suspected -&amp;gt; which direction to try fixing&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Curved residuals&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;This usually suggests the mean structure is wrong: the average relationship between inputs and output is no longer simply linear.&lt;/li&gt;
  &lt;li&gt;Action to try first: add nonlinear terms such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x^2&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(x)&lt;/code&gt;, splines, or add interaction variables if you suspect the effect of one variable depends on another.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Funnel-shaped residuals&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;This usually suggests non-constant variance, i.e., the noise level increases with the predicted value.&lt;/li&gt;
  &lt;li&gt;Action to try first: change the scale such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(y)&lt;/code&gt;, use a likelihood better suited to skewed data/increasing variance, or model the changing variance if the context requires it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;More extreme values than expected&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;This usually suggests the current likelihood is too “thin-tailed”, for example a Gaussian does not tolerate outliers well.&lt;/li&gt;
  &lt;li&gt;Action to try first: re-check for data errors, see whether an important variable is missing, then consider a heavy-tailed likelihood such as Student-t instead of Gaussian.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Count data with too many zeros or variance clearly larger than the mean&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;This usually suggests Poisson is too tight for the real data.&lt;/li&gt;
  &lt;li&gt;Action to try first: use Negative Binomial when there is overdispersion; if there are too many zeros due to a separate mechanism, consider adding a zero-inflated or hurdle model.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Data clustered by group or over time&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;This usually suggests the independence assumption among observations is no longer reasonable.&lt;/li&gt;
  &lt;li&gt;Action to try first: add hierarchical structure by group, random effects, or model the correlation over time/observation order.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In short: do not fix a model by its “hot” name, fix the assumption that is actually broken. Curved residuals are mainly a &lt;strong&gt;mean structure&lt;/strong&gt; problem. A funnel shape is a &lt;strong&gt;noise structure&lt;/strong&gt; problem. Too many zeros or heavy tails are usually a &lt;strong&gt;likelihood&lt;/strong&gt; problem. Dependence by group/time is an &lt;strong&gt;independence structure&lt;/strong&gt; problem.&lt;/p&gt;

&lt;h2 id=&quot;4-a-real-data-example-state-the-data-source-and-the-reasoning&quot;&gt;4) A real-data example: state the data source and the reasoning&lt;/h2&gt;

&lt;p&gt;To avoid “gut-feeling commentary”, this section uses public data that can be reproduced directly in Python (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seaborn.load_dataset&lt;/code&gt;). Each example follows the same chain of reasoning:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;State clearly the data and the question you want to answer.&lt;/li&gt;
  &lt;li&gt;Choose a simple baseline so you know exactly what you are assuming.&lt;/li&gt;
  &lt;li&gt;Use descriptive numbers or residuals to check whether that assumption is reasonable.&lt;/li&gt;
  &lt;li&gt;Only after seeing signs of misspecification do we propose an update.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;example-1-the-diamonds-data-diamond-prices&quot;&gt;Example 1: The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;diamonds&lt;/code&gt; data (diamond prices)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Data source&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seaborn.load_dataset(&quot;diamonds&quot;)&lt;/code&gt;, \(n=53{,}940\) observations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Question&lt;/strong&gt;: if we start with just a simple predictor, the weight &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;, which model can describe the price &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; passably, and which assumptions are most likely to break?&lt;/p&gt;

&lt;p&gt;This example is useful because it shows a very common problem in real data: a positive, right-skewed output variable whose variability grows as the mean increases. If we directly fit a linear Gaussian model on the original price scale, we usually run into problems in both the &lt;strong&gt;mean structure&lt;/strong&gt; and the &lt;strong&gt;noise structure&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A small slice of the data to visualize&lt;/strong&gt;: the table below is not synthetic data, but 7 real observations taken from different points of the price distribution after sorting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; in increasing order. The aim is to help you quickly see that as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt; increases &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; usually increases sharply, but the price still depends on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cut&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;color&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clarity&lt;/code&gt;.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Point in the price distribution&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;carat&lt;/th&gt;
      &lt;th&gt;cut&lt;/th&gt;
      &lt;th&gt;color&lt;/th&gt;
      &lt;th&gt;clarity&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;price (USD)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;0%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.23&lt;/td&gt;
      &lt;td&gt;Ideal&lt;/td&gt;
      &lt;td&gt;E&lt;/td&gt;
      &lt;td&gt;SI2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;326&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;10%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.31&lt;/td&gt;
      &lt;td&gt;Ideal&lt;/td&gt;
      &lt;td&gt;H&lt;/td&gt;
      &lt;td&gt;VS2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;646&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;30%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.42&lt;/td&gt;
      &lt;td&gt;Premium&lt;/td&gt;
      &lt;td&gt;H&lt;/td&gt;
      &lt;td&gt;VS1&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1087&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;50%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.58&lt;/td&gt;
      &lt;td&gt;Ideal&lt;/td&gt;
      &lt;td&gt;F&lt;/td&gt;
      &lt;td&gt;VVS2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2401&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;70%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1.02&lt;/td&gt;
      &lt;td&gt;Ideal&lt;/td&gt;
      &lt;td&gt;I&lt;/td&gt;
      &lt;td&gt;VS2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4662&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;90%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1.51&lt;/td&gt;
      &lt;td&gt;Very Good&lt;/td&gt;
      &lt;td&gt;H&lt;/td&gt;
      &lt;td&gt;VS2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;9821&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;98%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2.43&lt;/td&gt;
      &lt;td&gt;Very Good&lt;/td&gt;
      &lt;td&gt;H&lt;/td&gt;
      &lt;td&gt;SI2&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;16170&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Step 1 - Check the output distribution&lt;/strong&gt;: before fitting a model, we ask a very basic question: does &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; on the original scale look like a near-Gaussian variable?&lt;/p&gt;

&lt;p&gt;On the real data, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; has &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;min=326&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;median=2401&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max=18823&lt;/code&gt;, right skewness &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;skewness = 1.618&lt;/code&gt;, and the 95% quantile threshold is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;13107.1&lt;/code&gt;, i.e., exactly 5% of observations lie above this price level.&lt;/p&gt;

&lt;p&gt;Those numbers should be read as follows:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;median=2401&lt;/code&gt; but &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max=18823&lt;/code&gt; shows the high-price side extends very far from the central region.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;skewness = 1.618&lt;/code&gt; is a quantitative sign that the distribution is clearly right-skewed, not just “looks skewed”.&lt;/li&gt;
  &lt;li&gt;The 95% mark at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;13107.1&lt;/code&gt; reminds us that only a small portion of observations lie in the high tail, but exactly this small portion can strongly affect the fit if we use an unsuitable model.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;price&lt;/code&gt; were truly near-Gaussian on the original scale, we would expect the histogram to be fairly symmetric around a central region and the two tails not too different. The real data does not have that shape. Already at this step we have reason to suspect that a Gaussian baseline on the original price scale will struggle.&lt;/p&gt;

&lt;h3 id=&quot;a-very-concrete-practical-decision-from-these-numbers&quot;&gt;A very concrete practical decision from these numbers&lt;/h3&gt;

&lt;p&gt;With &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;min=326&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;median=2401&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max=18823&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;skewness=1.618&lt;/code&gt;, a reasonable response is to try modeling on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(price)&lt;/code&gt; scale before jumping to more complex models. The reason is not that the log is always “right”, but that this transformation usually compresses the right tail and makes the variance more stable, giving us a more reasonable baseline to check further.&lt;/p&gt;

&lt;p&gt;In short: the descriptive numbers in the first step are not just for “casual comment”. They must lead to a concrete modeling action.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_assumption_diamonds_distribution.png&quot; alt=&quot;Diamonds price distribution&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates the diamonds price distribution. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;
&lt;em&gt;Figure 2: Histogram of diamond prices (diamonds) with the q95 line, showing a right-skewed distribution and a high tail.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2 - Fit the baseline and check residuals&lt;/strong&gt;: to check specifically which assumption is breaking, we should still fit a simple baseline. The goal here is not to find the “final model”, but to create a clear reference point for diagnosis.&lt;/p&gt;

&lt;p&gt;Baseline model:&lt;/p&gt;

\[y_i \sim \mathcal{N}(\mu_i, \sigma), \quad \mu_i = \alpha + \beta\,\text{carat}_i\]

&lt;p&gt;If written in the familiar error form, we can understand it equivalently as \(y_i = \mu_i + \epsilon_i\) with \(\epsilon_i \sim \mathcal{N}(0,\sigma)\). This model implicitly assumes two big things:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;The mean price increases &lt;strong&gt;linearly&lt;/strong&gt; with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;The level of fluctuation around the mean line has an almost &lt;strong&gt;constant&lt;/strong&gt; width over the whole prediction range.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;After fitting the model, what we take to the plot to check is not \(\epsilon_i\) because it cannot be observed, but the residual \(e_i = y_i - \hat y_i\).&lt;/p&gt;

&lt;p&gt;Quantitative diagnostics on the residuals show:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\mathrm{corr}(\lvert e_i \rvert, \hat y_i)=0.579\) is strong and positive, meaning the larger the fitted value, the more the residual magnitude tends to increase.&lt;/li&gt;
  &lt;li&gt;The MAE of the low and high fitted groups is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;478.4&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2059.1&lt;/code&gt; respectively, a difference of as much as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4.30&lt;/code&gt; times.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is a very important result. If the problem were just a few scattered outliers, we might see a few extreme points but not necessarily see the width of the residuals increase systematically. In contrast, the two numbers above show that the increase in dispersion is &lt;strong&gt;structured&lt;/strong&gt;: the higher the model’s prediction, the larger the absolute error. In other words, the &lt;strong&gt;homoscedasticity&lt;/strong&gt; assumption is clearly broken.&lt;/p&gt;

&lt;p&gt;This observation also fits business intuition: a difference of 500 USD can be large for a stone priced at 700 USD, but not so large for a stone priced at 10,000 USD. On the original price scale, noise is usually “proportional” rather than “adding a fixed amount”.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_assumption_diamonds_residuals.png&quot; alt=&quot;Diamonds residual vs fitted&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates the diamonds residual vs fitted. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;
&lt;em&gt;Figure 3: Residual vs fitted of the baseline model on diamonds; the residual dispersion widens as fitted increases (a sign of heteroscedasticity).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3 - Update the model and re-check&lt;/strong&gt;: a good update is not a “more complex” update, but one that fixes exactly the error just observed.&lt;/p&gt;

&lt;p&gt;Updated model (more stable):&lt;/p&gt;

\[\log y_i = \alpha + \beta_1\,\text{carat}_i + \beta_2\,\text{carat}_i^2 + \epsilon_i,\]

&lt;p&gt;with \(\epsilon_i\) now viewable as closer to Gaussian on the log scale.&lt;/p&gt;

&lt;p&gt;Why is this update reasonable?&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Taking &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(y)&lt;/code&gt; makes a positive, right-skewed output “tamer”, and also turns proportional differences into additive differences that are easier to model.&lt;/li&gt;
  &lt;li&gt;Adding &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;carat^2&lt;/code&gt; lets the relationship between weight and price have curvature, instead of forcing everything into a straight line.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After updating the model, \(\mathrm{corr}(\lvert e_i \rvert, \hat y_i)\) falls from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.579&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.047&lt;/code&gt;, and the high/low MAE ratio falls from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4.30&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.16&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;These two changes have very clear practical meaning:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;A correlation near 0 shows the residuals no longer visibly balloon as fitted increases.&lt;/li&gt;
  &lt;li&gt;An MAE ratio near 1 shows the errors in the low-price and high-price regions are much more balanced.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The conclusion of this example is not “the log-quadratic model is surely right”, but: the assumption check pointed very specifically to where the baseline is wrong, and the chosen update fixed exactly those broken points using the same diagnostic criteria.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;example-2-the-taxis-data-trip-counts-by-zone-day&quot;&gt;Example 2: The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;taxis&lt;/code&gt; data (trip counts by zone-day)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Data source&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seaborn.load_dataset(&quot;taxis&quot;)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Question&lt;/strong&gt;: if we aggregate the data into the number of trips per &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pickup_zone&lt;/code&gt; and per day, is Poisson a reasonable baseline for the count variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trips&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;This example is useful because it is a very common kind of count problem. With count data, the core assumption lies more in the &lt;strong&gt;likelihood&lt;/strong&gt; than in Gaussian residuals. So we prioritize checking what Poisson implicitly says about the data, then compare directly with reality.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to create the count variable&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Keep the trips with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pickup_borough = Manhattan&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Group by the pair &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(pickup_zone, day)&lt;/code&gt; to create the count variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trips&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Fill in every zone-day combination to preserve the days with 0 trips.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;After aggregation, there are \(n=1953\) zone-day observation cells. Each cell is now a non-negative count: some zone-days have no trips at all, some have very few trips, and some surge quite strongly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1 - Check the basic Poisson assumption&lt;/strong&gt;: with a Poisson baseline, if \(Y \sim \mathrm{Poisson}(\lambda)\) then a very important consequence is:&lt;/p&gt;

\[\mathbb{E}[Y] = \mathrm{Var}(Y).\]

&lt;p&gt;On the real data, we have &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean(trips)=2.697&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var(trips)=7.441&lt;/code&gt;, so the ratio &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var/mean = 2.76&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The number &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2.76&lt;/code&gt; should be read as follows: the actual dispersion is almost 3 times larger than what Poisson expects at the same mean of 2.697. This is not a small deviation due to chance, but a clear sign of &lt;strong&gt;overdispersion&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Intuitive interpretation: if every zone-day had almost the same trip-generation intensity, Poisson could be reasonable. But real data usually has strong heterogeneity between busy zones and quiet zones, between calm days and busy days. That heterogeneity makes the variance balloon faster than Poisson allows.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_assumption_taxis_distribution.png&quot; alt=&quot;Taxis trip-count distribution&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates the taxis trip-count distribution. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;
&lt;em&gt;Figure 4: Distribution of the number of trips per zone-day in taxis, with the mean, variance, and var/mean statistics to identify overdispersion.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2 - Check the zero part and the right tail&lt;/strong&gt;: a big advantage of Poisson is that once the mean \(\lambda\) is known, it determines not only the mean but also the probability of days with 0 trips and of very busy days. So if Poisson is wrong on these probabilities, we know right away that the likelihood is not flexible enough.&lt;/p&gt;

&lt;p&gt;The observed zero rate is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;P(Y=0)=0.245&lt;/code&gt;, while Poisson with \(\lambda=2.697\) predicts only &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;P(Y=0)=e^{-\lambda}=0.067&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In other words, the data has about &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.245 / 0.067 \approx 3.7&lt;/code&gt; times as many zero zone-days as the Poisson prediction.&lt;/p&gt;

&lt;p&gt;In the right tail, the observed probability is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;P(Y&amp;gt;=10)=0.0261&lt;/code&gt;, while Poisson predicts only &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;P(Y&amp;gt;=10)=0.00050&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Here the difference is even stronger: the probability of a very busy zone-day in the data is about &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;52&lt;/code&gt; times larger than under Poisson.&lt;/p&gt;

&lt;p&gt;This is a very notable point. The data simultaneously has:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;too many quiet zone-days,&lt;/li&gt;
  &lt;li&gt;and also too many busy zone-days.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A Poisson with a single fixed mean parameter does not do well at both ends at once. It is too “narrow”: when trying to fit the mean, it will fall short on both zeros and the tail.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/basic_model_assumption_taxis_probabilities.png&quot; alt=&quot;Observed vs model implied probabilities on taxis&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates observed vs model implied probabilities on taxis. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;
&lt;em&gt;Figure 5: Comparison of observed probabilities with the probabilities implied by Poisson and Negative Binomial for two target statistics: \(P(Y=0)\) and \(P(Y\ge 10)\).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3 - Update and re-check&lt;/strong&gt;: when count data has overdispersion, Negative Binomial is a very natural update because it allows the variance to be larger than the mean.&lt;/p&gt;

&lt;p&gt;Estimating the Negative Binomial by moment matching with dispersion parameter \(k=1.534\) gives the prediction &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;P(Y=0)=0.211&lt;/code&gt;, much closer to the observed 0.245, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;P(Y&amp;gt;=10)=0.0279&lt;/code&gt;, very close to the data’s 0.0261.&lt;/p&gt;

&lt;p&gt;The intuitive interpretation of the Negative Binomial is: instead of assuming every zone-day has the same fixed trip-generation intensity, we allow that intensity to vary more across different circumstances. This latent variability is what gives the count distribution a heavier tail and more zeros.&lt;/p&gt;

&lt;p&gt;The important thing here is that we do not choose Negative Binomial because “it is a commonly used model”, but because it fixes exactly where Poisson fails:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;variance larger than the mean,&lt;/li&gt;
  &lt;li&gt;more zeros than predicted,&lt;/li&gt;
  &lt;li&gt;and a heavier right tail than predicted.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The conclusion of this example is: assumption checking with descriptive statistics alone is enough to show that the Poisson baseline is unsuitable, and Negative Binomial is an update with a clear data basis.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;takeaways-from-the-two-examples&quot;&gt;Takeaways from the two examples&lt;/h3&gt;

&lt;p&gt;The two examples above emphasize four very important practical lessons:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Do not start with a complex model; start with a baseline simple enough that you know what you are assuming.&lt;/li&gt;
  &lt;li&gt;Do not conclude by eyeballing; tie each remark to a concrete number such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;skewness&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var/mean&lt;/code&gt;, the correlation of residuals, or the zero and tail probabilities.&lt;/li&gt;
  &lt;li&gt;Do not update the model on a whim; fix exactly the assumption that is broken: for example log-transform and add curvature when wrong in scale/mean structure, or switch to Negative Binomial when wrong in the count likelihood.&lt;/li&gt;
  &lt;li&gt;Do not just say the new model “looks better”; reuse the same old diagnostic metrics to check whether the new model has truly improved.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;5-a-15-minute-routine-before-trusting-results&quot;&gt;5) A 15-minute routine before trusting results&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Look at the distribution of the target variable.&lt;/li&gt;
  &lt;li&gt;Fit a simple model as a baseline.&lt;/li&gt;
  &lt;li&gt;Plot residual vs fitted and residual vs the main predictor.&lt;/li&gt;
  &lt;li&gt;Look for highly influential points and check the sensitivity of conclusions.&lt;/li&gt;
  &lt;li&gt;Check signs of dependence over time/group.&lt;/li&gt;
  &lt;li&gt;Note the 1-2 assumptions at highest risk.&lt;/li&gt;
  &lt;li&gt;Update the model and compare again.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The goal is to reduce the risk of wrong inference, not to make every possible plot.&lt;/p&gt;

&lt;h2 id=&quot;6-model-misspecification-is-not-a-failure-but-an-update-signal&quot;&gt;6) Model misspecification is not a failure, but an update signal&lt;/h2&gt;

&lt;p&gt;In Bayesian workflow thinking:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Propose a model,&lt;/li&gt;
  &lt;li&gt;Fit the model,&lt;/li&gt;
  &lt;li&gt;Check the predictive consequences and assumptions,&lt;/li&gt;
  &lt;li&gt;Improve the model.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The goal is not to “prove the model right”, but to make the model fit the data and the real question better.&lt;/p&gt;

&lt;h2 id=&quot;quick-summary&quot;&gt;Quick summary&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;A model always comes with assumptions.&lt;/li&gt;
  &lt;li&gt;Wrong assumptions can make conclusions wrong.&lt;/li&gt;
  &lt;li&gt;The minimum set of checks includes: distribution, residuals, outliers/influence, dependence.&lt;/li&gt;
  &lt;li&gt;Signs of misspecification must lead to action adjusting the likelihood/model structure.&lt;/li&gt;
  &lt;li&gt;Misspecification is information for improving the model, not a “failure”.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-detecting-hidden-autocorrelation-in-a-6-point-residual-sequence&quot;&gt;Worked Numerical Example: Detecting Hidden Autocorrelation in a 6-Point Residual Sequence&lt;/h3&gt;

&lt;p&gt;Suppose a regression model fits a 6-day time series and leaves residuals:&lt;/p&gt;

\[e = [+2,\; +1,\; +1,\; -1,\; -1,\; -2].\]

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Check mean and symmetry:&lt;/strong&gt; \(\bar{e} = 0\) and values look nicely balanced—a histogram alone looks totally fine!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the lag-1 autocorrelation \(r_1\) by hand&lt;/strong&gt; across the 5 consecutive pairs \((e_t, e_{t+1})\):
    &lt;ul&gt;
      &lt;li&gt;Pairs: \((2,1),\; (1,1),\; (1,-1),\; (-1,-1),\; (-1,-2)\).&lt;/li&gt;
      &lt;li&gt;Numerator \(\sum_{t=1}^5 e_t e_{t+1} = 2 + 1 - 1 + 1 + 2 = \mathbf{+5}\).&lt;/li&gt;
      &lt;li&gt;Denominator \(\sum_{t=1}^6 e_t^2 = 4 + 1 + 1 + 1 + 1 + 4 = \mathbf{12}\).&lt;/li&gt;
      &lt;li&gt;\(r_1 \approx \frac{5}{12} \approx \mathbf{+0.417}\)!
Because positive residuals stick together on days 1–3 and negative residuals stick together on days 4–6, the errors are &lt;strong&gt;not independent&lt;/strong&gt;—an i.i.d. model will underestimate parameter uncertainty!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-model-diagnostics-without-overreacting&quot;&gt;Explanation: Four Rules for Model Diagnostics Without Overreacting&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Prioritize &lt;em&gt;independence&lt;/em&gt; and &lt;em&gt;functional form&lt;/em&gt; above exact Gaussianity:&lt;/strong&gt; Mild non-normality rarely ruins inferences on means at moderate \(n\), whereas unmodeled dependence or missing nonlinearity wrecks everything!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always plot residuals against &lt;em&gt;time order&lt;/em&gt; and &lt;em&gt;group ID&lt;/em&gt;, not just \(\hat{y}\):&lt;/strong&gt; Drift over time or clustering by user/store shows up instantly on an index plot.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Don’t rely blindly on formal normality tests (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Shapiro–Wilk&lt;/code&gt;):&lt;/strong&gt; At \(n = 5{,}000\), Shapiro–Wilk rejects harmless microscopic deviations from Normality; at \(n = 10\), it misses huge skewness! Visual Q-Q plots + PPC beat p-value tests.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;When an assumption fails, upgrade the generative model rather than deleting data:&lt;/strong&gt; Heteroscedastic? Model \(\log\sigma_i\). Outliers? Use Student-\(t\). Grouped? Add a hierarchical random intercept!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If a residual plot against fitted values \(\hat{y}\) looks like a widening funnel (small scatter on the left, huge scatter on the right), which assumption is violated—and what simple transformation of positive \(y\) often stabilizes it?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=okjYjClSjOg&quot;&gt;Quantile-Quantile Plots (QQ plots), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the Q–Q plot as a way to compare the distribution of the residuals with the assumed distribution, exactly the distribution-shape check.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=iMdtTCX2Q70&quot;&gt;Simple Linear Regression:  Checking Assumptions with Residual Plots&lt;/a&gt; — jbstatistics, English. Watch the kinds of residual plots and the assumptions they check, supporting the error structure part.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ADICTMUvPg0&quot;&gt;Lecture37 (Data2Decision) Independence of Residuals&lt;/a&gt; — Chris Mack, English. Watch the independence assumption of residuals and the signs of its violation, used for the independence section of the lesson.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Name a situation where the independence assumption is violated in real data and propose how to fix the model.&lt;/li&gt;
  &lt;li&gt;Why does checking residual vs fitted help detect a wrong mean function form?&lt;/li&gt;
  &lt;li&gt;If there is a strong outlier, how would you distinguish a “data error” from a “real signal”?&lt;/li&gt;
  &lt;li&gt;Pick a problem you have worked on and list the 2 highest-risk assumptions of that model.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;McElreath, R. (2020). &lt;em&gt;Statistical Rethinking&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_19_simulation_for_statistical_intuition/&quot;&gt;0.21 Simulation to Test Statistical Intuition&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.19: Log-probability and Numerical Stability</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_17_log_probability_numerical_stability/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_17_log_probability_numerical_stability</id>
   <content type="html">&lt;p&gt;Try multiplying 400 probabilities of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.1&lt;/code&gt; together in Python (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.1 ** 400&lt;/code&gt;). Instead of a tiny positive number, IEEE 754 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; silently rounds the answer to &lt;strong&gt;exact &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt;&lt;/strong&gt; (&lt;em&gt;numerical underflow&lt;/em&gt;)! Now try dividing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0 / 0.0&lt;/code&gt; in Bayes’ rule, and your entire inference pipeline crashes with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;! That is why &lt;strong&gt;no serious Bayesian library ever multiplies raw probabilities&lt;/strong&gt;—everything runs in &lt;strong&gt;log-probability space&lt;/strong&gt; using the &lt;strong&gt;Log-Sum-Exp trick&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This lesson equips you with the exact floating-point survival kit used inside Stan, PyMC, and every deep-learning framework: turning products into log-sums, computing log-normalizers safely with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;logsumexp&lt;/code&gt;, and checking gradients without overflow or underflow.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-floating-point-arithmetic-inside-bayesian-samplers&quot;&gt;Key ideas: Floating-Point Arithmetic Inside Bayesian Samplers&lt;/h2&gt;

&lt;p&gt;Four numerical-computing rules keep Bayesian software from ever returning &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0 / 0.0 = NaN&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;IEEE 754 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; Dynamic Range:&lt;/strong&gt; Positive &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; numbers span roughly \(10^{-308}\) to \(10^{+308}\). Multiplying even 500 typical likelihood densities (each \(\sim 0.1\)) immediately underflows below \(10^{-308}\) to exact zero!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Log-Space Turns Products Into Sums:&lt;/strong&gt; \(\log\prod_{i=1}^n p(y_i\mid\theta) = \sum_{i=1}^n \log p(y_i\mid\theta)\). Even for \(n = 1{,}000{,}000\) data points, the sum sits comfortably around \(-2.3\times 10^6\)—nowhere near underflow!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Log-Sum-Exp (LSE) Trick:&lt;/strong&gt; To normalize log-weights \(\ell_1,\dots,\ell_M\) without &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;exp(-1000) == 0.0&lt;/code&gt;, subtract \(m = \max_j \ell_j\) first:
\(\ln\sum_{j=1}^M e^{\ell_j} = m + \ln\sum_{j=1}^M e^{\ell_j - m}.\)
Since every shifted exponent \(\ell_j - m \le 0\) and at least one equals \(0\) (\(e^0 = 1\)), overflow is impossible and total underflow is impossible!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Log-Ratio Acceptance in MCMC:&lt;/strong&gt; Metropolis–Hastings computes \(\log \alpha = \log p(\theta^*) - \log p(\theta)\) directly in log space and compares against \(\log u\) (\(u \sim \mathrm{Uniform}(0,1)\))—never exponentiating giant log-posteriors!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will understand why Bayesian practice almost always works on the log scale, recognize underflow, overflow, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt; in probability computations, know how to write log-likelihoods and log-posteriors correctly, and master the log-sum-exp technique for safely normalizing posterior weights.&lt;/p&gt;

&lt;h2 id=&quot;introduction-being-mathematically-correct-is-not-enough-it-must-also-be-stable-on-a-machine&quot;&gt;Introduction: being mathematically correct is not enough, it must also be stable on a machine&lt;/h2&gt;

&lt;p&gt;Many probability formulas are perfectly correct on paper but fail when put into a computer. The reason is not in the statistics, but in the fact that computers can only store numbers with finite precision. In Bayesian computation, likelihoods and posteriors often contain products of very many numbers smaller than 1; if computed directly, they are easily rounded to 0. In the opposite direction, some exponentials can blow up to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt;. Then the theoretical model is still right but the algorithm has broken.&lt;/p&gt;

&lt;p&gt;So log-probability is not just a programming trick. It is the standard way to turn a probability model into a stable computation that can be optimized, normalized, and sampled reliably.&lt;/p&gt;

&lt;h2 id=&quot;1-where-is-the-real-problem&quot;&gt;1) Where is the real problem?&lt;/h2&gt;

&lt;p&gt;Computers do not store real numbers with infinite precision. With the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; type, only a finite range of values can be represented. In probability models, this becomes a problem as soon as we deal with:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Products of very many probabilities smaller than 1.&lt;/li&gt;
  &lt;li&gt;Exponentials of numbers with very large magnitude.&lt;/li&gt;
  &lt;li&gt;Normalizations that require dividing extremely small numbers by the sum of other extremely small numbers.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A very simple example:&lt;/p&gt;

\[10^{-3}\times 10^{-3}\times \cdots \times 10^{-3}\quad \text{(1000 times)} = 10^{-3000}\]

&lt;p&gt;This number is perfectly valid mathematically, but on a computer it is almost certainly rounded to 0. Then we no longer know how small the true value is; we only know it has “fallen out of the representable range”.&lt;/p&gt;

&lt;h2 id=&quot;2-what-is-log-probability-and-why-does-it-save-the-day&quot;&gt;2) What is log-probability and why does it save the day?&lt;/h2&gt;

&lt;p&gt;If \(p&amp;gt;0\), we can work with \(\log p\) instead of \(p\). In statistics, the default here is the natural log.&lt;/p&gt;

&lt;p&gt;The most important point is:&lt;/p&gt;

\[\log\left(\prod_{i=1}^n p(x_i\mid\theta)\right)=\sum_{i=1}^n \log p(x_i\mid\theta)\]

&lt;p&gt;That is, the log turns products into sums. This is the core reason the log domain is more stable.&lt;/p&gt;

&lt;p&gt;In practice, working on the log scale has three big benefits:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;It avoids underflow from multiplying too many small numbers.&lt;/li&gt;
  &lt;li&gt;It turns products into sums, making them easier to optimize and easier to check.&lt;/li&gt;
  &lt;li&gt;It combines the prior with the likelihood very naturally in Bayes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A small note on language: for continuous variables, more precisely we are working with the &lt;strong&gt;log-density&lt;/strong&gt; and not the probability at a point. In Bayesian practice, however, people usually call it &lt;strong&gt;log-probability&lt;/strong&gt; for short.&lt;/p&gt;

&lt;h3 id=&quot;21-a-familiar-formula-when-moving-to-the-log-scale&quot;&gt;2.1) A familiar formula when moving to the log scale&lt;/h3&gt;

&lt;p&gt;For the Binomial model:&lt;/p&gt;

\[p(k\mid n,\theta)=\binom{n}{k}\theta^k(1-\theta)^{n-k}\]

&lt;p&gt;taking the log gives us:&lt;/p&gt;

\[\log p(k\mid n,\theta)=\log\binom{n}{k}+k\log\theta+(n-k)\log(1-\theta)\]

&lt;p&gt;Instead of multiplying very small numbers like \(\theta^k\) and \((1-\theta)^{n-k}\), we just add the corresponding log-terms.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/log_probability_direct_product.png&quot; alt=&quot;Directly multiplying many small probabilities easily causes underflow&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1a: Computing directly on the probability scale makes the product of many small numbers quickly hit 0 on a computer.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;22-maximizing-the-likelihood-does-not-change-when-taking-the-log&quot;&gt;2.2) Maximizing the likelihood does not change when taking the log&lt;/h3&gt;

&lt;p&gt;Since the log function is monotonically increasing, we have:&lt;/p&gt;

\[\arg\max_\theta L(\theta)=\arg\max_\theta \log L(\theta)\]

&lt;p&gt;This means: if our goal is to find the MLE or MAP, we can optimize on the log scale without changing the optimal solution.&lt;/p&gt;

&lt;h2 id=&quot;3-a-very-concrete-numerical-example-mathematically-right-but-numerically-wrong&quot;&gt;3) A very concrete numerical example: mathematically right but numerically wrong&lt;/h2&gt;

&lt;p&gt;Suppose we have 1000 independent observations, and for some parameter value, each observation contributes a probability of about 0.01. Then:&lt;/p&gt;

\[L = 0.01^{1000} = 10^{-2000}\]

&lt;p&gt;On paper, this is a positive number. But on a computer, this value usually becomes:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;That is, &lt;strong&gt;underflow&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Meanwhile, the log-likelihood is still perfectly useful:&lt;/p&gt;

\[\log L = 1000\log(0.01)\approx -4605.17\]

&lt;p&gt;This is a large negative number, but still finite and still comparable.&lt;/p&gt;

&lt;p&gt;The important point is: Bayesian algorithms usually do not need to know the absolute probability. They only need to know which value is &lt;strong&gt;relatively larger&lt;/strong&gt;. If two parameters give:&lt;/p&gt;

\[\log L_1=-4605,\qquad \log L_2=-4700\]

&lt;p&gt;then we immediately know \(L_1 &amp;gt; L_2\), even though if we exponentiate both on a computer they might both become 0.&lt;/p&gt;

&lt;h2 id=&quot;4-underflow-overflow--inf-and-nan&quot;&gt;4) Underflow, overflow, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;These are four signals you will meet very often when coding probability models:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Underflow&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A positive number that is too small gets rounded to 0.&lt;/p&gt;

&lt;p&gt;A typical example is the product of very many small likelihood terms, or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.exp(-1000)&lt;/code&gt; being almost 0 on a machine.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overflow&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A number that is too large exceeds what the machine can represent and becomes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A typical example is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.exp(1000)&lt;/code&gt;, which exceeds the storage capacity of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Usually appears when taking \(\log(0)\). In probability models, this is sometimes legitimate: if the model assigns probability 0 to the observed data, then the log-probability of that state really is \(-\infty\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Appears when the computation has lost numerical meaning, for example &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0/0&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf - inf&lt;/code&gt;, or normalizing a weight vector in which all entries have underflowed to 0.&lt;/p&gt;

&lt;p&gt;So the log domain does not make everything “absolutely safe”. It only pushes the risk much lower. You still have to check for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt; in the pipeline.&lt;/p&gt;

&lt;h2 id=&quot;5-in-bayes-we-almost-always-work-with-the-log-posterior&quot;&gt;5) In Bayes, we almost always work with the log-posterior&lt;/h2&gt;

&lt;p&gt;Bayes’ formula written in terms of probabilities is:&lt;/p&gt;

\[p(\theta\mid x)=\frac{p(x\mid\theta)p(\theta)}{p(x)}\]

&lt;p&gt;Taking the log:&lt;/p&gt;

\[\log p(\theta\mid x)=\log p(x\mid\theta)+\log p(\theta)-\log p(x)\]

&lt;p&gt;Or more compactly:&lt;/p&gt;

\[\log p(\theta\mid x)=\log p(x\mid\theta)+\log p(\theta)+C\]

&lt;p&gt;where \(C\) is a constant not depending on \(\theta\).&lt;/p&gt;

&lt;p&gt;This is extremely important because:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;To compare two parameter values, we do not need to fully normalize the posterior.&lt;/li&gt;
  &lt;li&gt;MAP only needs to maximize the unnormalized log-posterior.&lt;/li&gt;
  &lt;li&gt;Many MCMC, HMC, NUTS, and variational inference algorithms all operate on the joint log-probability.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In other words: in modern Bayesian practice, what the library internally actually computes is usually the &lt;strong&gt;log-likelihood&lt;/strong&gt; or the &lt;strong&gt;unnormalized log-posterior&lt;/strong&gt;, not the posterior on the ordinary probability scale.&lt;/p&gt;

&lt;h2 id=&quot;6-when-are-we-forced-to-return-to-the-probability-scale&quot;&gt;6) When are we forced to return to the probability scale?&lt;/h2&gt;

&lt;p&gt;We cannot always stay on the log scale. We often have to return to the probability scale when we:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Need to normalize weights so they sum to 1.&lt;/li&gt;
  &lt;li&gt;Need to compute a posterior on a grid (grid approximation).&lt;/li&gt;
  &lt;li&gt;Need to convert log-weights into sampling probabilities.&lt;/li&gt;
  &lt;li&gt;Need to compute softmax in machine learning or Bayesian classification.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The problem is that if the log-weights are very negative, the direct computation&lt;/p&gt;

\[e^{a_i}\]

&lt;p&gt;can underflow to 0 for every \(i\). Then the subsequent normalization step becomes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0/0&lt;/code&gt;, producing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;7-log-sum-exp-a-normalization-technique-you-must-know&quot;&gt;7) Log-sum-exp: a normalization technique you must know&lt;/h2&gt;

&lt;p&gt;When we need to compute:&lt;/p&gt;

\[\log\sum_i e^{a_i}\]

&lt;p&gt;we should not compute it directly. The stable formula is:&lt;/p&gt;

\[\log\sum_i e^{a_i}=m+\log\sum_i e^{a_i-m},\qquad m=\max_i a_i\]

&lt;p&gt;The idea is very simple: pull \(e^m\) out of the sum. Since every \(a_i-m\le 0\), the new exponents no longer explode.&lt;/p&gt;

&lt;h3 id=&quot;71-why-does-subtracting-max-make-sense&quot;&gt;7.1) Why does subtracting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt; make sense?&lt;/h3&gt;

&lt;p&gt;When normalizing weights, what we need is the &lt;strong&gt;relative ratios&lt;/strong&gt; among values. For any constant \(c\):&lt;/p&gt;

\[\frac{e^{a_i}}{\sum_j e^{a_j}}
=
\frac{e^{a_i-c}}{\sum_j e^{a_j-c}}\]

&lt;p&gt;That is, we can subtract the same constant from all log-weights without changing the final probabilities. Choosing \(c=\max_j a_j\) is the safest choice.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/log_probability_log_sum.png&quot; alt=&quot;Addition on the log scale is more stable with log-sum-exp&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1b: Log-sum-exp keeps the addition of probabilities stable by pulling all exponents to around the largest value.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;72-a-small-but-very-important-example&quot;&gt;7.2) A small but very important example&lt;/h3&gt;

&lt;p&gt;Suppose the three log-weights are:&lt;/p&gt;

\[a=(-1000,\,-1001,\,-1005)\]

&lt;p&gt;If computed directly:&lt;/p&gt;

\[e^{-1000},\ e^{-1001},\ e^{-1005}\]

&lt;p&gt;then on a computer all three may become 0.&lt;/p&gt;

&lt;p&gt;But if we subtract the max, we get:&lt;/p&gt;

\[a-\max(a)=(0,\,-1,\,-5)\]

&lt;p&gt;Then:&lt;/p&gt;

\[(e^0,\ e^{-1},\ e^{-5}) \approx (1,\ 0.3679,\ 0.0067)\]

&lt;p&gt;and after normalization, the weights are approximately:&lt;/p&gt;

\[(0.727,\ 0.268,\ 0.005)\]

&lt;p&gt;That is, the probability information is actually still intact; only the direct computation has lost it.&lt;/p&gt;

&lt;h2 id=&quot;8-a-short-python-example&quot;&gt;8) A short Python example&lt;/h2&gt;

&lt;p&gt;The following code illustrates two very typical errors: underflow when multiplying likelihoods directly and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt; errors when normalizing log-weights the wrong way.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example 1: multiplying probabilities directly
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;likelihood&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;log_likelihood&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# 0.0  -&amp;gt; underflow
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# -4605.170185988091
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Example 2: normalizing log-weights the wrong way
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1000.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1001.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1005.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;bad_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;bad_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bad_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bad_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bad_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;     &lt;span class=&quot;c1&quot;&gt;# [nan nan nan]
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Stable way: subtract the max before exponentiating
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;good_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;good_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;good_weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;good_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;good_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# [0.727..., 0.268..., 0.0049...]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;What to take away is not “Python is annoying”, but:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;If you are already on the log scale, do not exponentiate too early.&lt;/li&gt;
  &lt;li&gt;When you need to normalize, subtract &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt; or use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log-sum-exp&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;9-very-common-practical-mistakes&quot;&gt;9) Very common practical mistakes&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;You have \(\log a\) and \(\log b\) but use \(\log a + \log b\) in place of \(\log(a+b)\). This is a fundamental difference: \(\log a + \log b = \log(ab)\), not the log of a sum. When you need to add probabilities in the log domain, you must use log-sum-exp.&lt;/li&gt;
  &lt;li&gt;Computing the likelihood on the ordinary scale first, then taking the log afterwards. If the likelihood has already underflowed to 0, taking the log only gives \(-\infty\); the lost information cannot be recovered.&lt;/li&gt;
  &lt;li&gt;Exponentiating the log-posterior too early just to “look at it familiarly”. Many inference steps do not need to return to the probability scale.&lt;/li&gt;
  &lt;li&gt;Always treating \(-\infty\) as a bug. Actually \(-\infty\) is sometimes a legitimate signal that the model is assigning probability 0 to some configuration. What to do is check whether it is a consequence of the model or a numerical error.&lt;/li&gt;
  &lt;li&gt;Forgetting that for continuous variables, the log-density can be positive if the density exceeds 1. This is not necessarily wrong.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;10-good-habits-when-coding-bayesian-models&quot;&gt;10) Good habits when coding Bayesian models&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Write functions that return the log-likelihood or log-posterior, not the raw likelihood.&lt;/li&gt;
  &lt;li&gt;Add likelihood contributions on the log scale.&lt;/li&gt;
  &lt;li&gt;Only exponentiate at the final step, when you really need normalized probabilities.&lt;/li&gt;
  &lt;li&gt;Use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;subtract max&lt;/code&gt; or log-sum-exp technique when normalizing weights.&lt;/li&gt;
  &lt;li&gt;Always check &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.isfinite(...)&lt;/code&gt; at important steps.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you have to remember just one sentence from this lesson, remember this one:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Bayes, stay on the log scale for as long as possible.&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;quick-summary&quot;&gt;Quick summary&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Many probability computations are right on paper but unstable on a computer.&lt;/li&gt;
  &lt;li&gt;Log-probability turns products into sums, helping avoid underflow and making optimization easier.&lt;/li&gt;
  &lt;li&gt;In Bayes, we usually work with the log-likelihood and the unnormalized log-posterior.&lt;/li&gt;
  &lt;li&gt;When you need to add or normalize probabilities in the log domain, you must use log-sum-exp or the subtract-&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt; technique.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nan&lt;/code&gt; are not minor details; they are very important diagnostic signals.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-rescuing-exp-1000--exp-1001-with-log-sum-exp&quot;&gt;Worked Numerical Example: Rescuing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;exp(-1000) + exp(-1001)&lt;/code&gt; With Log-Sum-Exp&lt;/h3&gt;

&lt;p&gt;Suppose two candidate models have unnormalized log-posteriors \(\ell_1 = -1000.0\) and \(\ell_2 = -1001.0\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Naive &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; evaluation:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.exp(-1000.0)&lt;/code&gt; returns &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.exp(-1001.0)&lt;/code&gt; returns &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0 / (0.0 + 0.0)&lt;/code&gt; explodes into &lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Log-Sum-Exp trick by hand:&lt;/strong&gt;
    &lt;ol&gt;
      &lt;li&gt;Shift by the maximum: \(m = \max(-1000.0, -1001.0) = -1000.0\).&lt;/li&gt;
      &lt;li&gt;Compute shifted exponentials: \(e^{-1000 - (-1000)} = e^0 = 1.0\) and \(e^{-1001 - (-1000)} = e^{-1} \approx 0.3679\).&lt;/li&gt;
      &lt;li&gt;Log-normalizer:
\(\mathrm{LSE} = -1000.0 + \ln(1 + 0.3679) = -1000.0 + 0.3133 = \mathbf{-999.6867}.\)&lt;/li&gt;
      &lt;li&gt;Exact normalized posterior probabilities:
\(P(M_1) = e^{-1000.0 - (-999.6867)} = e^{-0.3133} \approx \mathbf{0.7311}, \qquad P(M_2) = e^{-1.3133} \approx \mathbf{0.2689}!\)&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Zero underflow, zero overflow, and exact to full machine precision!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-numerical-rules-every-bayesian-coder-must-follow&quot;&gt;Explanation: Four Numerical Rules Every Bayesian Coder Must Follow&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always call &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.logpdf()&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.logpmf()&lt;/code&gt;, never &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.log(dist.pdf(...))&lt;/code&gt;:&lt;/strong&gt; Taking &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log&lt;/code&gt; &lt;em&gt;after&lt;/em&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pdf&lt;/code&gt; underflows to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt; still returns &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt;! Built-in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.logpdf()&lt;/code&gt; evaluates the algebraic log formula directly.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.special.logsumexp&lt;/code&gt; (or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log1p&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;expm1&lt;/code&gt;) for every normalization step:&lt;/strong&gt; Never hand-roll &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.exp(log_p) / np.sum(np.exp(log_p))&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Subtract the maximum log-posterior before plotting a grid:&lt;/strong&gt; Plotting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.exp(log_post - log_post.max())&lt;/code&gt; keeps peak height at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.0&lt;/code&gt; so grid normalization never underflows.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Remember that continuous log-densities can be positive:&lt;/strong&gt; Only discrete log-probabilities are always \(\le 0\); seeing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log_p = +1.8&lt;/code&gt; for a narrow continuous Normal or Beta is completely healthy!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Using the Log-Sum-Exp trick by hand, compute the exact normalized probabilities for two models with log-posteriors \(\ell_1 = -500.0\) and \(\ell_2 = -500.0\)!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VSi0Z04fWj0&quot;&gt;Logs (logarithms), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the log rules for products and sums, the algebraic foundation for the part of the lesson that moves from likelihood to log-likelihood.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HghZrdnrNQY&quot;&gt;Why Log Probabilities Are Everywhere in AI - Underflow Error in HMMs and Viterbi Algorithm&lt;/a&gt; — Algorithms and AI, English. Watch underflow when multiplying many small probabilities, exactly the numerical failure the lesson illustrates with a product of probabilities.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=MZ2VM32h37g&quot;&gt;The log-sum-exp trick (NLP817 5.12)&lt;/a&gt; — Herman Kamper, English. Watch the log-sum-exp trick, supporting the part of the lesson about normalizing without returning to the probability scale too early.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why can two different likelihood values both show up as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt; on a machine, while the two corresponding log-likelihoods remain comparable?&lt;/li&gt;
  &lt;li&gt;Explain in words why subtracting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt; does not change the final softmax.&lt;/li&gt;
  &lt;li&gt;When is \(-\infty\) a legitimate signal from the model, and when might it be a numerical bug?&lt;/li&gt;
  &lt;li&gt;Why can \(\log a + \log b\) not replace \(\log(a+b)\)?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Murphy, K. (2012). &lt;em&gt;Machine Learning: A Probabilistic Perspective&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Bishop, C. (2006). &lt;em&gt;Pattern Recognition and Machine Learning&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Higham, N. J. (2002). &lt;em&gt;Accuracy and Stability of Numerical Algorithms&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_18_basic_model_assumption_checks/&quot;&gt;0.20 Basic Model Assumption Checks&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.18: Point Estimation, Bias-Variance, Consistency</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_16_point_estimation_bias_variance_consistency/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_16_point_estimation_bias_variance_consistency</id>
   <content type="html">&lt;p&gt;Should a good estimator always be &lt;strong&gt;unbiased&lt;/strong&gt;? Classical textbooks often make unbiasedness sound sacred—yet in 1956 Charles Stein shocked the statistics world by proving that in 3 or more dimensions, gently &lt;strong&gt;shrinking&lt;/strong&gt; unbiased sample means toward a common prior cuts total Mean Squared Error &lt;em&gt;strictly lower&lt;/em&gt; than the unbiased MLE! That exact &lt;strong&gt;Bias–Variance Trade-off&lt;/strong&gt; is why Bayesian posterior means routinely beat frequentist MLEs on small and medium datasets.&lt;/p&gt;

&lt;p&gt;This lesson unpacks &lt;strong&gt;bias&lt;/strong&gt;, &lt;strong&gt;variance&lt;/strong&gt;, &lt;strong&gt;MSE&lt;/strong&gt;, and &lt;strong&gt;consistency&lt;/strong&gt;, and proves by hand how a tiny Bayesian Beta(2,2) prior beats unbiased MLE on MSE when sample size is small.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-evaluating-estimators-through-the-biasvariance-lens&quot;&gt;Key ideas: Evaluating Estimators Through the Bias–Variance Lens&lt;/h2&gt;

&lt;p&gt;Four principles bridge classical point estimation and Bayesian shrinkage:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Exact MSE Decomposition:&lt;/strong&gt; \(\mathrm{MSE}(\hat{\theta}) = \mathbb{E}[(\hat{\theta} - \theta)^2] = \mathrm{Bias}(\hat{\theta})^2 + \mathrm{Var}(\hat{\theta})\). Minimizing total error means balancing both terms, not obsessing over zero bias alone!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Consistency:&lt;/strong&gt; An estimator is consistent if \(\hat{\theta}_n \to \theta\) in probability as \(n \to \infty\). Both unbiased MLEs and Bayesian posterior means (under non-zero priors) are consistent—prior bias washes away as data grows!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Shrinkage Beats Unbiasedness at Small \(n\):&lt;/strong&gt; Pulling noisy estimates slightly toward a sensible prior introduces a tiny bias while slashing variance quadratically, reducing total MSE across most of the parameter space.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Point Estimates Are Loss-Function Decisions:&lt;/strong&gt; In Bayesian decision theory, the &lt;strong&gt;posterior mean&lt;/strong&gt; minimizes squared error (\(L_2\)), the &lt;strong&gt;posterior median&lt;/strong&gt; minimizes absolute error (\(L_1\)), and the &lt;strong&gt;MAP mode&lt;/strong&gt; minimizes 0–1 loss.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will understand the three core criteria for evaluating an estimator: bias, variance, consistency; and also grasp the bias-variance tradeoff as a model design principle rather than a slogan.&lt;/p&gt;

&lt;h2 id=&quot;introduction-evaluating-an-estimator-cannot-rely-on-a-single-number&quot;&gt;Introduction: evaluating an estimator cannot rely on a single number&lt;/h2&gt;

&lt;p&gt;A good estimator is not simply one that gives a “roughly right” result in one sample. We need to evaluate its behavior over many possible samples: is there systematic bias, does it fluctuate too much, and does it converge to the true value as data increases. The three criteria bias, variance, consistency were built to answer exactly these questions.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/bias_variance_tradeoff_curve.png&quot; alt=&quot;Bias variance tradeoff&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates the bias variance tradeoff. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;
&lt;em&gt;Figure 1: Bias gradually decreases as complexity increases, variance gradually increases, and the MSE has an optimal balance point.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-what-is-point-estimation&quot;&gt;1) What is point estimation?&lt;/h2&gt;

&lt;p&gt;A point estimate is a function of the data \(\hat\theta=g(x_1,\dots,x_n)\) used to predict the value of an unknown parameter \(\theta\).&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;We can use \(\bar X\) to estimate \(\mu\), use the sample proportion \(\hat p\) to estimate \(p\), or use a sample regression coefficient to estimate the true slope.&lt;/p&gt;

&lt;h2 id=&quot;2-bias&quot;&gt;2) Bias&lt;/h2&gt;

&lt;p&gt;Bias measures systematic deviation:&lt;/p&gt;

\[\mathrm{Bias}(\hat\theta)=\mathbb{E}[\hat\theta]-\theta\]

&lt;p&gt;When the bias is 0, the estimator is unbiased; when the bias is nonzero, the estimator tends to be systematically off to one side.&lt;/p&gt;

&lt;h2 id=&quot;3-the-variance-of-an-estimator&quot;&gt;3) The variance of an estimator&lt;/h2&gt;

&lt;p&gt;Even an unbiased estimator can still fluctuate strongly between different samples. That fluctuation is measured by \(\mathrm{Var}(\hat\theta)\).&lt;/p&gt;

&lt;p&gt;A good estimator needs not only little bias but also reasonable variance.&lt;/p&gt;

&lt;h2 id=&quot;4-mse-and-the-bias-variance-decomposition&quot;&gt;4) MSE and the bias-variance decomposition&lt;/h2&gt;

&lt;p&gt;The expected squared error:&lt;/p&gt;

\[\mathrm{MSE}(\hat\theta)=\mathbb{E}[(\hat\theta-\theta)^2]\]

&lt;p&gt;decomposes into:&lt;/p&gt;

\[\mathrm{MSE}(\hat\theta)=\mathrm{Bias}(\hat\theta)^2+\mathrm{Var}(\hat\theta)\]

&lt;p&gt;This is the foundation for regularization thinking: accept a little bias to reduce variance and improve the total prediction error.&lt;/p&gt;

&lt;h3 id=&quot;41-a-very-concrete-example-of-the-bias-variance-trade-off&quot;&gt;4.1) A very concrete example of the bias-variance trade-off&lt;/h3&gt;

&lt;p&gt;Suppose we need to estimate a true parameter \(\theta = 10\), and we have two estimators:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Estimator A: unbiased, so \(\mathrm{Bias}=0\), but its variance is \(9\).&lt;/li&gt;
  &lt;li&gt;Estimator B: slightly biased by 1 unit, so \(\mathrm{Bias}=1\), but its variance is only \(4\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then:&lt;/p&gt;

\[\mathrm{MSE}(A) = 0^2 + 9 = 9,
\qquad
\mathrm{MSE}(B) = 1^2 + 4 = 5.\]

&lt;p&gt;Even though estimator B has bias, it is still better in MSE because in return it gets a larger reduction in variance. This is the logic behind many shrinkage and regularization techniques: accept a slight bias in exchange for more stable predictions.&lt;/p&gt;

&lt;h2 id=&quot;5-consistency&quot;&gt;5) Consistency&lt;/h2&gt;

&lt;p&gt;An estimator \(\hat\theta_n\) is called consistent if:&lt;/p&gt;

\[\hat\theta_n \xrightarrow[]{P} \theta \quad \text{as } n\to\infty\]

&lt;p&gt;Simply put: when there is enough data, the estimator approaches the true value.&lt;/p&gt;

&lt;h2 id=&quot;6-the-connection-to-bayes&quot;&gt;6) The connection to Bayes&lt;/h2&gt;

&lt;p&gt;In Bayes, we do not only use a point estimate but use the whole posterior. Still, bias-variance thinking remains very useful:&lt;/p&gt;

&lt;p&gt;A strong prior usually reduces variance but may increase bias, while a weak prior usually reduces bias but the variance can be large when data is still scarce.&lt;/p&gt;

&lt;h2 id=&quot;quick-summary&quot;&gt;Quick summary&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Bias measures the systematic deviation of an estimator.&lt;/li&gt;
  &lt;li&gt;Variance measures the fluctuation between samples.&lt;/li&gt;
  &lt;li&gt;MSE = bias^2 + variance.&lt;/li&gt;
  &lt;li&gt;Consistency is about behavior when the sample size is large.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-comparing-unbiased-mle-vs-bayesian-mathrmbeta22-estimator-at-n--4&quot;&gt;Worked Numerical Example: Comparing Unbiased MLE vs. Bayesian \(\mathrm{Beta}(2,2)\) Estimator at \(n = 4\)&lt;/h3&gt;

&lt;p&gt;Suppose we flip a coin \(n = 4\) times with true probability \(p = 0.5\) and compare two estimators of \(p\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Unbiased MLE:&lt;/strong&gt; \(\hat{p}_{\text{MLE}} = \frac{K}{4}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Posterior Mean under \(\mathrm{Beta}(2,2)\) prior:&lt;/strong&gt; \(\hat{p}_{\text{Bayes}} = \frac{K + 2}{4 + 4} = \frac{K + 2}{8} = 0.5\,\hat{p}_{\text{MLE}} + 0.25\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Compute exact Bias, Variance, and MSE at \(p = 0.5\) (where \(\mathrm{Var}(K) = 4(0.5)(0.5) = 1\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Estimator&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Formula&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Bias at \(p=0.5\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Variance at \(p=0.5\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Total MSE = \(\mathrm{Bias}^2 + \mathrm{Var}\)&lt;/strong&gt;&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Unbiased MLE&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(K / 4\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\frac{1}{16} = \mathbf{0.0625}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.0625\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Bayesian \(\mathrm{Beta}(2,2)\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((K + 2) / 8\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\frac{1}{64} = \mathbf{0.0156}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.0156\) (4× smaller MSE!)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Even if the true coin is &lt;em&gt;biased&lt;/em&gt; at \(p = 0.7\) (where \(\mathrm{Var}(K) = 4(0.7)(0.3) = 0.84\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;MLE:&lt;/strong&gt; \(\mathrm{Bias} = 0\), \(\mathrm{MSE} = 0.84/16 = \mathbf{0.0525}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian \(\mathrm{Beta}(2,2)\):&lt;/strong&gt; \(\mathbb{E}[\hat{p}_{\text{Bayes}}] = \frac{2.8+2}{8} = 0.60 \implies \mathrm{Bias} = -0.10\), \(\mathrm{Var} = 0.84/64 = 0.0131\), so \(\mathrm{MSE} = (-0.10)^2 + 0.0131 = \mathbf{0.0231}\) — &lt;strong&gt;still more than 2× lower total error than unbiased MLE!&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-takeaways-on-bias-variance-and-bayesian-shrinkage&quot;&gt;Explanation: Four Takeaways on Bias, Variance, and Bayesian Shrinkage&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Unbiasedness is a property of averages, not individual estimates:&lt;/strong&gt; An unbiased estimator with huge variance can land wildly far from the truth on &lt;em&gt;your&lt;/em&gt; single dataset.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Every Bayesian prior acts as a principled regularizer:&lt;/strong&gt; Just as Ridge regression shrinks noisy regression slopes to cut MSE, a weakly informative prior shrinks small-sample estimates toward plausible values.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check consistency as \(n \to \infty\):&lt;/strong&gt; For \(\hat{p}_{\text{Bayes}} = \frac{K+2}{n+4}\), as \(n\) grows, both Bias \(O(1/n)\) and Variance \(O(1/n)\) vanish—it becomes asymptotically indistinguishable from MLE!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Keep the full posterior whenever possible:&lt;/strong&gt; Collapsing a posterior into a single point estimate throws away uncertainty; report the full credible interval alongside any point summary.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Using the same \(n = 4\) comparison above, at the extreme coin \(p = 1.0\) (where \(\mathrm{Var}(K) = 0\)), which estimator has lower MSE—MLE or \(\mathrm{Beta}(2,2)\)—and why?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=6i7mqDJICzQ&quot;&gt;Unbiasedness vs consistency of estimators - an example&lt;/a&gt; — Ben Lambert, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch an example separating an unbiased estimator from a consistent one, exactly the two criteria the lesson places side by side.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qmVT35gFW-Q&quot;&gt;[Proof] MSE = Variance + Bias²&lt;/a&gt; — math et al, English. Watch the decomposition of MSE into squared bias plus variance, supporting the bias–variance tradeoff part of the estimator discussion.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vikkiwjQqfU&quot;&gt;Population and Estimated Parameters, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch estimating parameters from a sample, used for the part of the lesson about the behavior of an estimator as data grows.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Can an estimator have small bias but large MSE? Why?&lt;/li&gt;
  &lt;li&gt;Why can regularization help prediction even though it creates bias?&lt;/li&gt;
  &lt;li&gt;Does consistency guarantee good performance in small samples?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Casella, G., &amp;amp; Berger, R. (2002). &lt;em&gt;Statistical Inference&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Hastie, T., Tibshirani, R., &amp;amp; Friedman, J. (2009). &lt;em&gt;The Elements of Statistical Learning&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_17_log_probability_numerical_stability/&quot;&gt;0.19 Log-probability and Numerical Stability&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.17: Sampling Distribution and Standard Error</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_15_sampling_distribution_standard_error/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_15_sampling_distribution_standard_error</id>
   <content type="html">&lt;p&gt;Open almost any scientific paper and you will see error bars plotted around a mean—yet half of readers (and plenty of authors!) confuse &lt;strong&gt;Standard Deviation (SD)&lt;/strong&gt; with &lt;strong&gt;Standard Error (SE)&lt;/strong&gt;. When a nutrition study reports &lt;em&gt;“mean weight loss = 4 kg, SD = 12 kg, \(n = 144\)“&lt;/em&gt;, individual patients vary wildly (\(\pm 12\text{ kg}\)), yet the &lt;em&gt;standard error of the mean&lt;/em&gt; is a razor-thin &lt;strong&gt;\(12 / \sqrt{144} = 1.0\text{ kg}\)&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;This lesson draws an unbreakable line between &lt;strong&gt;data spread (SD)&lt;/strong&gt; and &lt;strong&gt;estimator uncertainty (SE)&lt;/strong&gt;, showing how the frequentist sampling distribution compares directly to the Bayesian &lt;strong&gt;posterior standard deviation&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-data-spread-vs-estimator-uncertainty&quot;&gt;Key ideas: Data Spread vs. Estimator Uncertainty&lt;/h2&gt;

&lt;p&gt;Four distinctions clear up every error-bar confusion forever:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Standard Deviation (SD, \(s\)):&lt;/strong&gt; Measures how spread out &lt;em&gt;individual observations&lt;/em&gt; are around the mean. Collecting more data makes \(s\) estimate \(\sigma\) more accurately—it does &lt;strong&gt;NOT&lt;/strong&gt; shrink \(s\) toward zero!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Standard Error (SE, \(s/\sqrt{n}\)):&lt;/strong&gt; Measures how much the &lt;em&gt;sample mean&lt;/em&gt; \(\bar{X}_n\) would bounce around if you repeated the entire study from scratch. As \(n \to \infty\), \(\mathrm{SE} \to 0\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sampling Distribution:&lt;/strong&gt; The theoretical distribution of a statistic (\(\bar{X}_n\), \(\hat{p}\), \(\hat{\beta}_1\)) across hypothetical repeated samples of size \(n\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Counterpart (Posterior SD):&lt;/strong&gt; Instead of imagining repeated hypothetical samples, Bayesian inference computes the exact spread of your belief about \(\mu\) given &lt;em&gt;this&lt;/em&gt; dataset—and for large \(n\) with a weak prior, the Bayesian posterior SD converges right onto \(\mathrm{SE} = \sigma/\sqrt{n}\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will clearly distinguish the raw data from the distribution of an estimate, understand that the standard error is the uncertainty of the estimator (not the spread of the data), and use this intuition to read inference results more correctly.&lt;/p&gt;

&lt;h2 id=&quot;introduction-from-one-data-sample-to-the-reliability-of-an-estimate&quot;&gt;Introduction: from one data sample to the reliability of an estimate&lt;/h2&gt;

&lt;p&gt;In practice, we often have only a single data sample, but still need to answer the question “how stable is the current estimate if the sampling procedure were repeated?”. The sampling distribution and the standard error are exactly the language for quantifying that question scientifically.&lt;/p&gt;

&lt;h2 id=&quot;1-what-is-a-sampling-distribution&quot;&gt;1) What is a sampling distribution?&lt;/h2&gt;

&lt;p&gt;Suppose we repeat the same sampling procedure many times and each time compute an estimate \(\hat\theta\) (for example the sample mean \(\bar X\)). The collection of \(\hat\theta\) values across the repetitions forms the &lt;strong&gt;sampling distribution&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The key point: the sampling distribution is the distribution of the &lt;strong&gt;estimate&lt;/strong&gt;, not the distribution of individual data points.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/sampling_distribution_n20.png&quot; alt=&quot;Sampling distribution of the sample mean with n = 20&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1a: For the same problem but with a small sample size, the sampling distribution of the sample mean is still fairly wide.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-standard-error-se&quot;&gt;2) Standard Error (SE)&lt;/h2&gt;

&lt;p&gt;The SE is the standard deviation of the sampling distribution:&lt;/p&gt;

\[\mathrm{SE}(\hat\theta)=\sqrt{\mathrm{Var}(\hat\theta)}\]

&lt;p&gt;For the sample mean:&lt;/p&gt;

\[\mathrm{SE}(\bar X)=\frac{\sigma}{\sqrt{n}}\approx\frac{s}{\sqrt{n}}\]

&lt;p&gt;So:&lt;/p&gt;

&lt;p&gt;The SD of the data measures the spread among individuals, while the SE measures the uncertainty of the estimate itself.&lt;/p&gt;

&lt;h3 id=&quot;experiment-sampling-distribution-and-standard-error&quot;&gt;Experiment: sampling distribution and standard error&lt;/h3&gt;

&lt;p&gt;Increase the sample size n and watch the standard deviation of the sample mean decrease as σ/√n.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;clt-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;clt&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;3-a-common-confusion-sd-vs-se&quot;&gt;3) A common confusion: SD vs SE&lt;/h2&gt;

&lt;p&gt;Two datasets with the same SD but different sample sizes will have different SEs.&lt;/p&gt;

&lt;p&gt;If \(n\) is larger then the SE is smaller and the estimate is more stable, while if \(n\) is small then the SE is larger and the conclusion is therefore less certain.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/sampling_distribution_n200.png&quot; alt=&quot;Sampling distribution of the sample mean with n = 200&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1b: When the sample size is increased to \(n = 200\), the sampling distribution narrows markedly, corresponding to a smaller standard error.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;31-an-example-where-sd-and-se-are-easily-confused&quot;&gt;3.1) An example where SD and SE are easily confused&lt;/h3&gt;

&lt;p&gt;Suppose the weight of a group of people has a standard deviation of about 12 kg.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;If we sample \(n=25\) people, the standard error of the mean is \(12/\sqrt{25}=2.4\) kg.&lt;/li&gt;
  &lt;li&gt;If we sample \(n=100\) people, the standard error of the mean is \(12/\sqrt{100}=1.2\) kg.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The important point is that the SD of individual data is still 12 kg in both cases. What changes is the uncertainty of the &lt;strong&gt;estimate of the mean&lt;/strong&gt;. This is why SD and SE cannot be used interchangeably, even though many beginners often mix up the two quantities.&lt;/p&gt;

&lt;h2 id=&quot;4-how-does-the-se-relate-to-confidencecredible-intervals&quot;&gt;4) How does the SE relate to confidence/credible intervals?&lt;/h2&gt;

&lt;p&gt;In normal-approximation thinking, an uncertainty interval usually has the form:&lt;/p&gt;

\[\hat\theta \pm c\cdot \mathrm{SE}(\hat\theta)\]

&lt;p&gt;The factor \(c\) depends on the goal (95%, 90%, …). Regardless of the framework (Frequentist or Bayesian), the intuition that “the width increases when the SE is large” remains the same.&lt;/p&gt;

&lt;h2 id=&quot;5-the-connection-to-the-bayesian-workflow&quot;&gt;5) The connection to the Bayesian workflow&lt;/h2&gt;

&lt;p&gt;In Bayes, the posterior SD of a parameter plays a role close to the SE: it gives us the uncertainty of the parameter after combining the prior and the data.&lt;/p&gt;

&lt;p&gt;If you are used to thinking in terms of sampling distribution + SE, reading posterior intervals will be much easier.&lt;/p&gt;

&lt;h2 id=&quot;quick-summary&quot;&gt;Quick summary&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;The sampling distribution is the distribution of the estimator.&lt;/li&gt;
  &lt;li&gt;The SE is the standard deviation of the estimator.&lt;/li&gt;
  &lt;li&gt;The data SD and the SE are two different things.&lt;/li&gt;
  &lt;li&gt;Increasing the sample size decreases the SE as \(1/\sqrt{n}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-watching-sd-stay-flat-while-se-collapses-as-n-grows&quot;&gt;Worked Numerical Example: Watching SD Stay Flat While SE Collapses as \(n\) Grows&lt;/h3&gt;

&lt;p&gt;Suppose adult reaction times have population mean \(\mu = 250\text{ ms}\) and population SD \(\sigma = 36\text{ ms}\). Compare studies of size \(n = 9\), \(n = 36\), and \(n = 144\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Sample Size \(n\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Individual Spread (\(\sigma\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Standard Error (\(\mathrm{SE} = \sigma/\sqrt{n}\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;95% Interval for Mean \(\mu\) (\(\pm 1.96\,\mathrm{SE}\))&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(n = 9\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(36.0\text{ ms}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(36 / 3 = \mathbf{12.0\text{ ms}}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\bar{x} \pm 23.5\text{ ms}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(n = 36\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(36.0\text{ ms}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(36 / 6 = \mathbf{6.0\text{ ms}}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\bar{x} \pm 11.8\text{ ms}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(n = 144\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(36.0\text{ ms}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(36 / 12 = \mathbf{3.0\text{ ms}}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\bar{x} \pm 5.9\text{ ms}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Every 4× increase in sample size halves the SE while leaving individual human variability (\(36\text{ ms}\)) completely unchanged!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-reading-error-bars-like-a-statistician&quot;&gt;Explanation: Four Rules for Reading Error Bars Like a Statistician&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check the caption: are the error bars SD, SE, or 95% CI?&lt;/strong&gt; Plotting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;± 1 SE&lt;/code&gt; makes noisy data look artificially tight—always label explicitly!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use SD to describe people/items; use SE (or posterior SD) to describe uncertainty in an average:&lt;/strong&gt; A doctor telling a patient &lt;em&gt;“your outcome will likely fall within…”&lt;/em&gt; needs SD (or a posterior predictive interval), never SE!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Beware non-independent samples:&lt;/strong&gt; If you measure 100 time points from just &lt;strong&gt;5 patients&lt;/strong&gt;, your effective sample size for estimating the population mean is closer to 5, not 100—dividing by \(\sqrt{100}\) severely understates true SE!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bootstrap when no closed-form SE exists:&lt;/strong&gt; For medians, ratios, or AUC scores, resampling your data 2,000 times estimates the sampling distribution directly.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If a dataset has \(n = 100\) independent observations with sample SD \(s = 20\), what is the standard error of the mean—and if you collect \(300\) &lt;em&gt;more&lt;/em&gt; observations (reaching \(n = 400\)), what happens to \(s\) and to \(\mathrm{SE}\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=A82brFpdr9g&quot;&gt;Standard Deviation vs Standard Error, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch so as not to mix the spread of the data with the uncertainty of the estimate, exactly the distinction between standard deviation and standard error.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Introduction to sampling distributions&lt;/td&gt;
          &lt;td&gt;Sampling distributions&lt;/td&gt;
          &lt;td&gt;AP Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=z0Ry_3_qhDw) — Khan Academy, English. Watch the sampling distribution of a statistic, supporting the question the lesson poses if the sampling procedure were repeated.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Standard error of the mean&lt;/td&gt;
          &lt;td&gt;Inferential statistics&lt;/td&gt;
          &lt;td&gt;Probability and Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=J1twbrHel3o) — Khan Academy, English. Watch the standard error of the sample mean decrease with sample size, used for the part on reading the stability of an estimator.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Explain why a large SD does not mean a large SE in every case.&lt;/li&gt;
  &lt;li&gt;If the sample size is increased from 100 to 400, how does the SE change?&lt;/li&gt;
  &lt;li&gt;Is the sampling distribution of the median the same as that of the mean? Why?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Rice, J. (2006). &lt;em&gt;Mathematical Statistics and Data Analysis&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Wasserman, L. (2004). &lt;em&gt;All of Statistics&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_16_point_estimation_bias_variance_consistency/&quot;&gt;0.18 Point Estimation, Bias-Variance, Consistency&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.16: The Law of Large Numbers and the Central Limit Theorem</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_14_law_large_numbers_clt/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_14_law_large_numbers_clt</id>
   <content type="html">&lt;p&gt;When an MCMC sampler generates 4,000 posterior draws and reports that your posterior mean is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.412&lt;/code&gt;, how do you know that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.412&lt;/code&gt; is actually close to the true integral \(\int \theta\,p(\theta\mid y)\,d\theta\)—and how many extra draws would it take to pin down one more decimal digit? Two twin theorems from probability theory answer both questions: the &lt;strong&gt;Law of Large Numbers (LLN)&lt;/strong&gt; guarantees your sample average converges to the truth, and the &lt;strong&gt;Central Limit Theorem (CLT)&lt;/strong&gt; tells you the exact speed of convergence: &lt;strong&gt;\(O(1/\sqrt{S})\)&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;This lesson builds crystal-clear intuition for LLN and CLT—not just for real-world data collection, but as the exact mathematical warranty behind &lt;strong&gt;Monte Carlo integration and MCMC sampling&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-lln-and-clt-as-the-engine-of-monte-carlo-bayes&quot;&gt;Key ideas: LLN and CLT as the Engine of Monte Carlo Bayes&lt;/h2&gt;

&lt;p&gt;Four concepts connect classical limit theorems directly to modern Bayesian computation:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Law of Large Numbers (LLN):&lt;/strong&gt; As independent draws \(S \to \infty\), the sample mean \(\bar{X}_S = \frac{1}{S}\sum_{s=1}^S X^{(s)}\) converges to \(\mu = \mathbb{E}[X]\)—guaranteeing that Monte Carlo expectations are consistent.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Central Limit Theorem (CLT) &amp;amp; Monte Carlo Standard Error (MCSE):&lt;/strong&gt; For large \(S\), \(\bar{X}_S \approx \mathcal{N}\!\left(\mu,\; \frac{\sigma^2}{S}
ight)\), so the Monte Carlo standard error is \(\mathrm{MCSE} = \frac{\sigma}{\sqrt{S}}\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The 100× Cost of One Extra Decimal Digit:&lt;/strong&gt; Because error shrinks like \(1/\sqrt{S}\), cutting MCSE by \(10\times\) requires &lt;strong&gt;\(100\times\) as many samples&lt;/strong&gt;—explaining why efficient HMC/NUTS samplers beat crude random-walk samplers by orders of magnitude.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Effective Sample Size (ESS) for Correlated MCMC Draws:&lt;/strong&gt; When draws are positively autocorrelated (as in MCMC), replace raw \(S\) with the &lt;strong&gt;Effective Sample Size \(S_{\text{eff}}\)&lt;/strong&gt; in \(\mathrm{MCSE} = \sigma / \sqrt{S_{\text{eff}}}\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will understand why the sample mean stabilizes as the sample size grows (LLN), why the sum/mean of many random variables tends to be close to normal (CLT), and why these two theorems are the foundation for thinking about simulation, estimation, and testing.&lt;/p&gt;

&lt;h2 id=&quot;introduction-why-does-randomness-still-produce-stable-regularities&quot;&gt;Introduction: why does randomness still produce stable regularities?&lt;/h2&gt;

&lt;p&gt;One of the foundational ideas of statistics is: each individual observation can be very noisy, but when we aggregate enough observations, we see a clear structure of regularity. The LLN and CLT are two theorems that describe exactly this phenomenon, and also explain why sample estimates can be used to make inferences about the population.&lt;/p&gt;

&lt;h2 id=&quot;1-the-law-of-large-numbers-lln-the-sample-mean-converges&quot;&gt;1) The Law of Large Numbers (LLN): the sample mean converges&lt;/h2&gt;

&lt;p&gt;Let \(X_1,\dots,X_n\) be independent and identically distributed, with expectation \(\mu\). The sample mean:&lt;/p&gt;

\[\bar X_n = \frac{1}{n}\sum_{i=1}^n X_i\]

&lt;p&gt;The LLN says that as \(n\to\infty\), \(\bar X_n\) approaches \(\mu\) (in probability).&lt;/p&gt;

&lt;p&gt;Intuition: random noise “gradually cancels out” when averaging over many observations.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/lln_running_mean_convergence.png&quot; alt=&quot;The running mean gradually converges to the expectation&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1a: The law of large numbers shows the running mean gradually stabilizing and converging to the expected value as the number of observations increases.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;experiment-the-law-of-large-numbers&quot;&gt;Experiment: the law of large numbers&lt;/h3&gt;

&lt;p&gt;The running means of five simulated sequences converge to μ.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;clt-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;lln&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;2-the-clt-the-distribution-of-the-sample-mean-is-close-to-normal&quot;&gt;2) The CLT: the distribution of the sample mean is close to normal&lt;/h2&gt;

&lt;p&gt;Under mild enough conditions, we have:&lt;/p&gt;

\[\frac{\bar X_n-\mu}{\sigma/\sqrt{n}} \Rightarrow \mathcal N(0,1)\]

&lt;p&gt;Practical consequence:&lt;/p&gt;

\[\bar X_n \approx \mathcal N\left(\mu,\frac{\sigma^2}{n}\right)\]

&lt;p&gt;even when the original distribution is not normal (n large enough).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/clt_sample_means_histogram.png&quot; alt=&quot;The distribution of the sample mean is close to normal&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1b: The central limit theorem shows that the distribution of the sample mean approaches a normal shape even though the original data is not necessarily normal.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;experiment-the-central-limit-theorem&quot;&gt;Experiment: the central limit theorem&lt;/h3&gt;

&lt;p&gt;The histogram of the sample mean approaches a normal distribution as n increases, even though the original distribution is skewed.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;clt-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;clt&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;3-how-do-the-lln-and-clt-differ&quot;&gt;3) How do the LLN and CLT differ?&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;LLN&lt;/strong&gt; answers the question of whether the sample mean converges to the true value, while the &lt;strong&gt;CLT&lt;/strong&gt; answers the question of what the rate and shape of the uncertainty around the true value look like. In other words, the LLN is the story of “where it converges to”, and the CLT is the story of “how it fluctuates around the truth”.&lt;/p&gt;

&lt;h2 id=&quot;4-the-connection-to-the-standard-error&quot;&gt;4) The connection to the standard error&lt;/h2&gt;

&lt;p&gt;From the CLT, the magnitude of the fluctuation of \(\bar X_n\) is proportional to \(1/\sqrt{n}\). This is why the standard error decreases slowly:&lt;/p&gt;

&lt;p&gt;To cut the error by a factor of 2, we usually have to increase the sample size by about 4 times.&lt;/p&gt;

&lt;p&gt;This is an important intuition when designing experiments and assessing the reliability of estimates.&lt;/p&gt;

&lt;h3 id=&quot;41-a-numerical-example-what-if-we-increase-the-sample-4-times&quot;&gt;4.1) A numerical example: what if we increase the sample 4 times?&lt;/h3&gt;

&lt;p&gt;Suppose we are estimating a true proportion around \(0.6\). Then the standard error of the sample frequency is approximately:&lt;/p&gt;

\[\mathrm{SE}(\hat p)\approx \sqrt{\frac{0.6\times 0.4}{n}}.\]

&lt;ul&gt;
  &lt;li&gt;If \(n=25\) then \(\mathrm{SE}\approx 0.098\).&lt;/li&gt;
  &lt;li&gt;If \(n=100\) then \(\mathrm{SE}\approx 0.049\).&lt;/li&gt;
  &lt;li&gt;If \(n=400\) then \(\mathrm{SE}\approx 0.024\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That is, when increasing the sample size from 25 to 100, and then from 100 to 400, the uncertainty falls by about half each time, rather than in the style of “doubling the data halves the error”. This is a very direct way to remember why the LLN and CLT lead to the \(1/\sqrt{n}\) law in practice.&lt;/p&gt;

&lt;h2 id=&quot;5-the-connection-to-bayes-and-simulation&quot;&gt;5) The connection to Bayes and simulation&lt;/h2&gt;

&lt;p&gt;In Bayes, Monte Carlo estimates also rely on the idea of the sample mean: the more posterior samples there are, the more stable the estimate becomes, and many diagnostics about uncertainty are actually based on the intuition of the LLN and CLT.&lt;/p&gt;

&lt;h2 id=&quot;quick-summary&quot;&gt;Quick summary&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;LLN: the sample mean converges to the true expectation when the sample size is large.&lt;/li&gt;
  &lt;li&gt;CLT: the distribution of the sample mean is close to normal with variance \(\sigma^2/n\).&lt;/li&gt;
  &lt;li&gt;The LLN is about convergence; the CLT is about fluctuation around the point of convergence.&lt;/li&gt;
  &lt;li&gt;Both are foundations for statistical inference and simulation.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-budgeting-monte-carlo-draws-for-exact-posterior-precision&quot;&gt;Worked Numerical Example: Budgeting Monte Carlo Draws for Exact Posterior Precision&lt;/h3&gt;

&lt;p&gt;Suppose a posterior distribution for conversion rate \(\theta\) has standard deviation \(\sigma = 0.10\), and we estimate its posterior mean by averaging \(S\) independent Monte Carlo draws:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Independent Draws \(S\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(\mathrm{MCSE} = 0.10 / \sqrt{S}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;95% Monte Carlo Error Band (\(\pm 1.96\,\mathrm{MCSE}\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Reliable Decimal Places&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(S = 100\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0100\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\pm 0.0196\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;~1–2 digits (rough!)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(S = 1{,}600\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0025\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\pm 0.0049\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;2 digits&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(S = 10{,}000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0010\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\pm 0.0020\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;~3 digits&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(S = 1{,}000{,}000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0001\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\pm 0.0002\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;~4 digits (100× more compute!)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Now check what happens if an MCMC chain draws \(S = 10{,}000\) correlated samples with an Effective Sample Size of only \(S_{\text{eff}} = 400\): its true MCSE is \(0.10 / \sqrt{400} = 0.0050\)—five times noisier than 10,000 independent draws!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-using-lln--clt-wisely&quot;&gt;Explanation: Four Rules for Using LLN &amp;amp; CLT Wisely&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check MCSE in your Bayesian summary tables (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;arviz.summary&lt;/code&gt;):&lt;/strong&gt; A posterior mean of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.412&lt;/code&gt; with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mcse_mean = 0.001&lt;/code&gt; is rock-solid; with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mcse_mean = 0.04&lt;/code&gt;, you need more draws or a better sampler!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;LLN fails when the mean does not exist (Cauchy distribution!):&lt;/strong&gt; Averaging 10,000 draws from a Cauchy(0,1) distribution &lt;em&gt;never&lt;/em&gt; settles down because occasional giant outliers reset the running mean.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tail quantiles need more draws than the mean:&lt;/strong&gt; Estimating the 95% credible interval boundary accurately requires higher tail ESS (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ess_tail&lt;/code&gt;) than estimating the center (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ess_bulk&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;CLT does not make a small-sample &lt;em&gt;posterior&lt;/em&gt; Gaussian:&lt;/strong&gt; With \(n = 5\) data points, running \(S = 100{,}000\) MCMC draws makes your &lt;em&gt;Monte Carlo estimate&lt;/em&gt; of the posterior ultra-precise—it does &lt;em&gt;not&lt;/em&gt; turn a skewed posterior into a bell curve!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If your posterior SD is \(\sigma = 0.20\) and you want your Monte Carlo Standard Error (MCSE) of the posterior mean to be \(\le 0.002\), how many independent draws \(S\) do you need?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=MntX3zWNWec&quot;&gt;Law of Large Numbers - Explained and Visualized&lt;/a&gt; — Jeremy Blitz-Jones, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the sample mean stabilize as the number of observations grows, exactly the law of large numbers in the first half of the lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zeJD6dqJ5lo&quot;&gt;But what is the Central Limit Theorem?&lt;/a&gt; — 3Blue1Brown, English. Watch the shape of the distribution of the mean approach a bell, supporting the central limit theorem part.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Sm2yBx3Jn6c&quot;&gt;Định lý giới hạn trung tâm (Central limit theorem)&lt;/a&gt; — Bài Học 10 Phút, Vietnamese. Watch the same theorem again in Vietnamese, to compare with the lesson’s argument about estimation and simulation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why is the LLN not enough to deduce the uncertainty interval of \(\bar X\)?&lt;/li&gt;
  &lt;li&gt;Explain in words why the standard error decreases as \(1/\sqrt{n}\).&lt;/li&gt;
  &lt;li&gt;Does the CLT require the original data to be normal?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Casella, G., &amp;amp; Berger, R. (2002). &lt;em&gt;Statistical Inference&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Wasserman, L. (2004). &lt;em&gt;All of Statistics&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_15_sampling_distribution_standard_error/&quot;&gt;0.17 Sampling Distribution and Standard Error&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.15: Expectation, Variance, and Covariance</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_13_expectation_variance_covariance/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_13_expectation_variance_covariance</id>
   <content type="html">&lt;p&gt;If two financial assets each have a standard deviation of 10%, what is the standard deviation of their sum? Most people guess 20%—yet depending on their &lt;strong&gt;covariance&lt;/strong&gt;, the true standard deviation can be anywhere from &lt;strong&gt;0%&lt;/strong&gt; (perfect negative correlation, complete hedge!) to &lt;strong&gt;20%&lt;/strong&gt; (perfect positive correlation)! Mastering how expectations, variances, and covariances combine is essential for understanding both portfolio risk and &lt;strong&gt;correlated parameter uncertainty in Bayesian posteriors&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This lesson turns linearity of expectation, the variance sum law, and covariance/correlation into effortless mental reflexes.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-moments-linearity-and-correlated-uncertainty&quot;&gt;Key ideas: Moments, Linearity, and Correlated Uncertainty&lt;/h2&gt;

&lt;p&gt;Four identities do 90% of the algebraic heavy lifting in probability and Bayesian inference:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Linearity of Expectation (Always True!):&lt;/strong&gt; \(\mathbb{E}[aX + bY + c] = a\mathbb{E}[X] + b\mathbb{E}[Y] + c\) holds &lt;strong&gt;even when \(X\) and \(Y\) are strongly dependent&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Variance Scaling &amp;amp; Sum Law:&lt;/strong&gt; \(\mathrm{Var}(aX + b) = a^2\mathrm{Var}(X)\) (constants vanish, scales square!), and for two variables: \(\mathrm{Var}(X + Y) = \mathrm{Var}(X) + \mathrm{Var}(Y) + 2\mathrm{Cov}(X, Y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Covariance &amp;amp; Dimensionless Correlation:&lt;/strong&gt; \(\mathrm{Cov}(X, Y) = \mathbb{E}[XY] - \mathbb{E}[X]\mathbb{E}[Y]\) depends on units; dividing by \(\sigma_X\sigma_Y\) gives correlation \(ho \in [-1, 1]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Law of Total Expectation &amp;amp; Variance (Hierarchical Bayes Engine):&lt;/strong&gt; \(\mathrm{Var}(Y) = \mathbb{E}[\mathrm{Var}(Y\mid\theta)] + \mathrm{Var}(\mathbb{E}[Y\mid\theta])\) decomposes total predictive uncertainty into &lt;em&gt;within-model noise&lt;/em&gt; plus &lt;em&gt;parameter uncertainty&lt;/em&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will understand expectation as the “long-run average”, variance as the “spread around the mean”, covariance as the “same-direction or opposite-direction co-movement” between two variables, and know why these three concepts appear constantly in every Bayesian model.&lt;/p&gt;

&lt;h2 id=&quot;introduction-three-quantities-describing-center-and-uncertainty&quot;&gt;Introduction: three quantities describing center and uncertainty&lt;/h2&gt;

&lt;p&gt;In probabilistic inference, we do not always need to know the entire detailed distribution. Many practical decisions start from three basic questions: where the typical value lies, how large the fluctuation is, and whether the variables vary together. Expectation, variance, and covariance are the three quantities that answer those three questions directly.&lt;/p&gt;

&lt;h2 id=&quot;1-expectation-the-mean-value-under-a-distribution&quot;&gt;1) Expectation: the mean value under a distribution&lt;/h2&gt;

&lt;p&gt;For a discrete variable:&lt;/p&gt;

\[\mathbb{E}[X] = \sum_x x\,p(x)\]

&lt;p&gt;For a continuous variable:&lt;/p&gt;

\[\mathbb{E}[X] = \int x f(x)\,dx\]

&lt;p&gt;The expectation is not necessarily the value we observe most often directly. It is the “probability center of mass” of the distribution.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/expectation_center_histogram.png&quot; alt=&quot;Expectation as the center of mass of a distribution&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1a: The expectation can be seen as the center of mass of the distribution, not necessarily the highest peak of the histogram.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-variance-uncertainty-around-the-mean&quot;&gt;2) Variance: uncertainty around the mean&lt;/h2&gt;

\[\mathrm{Var}(X)=\mathbb{E}\big[(X-\mathbb{E}[X])^2\big]\]

&lt;p&gt;Rewritten in a quick-computation form:&lt;/p&gt;

\[\mathrm{Var}(X)=\mathbb{E}[X^2]-\mathbb{E}[X]^2\]

&lt;p&gt;The standard deviation is:&lt;/p&gt;

\[\mathrm{SD}(X)=\sqrt{\mathrm{Var}(X)}\]

&lt;p&gt;Intuitively, a large variance shows that the data is widely spread, while a small variance shows that the data is more concentrated around the mean.&lt;/p&gt;

&lt;h2 id=&quot;3-covariance-the-relationship-of-co-variation&quot;&gt;3) Covariance: the relationship of co-variation&lt;/h2&gt;

&lt;p&gt;For two variables \(X, Y\):&lt;/p&gt;

\[\mathrm{Cov}(X,Y)=\mathbb{E}\big[(X-\mathbb{E}[X])(Y-\mathbb{E}[Y])\big]\]

&lt;p&gt;When \(\mathrm{Cov}&amp;gt;0\), the two variables tend to increase together; when \(\mathrm{Cov}&amp;lt;0\), when one variable increases the other usually decreases; and when the covariance is near 0, the linear relationship between them is weak or almost negligible.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/covariance_positive_scatter.png&quot; alt=&quot;Positive covariance between two variables&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1b: Positive covariance appears when two variables tend to increase together.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/covariance_negative_scatter.png&quot; alt=&quot;Negative covariance between two variables&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1c: Negative covariance appears when one variable increases and the other tends to decrease.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Note: covariance depends on the unit of measurement. So in practice we usually use correlation:&lt;/p&gt;

\[\rho_{XY}=\frac{\mathrm{Cov}(X,Y)}{\mathrm{SD}(X)\mathrm{SD}(Y)}\]

&lt;h3 id=&quot;31-a-very-short-decision-example&quot;&gt;3.1) A very short decision example&lt;/h3&gt;

&lt;p&gt;Suppose there are two bus routes that both have an expected commute time of 30 minutes.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Route A has typical times around \(28, 30, 32\) minutes.&lt;/li&gt;
  &lt;li&gt;Route B has typical times around \(20, 30, 40\) minutes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The two routes can have the same expectation, but route B has a much larger variance, so the risk of being late is also clearly higher. If in addition we see that on heavy-rain days the commute time also rises sharply, we are describing a positive covariance between rainfall and travel time. This example reminds us that looking at the mean alone is not enough; real decisions often depend on both the spread and how the variables co-vary.&lt;/p&gt;

&lt;h2 id=&quot;4-properties-to-remember&quot;&gt;4) Properties to remember&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
\[\mathbb{E}[aX+b]=a\mathbb{E}[X]+b\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathrm{Var}(aX+b)=a^2\mathrm{Var}(X)\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathrm{Var}(X+Y)=\mathrm{Var}(X)+\mathrm{Var}(Y)+2\mathrm{Cov}(X,Y)\]
  &lt;/li&gt;
  &lt;li&gt;If \(X,Y\) are independent then \(\mathrm{Cov}(X,Y)=0\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Property (4) goes only one way: zero covariance does not necessarily mean independence.&lt;/p&gt;

&lt;h2 id=&quot;5-connection-to-bayes&quot;&gt;5) Connection to Bayes&lt;/h2&gt;

&lt;p&gt;In Bayesian inference, the posterior mean is exactly the expectation under the posterior, the uncertainty is usually reported as the posterior SD or posterior variance, and when there are many parameters the covariance matrix tells the degree of dependence between those parameters.&lt;/p&gt;

&lt;p&gt;In other words, learning Bayes without being sure of expectation/variance/covariance makes it hard to interpret results.&lt;/p&gt;

&lt;h2 id=&quot;quick-summary&quot;&gt;Quick summary&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Expectation is the mean under a distribution.&lt;/li&gt;
  &lt;li&gt;Variance measures the spread around the mean.&lt;/li&gt;
  &lt;li&gt;Covariance measures the same-direction/opposite-direction co-variation of two variables.&lt;/li&gt;
  &lt;li&gt;These three quantities are the basic language for interpreting the posterior.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-computing-expectation-variance-and-covariance-by-hand&quot;&gt;Worked Numerical Example: Computing Expectation, Variance, and Covariance by Hand&lt;/h3&gt;

&lt;p&gt;Suppose two investments \((X, Y)\) have 3 equally likely market scenarios (each probability \(1/3\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Scenario&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Probability&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Return \(X\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Return \(Y\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(X + Y\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Boom&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1/3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+6\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+4\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Flat&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1/3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bust&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1/3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-6\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(+2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(-4\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Means:&lt;/strong&gt; \(\mathbb{E}[X] = 0\), \(\mathbb{E}[Y] = 0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Variances:&lt;/strong&gt;
\(\mathrm{Var}(X) = \frac{36 + 0 + 36}{3} = 24, \qquad \mathrm{Var}(Y) = \frac{4 + 0 + 4}{3} = \frac{8}{3} \approx 2.67.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Covariance:&lt;/strong&gt;
\(\mathrm{Cov}(X, Y) = \mathbb{E}[XY] - 0 = \frac{6(-2) + 0 + (-6)(2)}{3} = \frac{-24}{3} = \mathbf{-8}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify the Variance Sum Law:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Via formula: \(\mathrm{Var}(X+Y) = 24 + \frac{8}{3} + 2(-8) = 8 + \frac{8}{3} = \frac{32}{3} \approx \mathbf{10.67}\).&lt;/li&gt;
      &lt;li&gt;Directly from column \(X+Y = (+4, 0, -4)\): \(\frac{16 + 0 + 16}{3} = \frac{32}{3} \approx \mathbf{10.67}\) — exact match! Negative covariance cut the variance of \(X\) by more than half!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-working-with-expectations-and-covariance&quot;&gt;Explanation: Four Rules for Working With Expectations and Covariance&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Zero covariance does NOT prove independence:&lt;/strong&gt; If \(X \in \{-1, 0, 1\}\) symmetrically and \(Y = X^2\), then \(\mathrm{Cov}(X, Y) = 0\) even though \(Y\) is 100% determined by \(X\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never add standard deviations—add &lt;em&gt;variances&lt;/em&gt; (plus \(2\mathrm{Cov}\)):&lt;/strong&gt; Adding \(\sigma_X + \sigma_Y\) overestimates uncertainty whenever variables are independent or negatively correlated.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;In Bayesian regression, slope \(\beta_1\) and intercept \(\beta_0\) are almost always negatively correlated:&lt;/strong&gt; Shifting the regression line up forces it to tilt flatter unless you &lt;strong&gt;center&lt;/strong&gt; predictors (\(x_i - \bar{x}\)), which drives \(\mathrm{Cov}(\beta_0, \beta_1) \to 0\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Monte Carlo turns any expectation into a simple average:&lt;/strong&gt; Once you have \(S\) posterior draws \(\theta^{(1)},\dots,\theta^{(S)}\), \(\mathbb{E}[g(\theta)\mid y] \approx \frac{1}{S}\sum g(\theta^{(s)})\) works for &lt;em&gt;any&lt;/em&gt; nonlinear function \(g\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the 3-scenario example above, what is the exact correlation \(ho(X, Y) = \frac{\mathrm{Cov}(X,Y)}{\sqrt{\mathrm{Var}(X)\mathrm{Var}(Y)}}\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KLs_7b7SKi4&quot;&gt;Expected Values, Main Ideas!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch expectation as the long-run average of a random variable, exactly the opening definition of the lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qtaqvPAeEJY&quot;&gt;Covariance, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch what positive, negative and zero covariance mean, supporting the part on two variables moving in the same or opposite directions.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vikkiwjQqfU&quot;&gt;Population and Estimated Parameters, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch the difference between population parameters and estimates from a sample, used where the lesson connects expectation to sample variance.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Why isn’t the expectation always at the peak of the distribution?&lt;/li&gt;
  &lt;li&gt;Give an example of two variables with negative covariance in everyday life.&lt;/li&gt;
  &lt;li&gt;Why is zero covariance not enough to conclude independence?&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Wasserman, L. (2004). &lt;em&gt;All of Statistics&lt;/em&gt;. Springer.&lt;/li&gt;
  &lt;li&gt;McElreath, R. (2020). &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.). CRC Press.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_14_law_large_numbers_clt/&quot;&gt;0.16 The Law of Large Numbers and the Central Limit Theorem&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.14: What is a Statistical Model?</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_12_statistical_model_definition/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_12_statistical_model_definition</id>
   <content type="html">&lt;p&gt;What actually &lt;em&gt;is&lt;/em&gt; a statistical model? It is not a black-box &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.fit()&lt;/code&gt; call—it is a &lt;strong&gt;mathematical story of how your data could have been generated!&lt;/strong&gt; In Bayesian statistics, writing down a statistical model means specifying two clean ingredients: a &lt;strong&gt;data-generating process&lt;/strong&gt; \(p(y\mid\theta)\) (how observable measurements emerge given hidden parameters) and a &lt;strong&gt;prior&lt;/strong&gt; \(p(\theta)\) (what parameter values are plausible before seeing data).&lt;/p&gt;

&lt;p&gt;This lesson teaches you to read and write generative statistical models fluently, separate &lt;strong&gt;parameters&lt;/strong&gt; from &lt;strong&gt;data&lt;/strong&gt; and &lt;strong&gt;hyperparameters&lt;/strong&gt;, and simulate synthetic data forward before ever fitting real observations.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-anatomy-of-a-generative-statistical-model&quot;&gt;Key ideas: The Anatomy of a Generative Statistical Model&lt;/h2&gt;

&lt;p&gt;Four elements define every Bayesian statistical model you will build in this course:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Data-Generating Story (Likelihood \(p(y\mid\theta)\)):&lt;/strong&gt; A family of probability distributions indexed by unknown parameter(s) \(\theta\) describing how noise and signal combine to produce observations \(y\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prior Distribution \(p(\theta\mid\phi)\):&lt;/strong&gt; Encodes domain constraints and plausible scales for \(\theta\), controlled by fixed &lt;strong&gt;hyperparameters&lt;/strong&gt; \(\phi\) (or learned hyperpriors in hierarchical models).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Forward Simulation (Prior Predictive):&lt;/strong&gt; Because a Bayesian model is fully generative, you can sample \(\theta \sim p(\theta)\) and then \(y_{\text{sim}} \sim p(y\mid\theta)\) &lt;em&gt;before&lt;/em&gt; touching real data—catching absurd priors immediately (like predicting negative human heights!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;All Models Are Wrong, Some Are Useful (George Box):&lt;/strong&gt; A statistical model is a deliberate simplification; its value is judged by how well it explains observed structure, quantifies uncertainty, and predicts new observations.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will understand a practical definition of a statistical model as a probability description of how data are generated, distinguish observed data from unknown parameters, and see why asking “what assumptions does this model make?” matters more than memorizing formulas.&lt;/p&gt;

&lt;h2 id=&quot;1-motivation-data-do-not-speak-without-a-model&quot;&gt;1) Motivation: Data do not speak without a model&lt;/h2&gt;

&lt;p&gt;From a dataset, we can compute means, standard deviations, and histograms. But those summaries alone do not answer inference questions such as:&lt;/p&gt;

&lt;p&gt;What the true population rate is, whether an effect is large enough to matter, or how uncertain future predictions are.&lt;/p&gt;

&lt;p&gt;To answer these, we need a bridge from “unknown parameter” to “observable data.” That bridge is a statistical model.&lt;/p&gt;

&lt;h2 id=&quot;2-core-definition&quot;&gt;2) Core definition&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;statistical model&lt;/strong&gt; is a family of probability distributions for data \(x\), indexed by parameter(s) \(\theta\):&lt;/p&gt;

\[\mathcal{M} = \{p(x\mid \theta): \theta \in \Theta\}\]

&lt;p&gt;Here, \(x\) denotes observed data, \(\theta\) is the unknown quantity governing the data-generating mechanism, and \(\Theta\) is the parameter space, that is, the set of valid values of \(\theta\).&lt;/p&gt;

&lt;p&gt;In short: a statistical model encodes “if parameters look like this, data tend to look like that.”&lt;/p&gt;

&lt;h2 id=&quot;3-generative-story-view&quot;&gt;3) Generative-story view&lt;/h2&gt;

&lt;p&gt;In this course, we use a generative interpretation: first imagine some unknown parameter value \(\theta\), then generate data \(x\) from \(p(x\mid\theta)\), and finally compare the observed data with what the model would expect under plausible values of \(\theta\).&lt;/p&gt;

&lt;p&gt;Coin example:&lt;/p&gt;

&lt;p&gt;In the coin example, \(\theta\) is the probability of heads, each toss produces an observation \(y_i \sim \text{Bernoulli}(\theta)\), and after \(n\) tosses the total number of heads \(k=\sum_i y_i\) follows \(\text{Binomial}(n,\theta)\).&lt;/p&gt;

&lt;p&gt;The model is not only the binomial formula. It also assumes that each trial has the same \(\theta\), that trials are independent, and that the data are counts arising from repeated trials under a common mechanism.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/statistical_model_definition_flow.png&quot; alt=&quot;Statistical model as bridge from parameters to data&quot; /&gt;
&lt;em&gt;Figure 1: A statistical model links unknown parameters \(\theta\) to observed data \(x\) through the data-generating mechanism \(p(x\mid\theta)\), then updates beliefs to posterior \(p(\theta\mid x)\).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;31-how-are-models-and-simulations-different&quot;&gt;3.1) How are models and simulations different?&lt;/h2&gt;

&lt;p&gt;These two ideas are easy to mix up, but they play different roles: a model is a probability description of the data-generating mechanism, while a simulation is what happens when we run that description on a computer to generate fake data many times.&lt;/p&gt;

&lt;p&gt;Coin example:&lt;/p&gt;

&lt;p&gt;The model says each toss satisfies \(y_i\sim\text{Bernoulli}(\theta)\). A simulation chooses a specific value such as \(\theta=0.6\) and then generates many repeated datasets to see how the proportion of heads varies.&lt;/p&gt;

&lt;p&gt;Short Python simulation example:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n_tosses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n_simulations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10_000&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;heads_counts&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_tosses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_simulations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;head_rates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;heads_counts&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_tosses&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heads_counts&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;head_rates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;head_rates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In this code, the model is still \(K \sim \text{Binomial}(20, 0.6)\). The simulation simply asks: if that model were true, how many heads would we usually see in 20 tosses, and how much variation would appear across repetitions?&lt;/p&gt;

&lt;p&gt;After many repetitions, the average of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;head_rates&lt;/code&gt; will be close to 0.6, but individual simulated datasets still vary around that value. That is the key point: a model does not imply one fixed outcome, but a distribution of plausible outcomes.&lt;/p&gt;

&lt;h2 id=&quot;4-a-model-is-not-the-truth&quot;&gt;4) A model is not “the truth”&lt;/h2&gt;

&lt;p&gt;A common mistake is to search for a perfectly true model. In practice:&lt;/p&gt;

&lt;p&gt;A model is a map rather than the territory, every model necessarily simplifies reality, and its value comes from how well it supports prediction, explanation, and decision-making.&lt;/p&gt;

&lt;p&gt;So whenever we model, we ask:&lt;/p&gt;

&lt;p&gt;We should therefore ask which assumptions are being imposed, whether those assumptions fit the context, and how our conclusions could fail if those assumptions are wrong.&lt;/p&gt;

&lt;h2 id=&quot;5-direct-link-to-bayesian-inference&quot;&gt;5) Direct link to Bayesian inference&lt;/h2&gt;

&lt;p&gt;In Bayesian analysis, the model appears through the likelihood:&lt;/p&gt;

\[p(\theta\mid x) \propto p(x\mid\theta)\,p(\theta)\]

&lt;p&gt;Here:&lt;/p&gt;

&lt;p&gt;The term \(p(x\mid\theta)\) comes from the statistical model, \(p(\theta)\) is the prior, and the posterior \(p(\theta\mid x)\) is the updated belief after seeing the data.&lt;/p&gt;

&lt;p&gt;If the model is unclear, the likelihood is unclear, and the posterior loses interpretability.&lt;/p&gt;

&lt;h2 id=&quot;6-mini-example-student-heights&quot;&gt;6) Mini example: student heights&lt;/h2&gt;

&lt;p&gt;Suppose \(x_1,\dots,x_n\) are student heights (cm). A simple model is:&lt;/p&gt;

\[x_i \sim \mathcal{N}(\mu,\sigma^2),\quad i=1,\dots,n\]

&lt;p&gt;where \(\mu\) is class-average height and \(\sigma\) is spread.&lt;/p&gt;

&lt;p&gt;This model implicitly assumes approximately normal data, conditional independence given the parameters, and a shared data-generating process across observations.&lt;/p&gt;

&lt;p&gt;With this model, we can estimate and interpret \(\mu, \sigma\), make predictions, and check whether the model is missing important structure.&lt;/p&gt;

&lt;h3 id=&quot;61-a-very-short-example-same-data-idea-different-model-story&quot;&gt;6.1) A very short example: same data idea, different model story&lt;/h3&gt;

&lt;p&gt;Suppose the data are not heights but the number of support calls arriving each hour: \(0, 1, 3, 2, 4, \dots\). For this kind of data, a Poisson model usually tells a more sensible story because it respects the counting structure and only produces nonnegative predictions. If we force a Normal model onto the same setting, we may still get a mean and a variance, but the model also quietly allows negative predicted counts that make no practical sense.&lt;/p&gt;

&lt;p&gt;The key point is that choosing a model is not just choosing a convenient formula. It is choosing a story about how the data are generated, and that story determines which conclusions become reasonable.&lt;/p&gt;

&lt;h2 id=&quot;quick-recap&quot;&gt;Quick recap&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;A statistical model is a family \(\{p(x\mid\theta)\}\) for data.&lt;/li&gt;
  &lt;li&gt;It links unknown parameters to observed data via a generative mechanism.&lt;/li&gt;
  &lt;li&gt;Every model carries assumptions; understanding assumptions is central.&lt;/li&gt;
  &lt;li&gt;In Bayes, the model provides the likelihood that updates prior to posterior.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-checking-a-generative-normal-model-via-prior-predictive-variance&quot;&gt;Worked Numerical Example: Checking a Generative Normal Model via Prior Predictive Variance&lt;/h3&gt;

&lt;p&gt;Suppose you model exam scores \(Y\) with known measurement noise \(\sigma = 10\) and an uncertain class mean \(\mu\):&lt;/p&gt;

\[\mu \sim \mathcal{N}(70,\; 5^2), \qquad Y \mid \mu \sim \mathcal{N}(\mu,\; 10^2).\]

&lt;p&gt;What distribution does a single &lt;em&gt;future&lt;/em&gt; score \(Y\) follow before seeing any data (&lt;strong&gt;Prior Predictive&lt;/strong&gt;)? Write \(Y = \mu + \varepsilon\) where \(\mu \sim \mathcal{N}(70, 25)\) and \(\varepsilon \sim \mathcal{N}(0, 100)\) are independent:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Prior predictive mean:&lt;/strong&gt; \(\mathbb{E}[Y] = 70 + 0 = 70\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prior predictive variance (variances of independent sources add!):&lt;/strong&gt;
\(\mathrm{Var}(Y) = \mathrm{Var}(\mu) + \mathrm{Var}(\varepsilon) = 5^2 + 10^2 = 25 + 100 = 125 \implies \mathrm{SD}(Y) = \sqrt{125} \approx \mathbf{11.18}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;95% Prior Predictive Range:&lt;/strong&gt; \(70 \pm 1.96(11.18) = [48.1,\; 91.9]\)—completely sensible for a 0–100 exam! &lt;em&gt;(Whereas a lazy “flat” prior \(\mu \sim \mathcal{N}(70, 1000^2)\) would predict exam scores from \(-1890\) to \(+2030\)!)&lt;/em&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-specifying-clean-statistical-models&quot;&gt;Explanation: Four Rules for Specifying Clean Statistical Models&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always write the model in mathematical notation before writing code:&lt;/strong&gt; Two lines like \(\mu \sim \mathcal{N}(70, 5^2); \; y_i \mid \mu \sim \mathcal{N}(\mu, 10^2)\) clarify every assumption in seconds.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Distinguish epistemic uncertainty (about \(\theta\)) from aleatoric noise (about \(Y\mid\theta\)):&lt;/strong&gt; Collecting more data shrinks \(\mathrm{Var}(\mu\mid y) \to 0\), but never shrinks \(\sigma^2 = 100\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Run prior predictive checks on every new model:&lt;/strong&gt; Simulating fake datasets from your prior instantly flags scale mistakes before you waste time running MCMC.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Start simple and expand iteratively:&lt;/strong&gt; Begin with a minimal baseline model (e.g., Normal or Binomial), check where its predictions fail real data, and only then add hierarchy or heavy tails.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the exam model above, if you knew the class mean \(\mu = 70\) with 100% certainty (\(\mathrm{SD}(\mu) = 0\)), what would the predictive standard deviation of a new student’s score \(Y\) be?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=3d5ivs_8amQ&quot;&gt;What is a statistical model?&lt;/a&gt; — Very Normal, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch a statistical model defined as a probability story for how data are generated, the practical definition in this lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=FdnMWdICdRs&quot;&gt;Statistical Rethinking 2023 - 01 - The Golem of Prague&lt;/a&gt; — Richard McElreath, English. Watch the argument that a model is a tool that must be supervised, supporting the lesson’s focus on assumptions.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kn8fyNzvcPo&quot;&gt;Regression and Other Stories: Generative models and statistical inference (ros02 4)&lt;/a&gt; — Data Science Learning Community Videos, English. Watch generative models set next to statistical inference, useful for separating observed data from unknown parameters.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;For the coin example, list three implicit assumptions of the binomial model.&lt;/li&gt;
  &lt;li&gt;Give one context where the independence assumption is likely violated.&lt;/li&gt;
  &lt;li&gt;Explain in your own words: “A model is a map, not the territory.”&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;McElreath, R. (2020). &lt;em&gt;Statistical Rethinking&lt;/em&gt; (2nd ed.). CRC Press.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.). CRC Press.&lt;/li&gt;
  &lt;li&gt;Wasserman, L. (2004). &lt;em&gt;All of Statistics&lt;/em&gt;. Springer.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.13: Joint Distributions</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_11_joint_distribution/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_11_joint_distribution</id>
   <content type="html">&lt;p&gt;Every Bayesian model is secretly just one thing: &lt;strong&gt;a joint probability distribution \(p(\theta, y)\) over unknown parameters \(\theta\) and observable data \(y\)!&lt;/strong&gt; Once you specify that single joint surface—by multiplying a prior \(p(\theta)\) with a likelihood \(p(y\mid\theta)\)—every operation in Bayesian statistics is simply slicing it (&lt;strong&gt;conditioning&lt;/strong&gt; to get the posterior) or summing across one axis (&lt;strong&gt;marginalizing&lt;/strong&gt; to get the evidence or predictive distribution).&lt;/p&gt;

&lt;p&gt;This lesson builds concrete fluency with joint, marginal, and conditional distributions so you can visualize Bayes’ theorem as literally slicing a 2D probability table or surface and re-normalizing the slice to sum to 1.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-three-operations-on-any-joint-distribution&quot;&gt;Key ideas: The Three Operations on Any Joint Distribution&lt;/h2&gt;

&lt;p&gt;Three mechanical operations govern every multi-variable probability model:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Joint Distribution \(p(x, y)\):&lt;/strong&gt; Encodes &lt;em&gt;all&lt;/em&gt; information about both variables simultaneously, including how they co-vary; sums (or integrates) to 1 over the entire 2D grid.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Marginalization (Summing/Integrating Out a Nuisance Variable):&lt;/strong&gt; \(p(x) = \sum_y p(x, y)\) collapses a 2D table onto one axis—the exact mechanism used in Bayesian inference to integrate out nuisance parameters (like unknown variance \(\sigma^2\)) or compute model evidence \(p(y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Conditioning (Slicing &amp;amp; Renormalizing):&lt;/strong&gt; Fixing \(X = x\) slices one row/column out of the joint distribution and divides by its marginal total: \(p(y\mid x) = \frac{p(x, y)}{p(x)}\)—which is &lt;strong&gt;literally Bayes’ theorem&lt;/strong&gt; when \(x\) is observed data and \(y\) is the parameter!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will understand that a joint distribution is the natural extension of one-variable distributions to multiple variables, how to derive marginals and conditionals from the joint, and why this structure is the direct foundation of Bayesian inference.&lt;/p&gt;

&lt;h2 id=&quot;1-motivation-one-variable-is-often-not-enough&quot;&gt;1) Motivation: One variable is often not enough&lt;/h2&gt;

&lt;p&gt;In previous lessons, we used one-variable distributions:&lt;/p&gt;

&lt;p&gt;For the discrete case, we wrote \(p(x)=P(X=x)\); for the continuous case, we wrote \(f(x)\) and interpreted probability through the integral \(P(a\le X\le b)=\int_a^b f(x)\,dx\).&lt;/p&gt;

&lt;p&gt;That is a one-dimensional view. Now we extend to two dimensions (and in general, many dimensions): from \(p(x)\) or \(f(x)\) to \(p(x,y)\) or \(f(x,y)\). So joint distributions are not a separate idea; they are a &lt;strong&gt;direct multivariable extension of distribution functions&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/bayesian-statistics-self-learning/img/chapter_img/chapter00/joint_distribution_marginalization.png&quot; alt=&quot;Extension from one variable to multiple variables&quot; /&gt;
&lt;em&gt;Figure 1: Extension from a one-variable distribution to a two-variable joint distribution. Center: joint density \(f(x,y)\). Top/right: marginals obtained by integrating along the other axis. The dashed horizontal slice illustrates a conditional distribution.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In practice, we usually care about several variables at once. For example:&lt;/p&gt;

&lt;p&gt;We may care simultaneously about height \(H\) and weight \(W\), about study time \(T\) and exam score \(S\), or about disease status \(D\) together with test result \(X\).&lt;/p&gt;

&lt;p&gt;If we model variables separately, we can miss their relationship. Joint distributions answer questions like: “what is the probability that &lt;strong&gt;both&lt;/strong&gt; \(H\) falls in this range and \(W\) falls in that range?”&lt;/p&gt;

&lt;h2 id=&quot;2-definition-of-a-joint-distribution&quot;&gt;2) Definition of a joint distribution&lt;/h2&gt;

&lt;h3 id=&quot;21-discrete-case&quot;&gt;2.1 Discrete case&lt;/h3&gt;

&lt;p&gt;For discrete variables \(X, Y\), the joint distribution is:&lt;/p&gt;

\[p(x,y) = P(X=x, Y=y)\]

&lt;p&gt;For this to be valid, we need \(p(x,y) \ge 0\) for all \(x,y\) and the double sum \(\sum_x\sum_y p(x,y)=1\).&lt;/p&gt;

&lt;p&gt;Here, \(p(x,y)\) is the probability that both variables take specific values simultaneously.&lt;/p&gt;

&lt;h3 id=&quot;22-continuous-case&quot;&gt;2.2 Continuous case&lt;/h3&gt;

&lt;p&gt;For continuous variables \(X, Y\), we use a joint density:&lt;/p&gt;

\[f(x,y)\]

&lt;p&gt;such that:&lt;/p&gt;

\[P((X,Y)\in A)=\iint_A f(x,y)\,dx\,dy\]

&lt;p&gt;and:&lt;/p&gt;

\[\iint_{\mathbb{R}^2} f(x,y)\,dx\,dy=1\]

&lt;p&gt;As with one-dimensional PDFs, \(f(x,y)\) is not a point probability; it is a density over the plane.&lt;/p&gt;

&lt;h2 id=&quot;3-from-joint-to-marginal&quot;&gt;3) From joint to marginal&lt;/h2&gt;

&lt;p&gt;Marginal distributions describe one variable after “summing out” or integrating out the other. In the discrete case, we have:&lt;/p&gt;

\[p_X(x)=\sum_y p(x,y),\qquad p_Y(y)=\sum_x p(x,y)\]

&lt;p&gt;In the continuous case, the corresponding formulas are:&lt;/p&gt;

\[f_X(x)=\int_{-\infty}^{\infty} f(x,y)\,dy,\qquad f_Y(y)=\int_{-\infty}^{\infty} f(x,y)\,dx\]

&lt;p&gt;Intuition: a marginal is accumulated mass/density along the other axis.&lt;/p&gt;

&lt;h2 id=&quot;4-conditional-distributions-and-product-rule&quot;&gt;4) Conditional distributions and product rule&lt;/h2&gt;

&lt;p&gt;When \(Y=y\) is known, the conditional distribution of \(X\) is:&lt;/p&gt;

\[p(x\mid y)=\frac{p(x,y)}{p_Y(y)}\]

&lt;p&gt;(discrete form; continuous uses the corresponding densities).&lt;/p&gt;

&lt;p&gt;This gives the product rule:&lt;/p&gt;

\[p(x,y)=p(x\mid y)p_Y(y)=p(y\mid x)p_X(x)\]

&lt;p&gt;This is also the core mechanism behind Bayes:&lt;/p&gt;

\[p(\theta\mid x)=\frac{p(x\mid\theta)p(\theta)}{p(x)}\]

&lt;p&gt;with the key joint relationship:&lt;/p&gt;

\[p(\theta,x)=p(x\mid\theta)p(\theta)\]

&lt;h2 id=&quot;5-independence-vs-dependence&quot;&gt;5) Independence vs dependence&lt;/h2&gt;

&lt;p&gt;Variables \(X, Y\) are independent if and only if:&lt;/p&gt;

\[p(x,y)=p_X(x)p_Y(y)\]

&lt;p&gt;for all \(x,y\) (or \(f(x,y)=f_X(x)f_Y(y)\) in the continuous case).&lt;/p&gt;

&lt;p&gt;If this identity holds, knowing \(Y\) does not change our beliefs about \(X\); if it fails, one variable carries information about the other.&lt;/p&gt;

&lt;p&gt;Most interesting Bayesian models exploit dependence structure.&lt;/p&gt;

&lt;h2 id=&quot;6-short-discrete-example&quot;&gt;6) Short discrete example&lt;/h2&gt;

&lt;p&gt;Suppose:&lt;/p&gt;

&lt;p&gt;Let \(X \in \{0,1\}\) indicate whether a student attends class, and let \(Y \in \{0,1\}\) indicate whether that student passes.&lt;/p&gt;

&lt;p&gt;with joint table:&lt;/p&gt;

\[\begin{array}{c|cc}
 &amp;amp; y=0 &amp;amp; y=1 \\
\hline
x=0 &amp;amp; 0.30 &amp;amp; 0.10 \\
x=1 &amp;amp; 0.15 &amp;amp; 0.45
\end{array}\]

&lt;p&gt;As a quick check, the total probability is 1. We also get \(p_X(1)=0.15+0.45=0.60\), \(p_Y(1)=0.10+0.45=0.55\), and \(p(Y=1\mid X=1)=0.45/0.60=0.75\).&lt;/p&gt;

&lt;p&gt;Since \(0.75 \ne 0.55\), knowing \(X=1\) changes the probability of passing, so the variables are dependent.&lt;/p&gt;

&lt;h3 id=&quot;61-reading-the-story-from-the-table&quot;&gt;6.1) Reading the story from the table&lt;/h3&gt;

&lt;p&gt;If we translate the table into 100 students, we can read it in a very concrete way:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;45 students attend and pass&lt;/li&gt;
  &lt;li&gt;15 attend but do not pass&lt;/li&gt;
  &lt;li&gt;10 do not attend but still pass&lt;/li&gt;
  &lt;li&gt;30 neither attend nor pass&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;From this, the pass rate in the attending group is \(45/(45+15)=75\%\), while in the non-attending group it is only \(10/(10+30)=25\%\). This makes the point tangible: a joint distribution is not just a symbolic table, but a compact way to describe how two variables move together in an interpretable story.&lt;/p&gt;

&lt;h2 id=&quot;7-bayesian-connection-in-practice&quot;&gt;7) Bayesian connection in practice&lt;/h2&gt;

&lt;p&gt;In Bayesian modeling, we repeatedly use:&lt;/p&gt;

\[p(\theta, x)=p(x\mid\theta)p(\theta)\]

&lt;p&gt;Then marginalize over \(\theta\) to get evidence:&lt;/p&gt;

\[p(x)=\int p(x\mid\theta)p(\theta)\,d\theta\]

&lt;p&gt;and normalize to obtain the posterior:&lt;/p&gt;

\[p(\theta\mid x)=\frac{p(x\mid\theta)p(\theta)}{p(x)}\]

&lt;p&gt;So mastering joint, marginal, and conditional distributions is essential before deeper Bayesian inference.&lt;/p&gt;

&lt;h2 id=&quot;quick-recap&quot;&gt;Quick recap&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;A joint distribution models multiple variables simultaneously.&lt;/li&gt;
  &lt;li&gt;Marginals come from summing/integrating the joint.&lt;/li&gt;
  &lt;li&gt;Conditionals come from dividing joint by marginal.&lt;/li&gt;
  &lt;li&gt;Product rule links joint and conditional: \(p(x,y)=p(x\mid y)p(y)\).&lt;/li&gt;
  &lt;li&gt;Independence is exactly \(p(x,y)=p(x)p(y)\).&lt;/li&gt;
  &lt;li&gt;Bayes is built directly on joint-marginal-conditional relationships.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-slicing-and-marginalizing-a-2times-2-joint-table&quot;&gt;Worked Numerical Example: Slicing and Marginalizing a \(2\times 2\) Joint Table&lt;/h3&gt;

&lt;p&gt;Consider a joint distribution over &lt;strong&gt;Weather&lt;/strong&gt; (\(W \in \{\text{Rain}, \text{Dry}\}\)) and &lt;strong&gt;Traffic&lt;/strong&gt; (\(T \in \{\text{Jam}, \text{Clear}\}\)) summing to \(1.00\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Weather \ Traffic&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Jam (\(T=1\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Clear (\(T=0\))&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Marginal \(P(W)\)&lt;/strong&gt;&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Rain (\(W=1\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.24\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.06\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.30\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Dry (\(W=0\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.16\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.54\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.70\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Marginal \(P(T)\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.40\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.60\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(1.00\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Check independence:&lt;/strong&gt; \(P(W=1)\cdot P(T=1) = 0.30 \times 0.40 = 0.12 \neq 0.24\) \(\implies\) Rain and Traffic Jam are strongly &lt;strong&gt;dependent&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Condition on observing a Traffic Jam (\(T=1\)):&lt;/strong&gt; Slice the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Jam&lt;/code&gt; column &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0.24, 0.16]&lt;/code&gt; and divide by its marginal sum \(0.40\):
\(P(\text{Rain} \mid \text{Jam}) = \frac{0.24}{0.40} = \mathbf{0.60}, \qquad P(\text{Dry} \mid \text{Jam}) = \frac{0.16}{0.40} = \mathbf{0.40}.\)
Before looking out the window, your prior probability of Rain was \(30\%\); seeing a Traffic Jam updated your posterior probability of Rain to &lt;strong&gt;\(60\%\)&lt;/strong&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-thinking-in-joint-distributions&quot;&gt;Explanation: Four Rules for Thinking in Joint Distributions&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bayes’ rule is not a separate axiom—it is just two ways to factor the same joint:&lt;/strong&gt; \(p(\theta, y) = p(y\mid\theta)p(\theta) = p(\theta\mid y)p(y)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Marginalizing preserves uncertainty honestly:&lt;/strong&gt; Instead of plugging in a single point estimate for a nuisance parameter \(\sigma\), Bayesian inference integrates over the joint \(p(\mu, \sigma \mid y)\) so uncertainty in \(\sigma\) widens your credible interval for \(\mu\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check whether a table sums to 1 before interpreting entries:&lt;/strong&gt; A table of &lt;em&gt;conditional&lt;/em&gt; probabilities \(P(T\mid W)\) sums to 1 along each row, whereas a &lt;em&gt;joint&lt;/em&gt; table \(P(W, T)\) sums to 1 across all cells combined!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Independence is a fragile special case:&lt;/strong&gt; Only when \(p(x,y) = p(x)p(y)\) for &lt;em&gt;every&lt;/em&gt; cell can you multiply marginals; in hierarchical Bayesian models, sharing a group parameter intentionally creates dependence across observations.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Using the Weather–Traffic joint table above, if you observe that traffic is &lt;strong&gt;Clear&lt;/strong&gt; (\(T = 0\)), what is the posterior probability \(P(\text{Rain} \mid \text{Clear})\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pribJ8bUBzo&quot;&gt;Joint Probability Distributions: Marginal and Conditional Densities&lt;/a&gt; — Steve Brunton, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch joint densities split into marginals and conditionals, the three operations this lesson uses as the base of Bayes.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Marginal distribution and conditional distribution&lt;/td&gt;
          &lt;td&gt;AP Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=CAXQvTKP8sg) — Khan Academy, English. Watch the discrete table version of marginal and conditional distributions before the lesson moves to densities.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qtaqvPAeEJY&quot;&gt;Covariance, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch covariance as a summary of a joint distribution, supporting the lesson’s section on dependence.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1.&lt;/strong&gt; Using the table in Section 6, compute:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
\[p_X(0), p_X(1)\]
  &lt;/li&gt;
  &lt;li&gt;
\[p_Y(0), p_Y(1)\]
  &lt;/li&gt;
  &lt;li&gt;\(p(X=1\mid Y=1)\) and \(p(Y=1\mid X=1)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2.&lt;/strong&gt; Prove from definitions that:&lt;/p&gt;

\[p(x,y)=p(x\mid y)p(y)=p(y\mid x)p(x)\]

&lt;p&gt;&lt;strong&gt;Exercise 3.&lt;/strong&gt; Let two continuous variables have joint density \(f(x,y)=c(x+y)\) on \(0&amp;lt;x&amp;lt;1, 0&amp;lt;y&amp;lt;1\) and 0 elsewhere.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Find the constant \(c\) so that \(f\) is valid.&lt;/li&gt;
  &lt;li&gt;Derive \(f_X(x)\) and \(f_Y(y)\).&lt;/li&gt;
  &lt;li&gt;Check whether \(X, Y\) are independent.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Wasserman, L. (2004). &lt;em&gt;All of Statistics&lt;/em&gt;. Springer.&lt;/li&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.). CRC Press.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. (2015). &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.). Academic Press.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.10b: Introduction to the Gamma Function</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_10_gamma_function_intro/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_10_gamma_function_intro</id>
   <content type="html">&lt;p&gt;What is \(2.5!\)? You can’t multiply “2.5 integers in a row,” yet in 1729 Leonhard Euler discovered a smooth, analytic curve—the &lt;strong&gt;Gamma function \(\Gamma(z)\)&lt;/strong&gt;—that passes through every factorial \((n-1)!\) and fills in every real and half-integer value in between! Far from being a pure-math curiosity, \(\Gamma(z)\) is the exact normalizing glue holding together the &lt;strong&gt;Beta&lt;/strong&gt;, &lt;strong&gt;Gamma&lt;/strong&gt;, &lt;strong&gt;Chi-squared&lt;/strong&gt;, &lt;strong&gt;Dirichlet&lt;/strong&gt;, and &lt;strong&gt;Student-\(t\)&lt;/strong&gt; distributions across all of Bayesian statistics.&lt;/p&gt;

&lt;p&gt;This lesson strips the mystery off \(\Gamma(z)\) with its two core identities—\(\Gamma(z+1) = z\Gamma(z)\) and \(\Gamma(1/2) = \sqrt{\pi}\)—and shows why Bayesian libraries always compute &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lgamma&lt;/code&gt; in log space.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-where-the-gamma-function-appears-in-bayesian-models&quot;&gt;Key ideas: Where the Gamma Function Appears in Bayesian Models&lt;/h2&gt;

&lt;p&gt;Four properties turn \(\Gamma(z)\) from an intimidating integral into an everyday algebraic tool:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Continuous Factorial Extension:&lt;/strong&gt; For every positive integer \(n\), \(\Gamma(n) = (n-1)!\), and for all \(z &amp;gt; 0\), the recurrence \(\Gamma(z+1) = z\,\Gamma(z)\) lets you step any argument down by 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Half-Integer Anchor \(\Gamma(1/2) = \sqrt{\pi}\):&lt;/strong&gt; Connects \(\Gamma\) directly to the Gaussian integral \(\int_{-\infty}^{\infty} e^{-x^2}\,dx = \sqrt{\pi}\), explaining why \(\sqrt{\pi}\) appears inside the Student-\(t\) and Chi-squared densities!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Beta Function Normalizer:&lt;/strong&gt; \(B(\alpha, \beta) = \int_0^1 p^{\alpha-1}(1-p)^{\beta-1}\,dp = \frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\) is the exact normalizing constant of \(\mathrm{Beta}(\alpha,\beta)\)—and powers the closed-form &lt;strong&gt;Beta–Binomial marginal likelihood&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Log-Gamma (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lgamma&lt;/code&gt;) for Numerical Safety:&lt;/strong&gt; Because \(\Gamma(200) \approx 3.9\times 10^{372}\) overflows &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; (max \(1.8\times 10^{308}\)), statistical software computes \(\ln\Gamma(\alpha) + \ln\Gamma(\beta) - \ln\Gamma(\alpha+\beta)\) directly in log space!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will understand what the Gamma function is, why it is the natural extension of factorial to non-integer values, and why it appears throughout Bayesian statistics (Beta, Gamma, Dirichlet, Student-t, and more).&lt;/p&gt;

&lt;h2 id=&quot;1-motivation-from-factorial-to-non-integers&quot;&gt;1) Motivation: From factorial to non-integers&lt;/h2&gt;

&lt;p&gt;For positive integers, factorial is defined as:&lt;/p&gt;

\[n! = 1 \cdot 2 \cdot 3 \cdots n\]

&lt;p&gt;For example, \(5! = 120\).&lt;/p&gt;

&lt;p&gt;But what should \(\left(\frac{1}{2}\right)!\) mean? The usual factorial definition does not apply. The Gamma function gives a consistent extension.&lt;/p&gt;

&lt;p&gt;At an introductory level, this is a correct summary: &lt;strong&gt;the Gamma function extends factorial to positive non-integers&lt;/strong&gt;. More generally, for every \(x&amp;gt;0\), we can write:&lt;/p&gt;

\[x! = \Gamma(x+1)\]

&lt;h2 id=&quot;2-definition-of-the-gamma-function&quot;&gt;2) Definition of the Gamma function&lt;/h2&gt;

&lt;p&gt;For \(z &amp;gt; 0\), the Gamma function is:&lt;/p&gt;

\[\Gamma(z) = \int_0^{\infty} t^{z-1} e^{-t} \, dt\]

&lt;p&gt;This integral is positive and converges for \(z &amp;gt; 0\). In probability and Bayesian modeling, \(\Gamma(z)\) often appears as a normalization constant.&lt;/p&gt;

&lt;h2 id=&quot;3-core-relationship-with-factorial&quot;&gt;3) Core relationship with factorial&lt;/h2&gt;

&lt;p&gt;The key identity is:&lt;/p&gt;

\[\Gamma(z+1) = z\,\Gamma(z)\]

&lt;p&gt;Setting \(z=n\) (a positive integer) gives:&lt;/p&gt;

\[\Gamma(n+1) = n!\]

&lt;p&gt;For example, \(\Gamma(1)=1\), \(\Gamma(2)=1!=1\), \(\Gamma(3)=2!=2\), and \(\Gamma(6)=5!=120\).&lt;/p&gt;

&lt;p&gt;So on integer arguments, Gamma exactly matches factorial.&lt;/p&gt;

&lt;h2 id=&quot;4-special-value-gammalefttfrac12rightsqrtpi&quot;&gt;4) Special value: \(\Gamma\!\left(\tfrac{1}{2}\right)=\sqrt{\pi}\)&lt;/h2&gt;

&lt;p&gt;A famous result is:&lt;/p&gt;

\[\Gamma\!\left(\frac{1}{2}\right)=\sqrt{\pi}\]

&lt;p&gt;Then:&lt;/p&gt;

\[\Gamma\!\left(\frac{3}{2}\right)=\frac{1}{2}\Gamma\!\left(\frac{1}{2}\right)=\frac{\sqrt{\pi}}{2}\]

\[\Gamma\!\left(\frac{5}{2}\right)=\frac{3}{2}\Gamma\!\left(\frac{3}{2}\right)=\frac{3\sqrt{\pi}}{4}\]

&lt;p&gt;This helps explain why \(\pi\) appears in many continuous-distribution formulas.&lt;/p&gt;

&lt;h2 id=&quot;5-why-gamma-matters-in-bayesian-statistics&quot;&gt;5) Why Gamma matters in Bayesian statistics&lt;/h2&gt;

&lt;h3 id=&quot;51-distribution-normalization&quot;&gt;5.1 Distribution normalization&lt;/h3&gt;

&lt;p&gt;Many densities are first written in an unnormalized form, then divided by a constant so the total integral is 1. That constant is often expressed with Gamma.&lt;/p&gt;

&lt;p&gt;For example, the Gamma distribution (shape \(\alpha\), rate \(\beta\)):&lt;/p&gt;

\[p(x\mid \alpha,\beta)=\frac{\beta^{\alpha}}{\Gamma(\alpha)}x^{\alpha-1}e^{-\beta x},\quad x&amp;gt;0\]

&lt;h3 id=&quot;52-beta-distribution&quot;&gt;5.2 Beta distribution&lt;/h3&gt;

&lt;p&gt;The Beta normalization constant is:&lt;/p&gt;

\[B(a,b)=\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}\]

&lt;p&gt;So:&lt;/p&gt;

\[p(\theta\mid a,b)=\frac{1}{B(a,b)}\theta^{a-1}(1-\theta)^{b-1},\quad 0&amp;lt;\theta&amp;lt;1\]

&lt;h3 id=&quot;53-dirichlet-and-student-t&quot;&gt;5.3 Dirichlet and Student-t&lt;/h3&gt;

&lt;p&gt;Dirichlet is a multivariate generalization of Beta, and its normalization constant is also written with Gamma. Likewise, the Student-t distribution contains a Gamma ratio in its front coefficient to ensure the density is properly normalized.&lt;/p&gt;

&lt;p&gt;In short: if you do Bayesian analysis long enough, you repeatedly use Gamma.&lt;/p&gt;

&lt;h2 id=&quot;6-practical-computation-intuition&quot;&gt;6) Practical computation intuition&lt;/h2&gt;

&lt;p&gt;In numerical work, we usually avoid direct \(\Gamma(z)\) for large \(z\) because of overflow. Instead, we use:&lt;/p&gt;

\[\log\Gamma(z)\]

&lt;p&gt;Scientific libraries provide this directly (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln&lt;/code&gt; in SciPy), which is much more stable for optimization and MCMC.&lt;/p&gt;

&lt;p&gt;Python example:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy.special&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gammaln&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# 120.0
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# ~1.7724538509 = sqrt(pi)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gammaln&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# log(Gamma(100))
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;7-quick-recap&quot;&gt;7) Quick recap&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;\(\Gamma(z)\) extends factorial from integers to positive real numbers.&lt;/li&gt;
  &lt;li&gt;Recursion: \(\Gamma(z+1)=z\Gamma(z)\).&lt;/li&gt;
  &lt;li&gt;For \(n\in\mathbb{N}\): \(\Gamma(n+1)=n!\).&lt;/li&gt;
  &lt;li&gt;Famous value: \(\Gamma\!\left(\tfrac{1}{2}\right)=\sqrt{\pi}\).&lt;/li&gt;
  &lt;li&gt;In Bayesian statistics, Gamma frequently appears as a normalization constant.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-computing-gamma52-and-the-exact-normalizer-of-mathrmbeta2-3-by-hand&quot;&gt;Worked Numerical Example: Computing \(\Gamma(5/2)\) and the Exact Normalizer of \(\mathrm{Beta}(2, 3)\) by Hand&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Part A — Stepping down a half-integer:&lt;/strong&gt;
Using \(\Gamma(z+1) = z\Gamma(z)\) and \(\Gamma(1/2) = \sqrt{\pi} \approx 1.7725\):
\(\Gamma\!\left(\frac{5}{2}
ight) = \frac{3}{2}\,\Gamma\!\left(\frac{3}{2}
ight) = \frac{3}{2}\cdot\frac{1}{2}\,\Gamma\!\left(\frac{1}{2}
ight) = \frac{3}{4}\sqrt{\pi} \approx \mathbf{1.3293}.\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Part B — Exact normalizing constant of \(\mathrm{Beta}(\alpha=2,\; \beta=3)\):&lt;/strong&gt;
\(B(2, 3) = \frac{\Gamma(2)\,\Gamma(3)}{\Gamma(2+3)} = \frac{1!\cdot 2!}{4!} = \frac{1 \times 2}{24} = \frac{1}{12}.\)
Therefore the exact PDF of \(\mathrm{Beta}(2, 3)\) is \(f(p) = 12\,p(1-p)^2\) on \([0,1]\)! Verify by direct integration:
\(\int_0^1 12(p - 2p^2 + p^3)\,dp = 12\!\left(\frac{1}{2} - \frac{2}{3} + \frac{1}{4}
ight) = 12\cdot\frac{1}{12} = \mathbf{1}\) — exact!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-practical-takeaways-on-the-gamma-function&quot;&gt;Explanation: Four Practical Takeaways on the Gamma Function&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Remember the off-by-one shift:&lt;/strong&gt; \(\Gamma(n) = (n-1)!\), so \(\Gamma(1) = 0! = 1\) and \(\Gamma(5) = 4! = 24\)—never \(\Gamma(5) = 5!\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;You rarely need to integrate Beta/Gamma kernels by hand:&lt;/strong&gt; Whenever you see \(\int_0^1 p^{a-1}(1-p)^{b-1}\,dp\), immediately recognize it as \(B(a,b) = \frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.special.gammaln&lt;/code&gt; (or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;betaln&lt;/code&gt;) in code:&lt;/strong&gt; Even for modest datasets (\(n = 200\)), calling &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gamma(200)&lt;/code&gt; returns &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt;, whereas &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln(200) ≈ 859.66&lt;/code&gt; works effortlessly.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Watch the Dirichlet generalization:&lt;/strong&gt; For \(K\)-category probabilities \((p_1,\dots,p_K)\), the Dirichlet normalizer is simply \(\frac{\prod_{k=1}^K \Gamma(\alpha_k)}{\Gamma(\sum_k \alpha_k)}\)—the direct multi-category cousin of \(B(\alpha,\beta)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Using \(B(\alpha,\beta) = \frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\), compute the exact normalizing constant \(1/B(3, 3)\) for the symmetric prior \(\mathrm{Beta}(3, 3)\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=UZuszwqW_Qo&quot;&gt;Gamma Function - Explained&lt;/a&gt; — DataMListic, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch for the gamma function as the extension of factorial beyond the positive integers, which is the definition this lesson starts from.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=L4Trz6pFut4&quot;&gt;Introduction to the Gamma function &amp;amp; the Pi function (extending the factorial!)&lt;/a&gt; — blackpenredpen, English. Watch the explicit link between factorial and the gamma integral, supporting the lesson’s passage from n! to Γ(z).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dGnIJFzkLI4&quot;&gt;What is the factorial of -½?&lt;/a&gt; — Stand-up Maths, English. Watch a concrete non-integer factorial, useful when the lesson explains why Beta, Gamma, and t densities need this function.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1.&lt;/strong&gt; Use recursion to compute \(\Gamma(4)\) and \(\Gamma(5)\), then compare with \(3!\) and \(4!\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2.&lt;/strong&gt; Starting from \(\Gamma\!\left(\tfrac{1}{2}\right)=\sqrt{\pi}\), derive \(\Gamma\!\left(\tfrac{3}{2}\right)\) and \(\Gamma\!\left(\tfrac{5}{2}\right)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3.&lt;/strong&gt; Rewrite the Beta(\(a,b\)) normalization constant using Gamma and explain why this constant is needed for the density to integrate to 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4.&lt;/strong&gt; In Python, compute &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gamma(10)&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln(10)&lt;/code&gt;. Check whether &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.log(gamma(10))&lt;/code&gt; is close to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln(10)&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.). CRC Press.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. (2015). &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.). Academic Press.&lt;/li&gt;
  &lt;li&gt;SciPy Special Functions: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gamma&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.12: The T-test and the T Distribution</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_09_t_test_and_t_distribution/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_09_t_test_and_t_distribution</id>
   <content type="html">&lt;p&gt;In 1908, William Sealy Gosset—a chemist working at the Guinness brewery in Dublin—had a practical problem: testing barley yields and yeast batches with &lt;strong&gt;only 4 to 10 samples at a time&lt;/strong&gt;. Standard Normal \(z\)-tables kept giving him too many false alarms because he didn’t know the true population standard deviation \(\sigma\); he had to estimate it from the tiny sample itself! Publishing under the pseudonym &lt;strong&gt;“Student”&lt;/strong&gt; (because Guinness forbade employees from publishing trade secrets), Gosset derived the &lt;strong&gt;Student-\(t\) distribution&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This lesson explains &lt;em&gt;why&lt;/em&gt; estimating \(\sigma\) thickens the tails of the sampling distribution, walks through a hand-verifiable \(t\)-test, and reveals the Student-\(t\) distribution’s second life in Bayesian statistics: as the &lt;strong&gt;exact marginal posterior&lt;/strong&gt; for an unknown Normal mean AND the go-to &lt;strong&gt;robust likelihood&lt;/strong&gt; against outliers!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-student-t-in-both-frequentist-and-bayesian-worlds&quot;&gt;Key ideas: Student-\(t\) in Both Frequentist and Bayesian Worlds&lt;/h2&gt;

&lt;p&gt;Four insights connect Gosset’s 1908 brewery discovery directly to modern Bayesian modeling:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;The Price of Unknown \(\sigma\):&lt;/strong&gt; Replacing known \(\sigma\) with noisy sample \(S\) in \(T = \frac{\bar{X}-\mu}{S/\sqrt{n}}\) injects extra variability into the denominator, producing heavier tails governed by &lt;strong&gt;degrees of freedom \(\nu = n - 1\)&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convergence to Normal as \(\nu \to \infty\):&lt;/strong&gt; At \(\nu = 3\), the 95% critical value is \(3.182\) (far wider than \(1.960\)); by \(\nu = 30\) it shrinks to \(2.042\); as \(\nu\to\infty\), \(t_\nu \to \mathcal{N}(0,1)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exact Bayesian Appearance (Marginalizing \(\sigma^2\)):&lt;/strong&gt; In a Bayesian Normal model with unknown mean \(\mu\) &lt;em&gt;and&lt;/em&gt; unknown variance \(\sigma^2\), integrating out \(\sigma^2\) yields an exact &lt;strong&gt;Student-\(t\) posterior&lt;/strong&gt; for \(\mu\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Heavy-Tailed Robustness:&lt;/strong&gt; Because Student-\(t\) (with small \(\nu$, say\)\nu = 3\text{–}5\() assigns much higher probability to extreme values than a Gaussian, using a Student-\)t$$ likelihood in Bayesian regression makes your posterior nearly immune to wild outliers!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;p&gt;After completing this lesson, you will deeply understand the &lt;strong&gt;t-statistic&lt;/strong&gt;, the &lt;strong&gt;t distribution&lt;/strong&gt;, and the &lt;strong&gt;t-test&lt;/strong&gt; - one of the most common statistical tools in scientific research. You will learn why we need the t distribution (instead of the normal distribution), how to compute and interpret the t-value, and the different types of t-tests. More importantly, you will understand the assumptions and limitations of the t-test, preparing a foundation for comparison with Bayesian methods in later chapters.&lt;/p&gt;

&lt;h2 id=&quot;introduction-the-problem-with-an-unknown-standard-deviation&quot;&gt;Introduction: The Problem with an Unknown Standard Deviation&lt;/h2&gt;

&lt;p&gt;Imagine you are a researcher who wants to know whether the average height of male students at your university differs from 170 cm. You cannot measure the height of all male students, so you randomly sample 25 students and compute the sample mean height \(\bar{x} = 172.5\) cm with sample standard deviation \(s = 6.2\) cm.&lt;/p&gt;

&lt;p&gt;You want to know: is the difference between 172.5 cm (sample) and 170 cm (hypothesis) large enough to conclude that the true average height really differs from 170 cm, or could it be just due to chance?&lt;/p&gt;

&lt;p&gt;In classical statistics, if we &lt;strong&gt;know the population standard deviation&lt;/strong&gt; \(\sigma\), we can use the &lt;strong&gt;z-statistic&lt;/strong&gt;:&lt;/p&gt;

\[z = \frac{\bar{x} - \mu_0}{\sigma / \sqrt{n}}\]

&lt;p&gt;And this z-statistic follows the standard normal distribution \(N(0, 1)\).&lt;/p&gt;

&lt;p&gt;But in practice, we &lt;strong&gt;rarely know&lt;/strong&gt; \(\sigma\)! We only have \(s\) - the sample standard deviation, an estimate of \(\sigma\). When we replace \(\sigma\) with \(s\), the uncertainty increases, and the distribution of the statistic is no longer normal.&lt;/p&gt;

&lt;p&gt;This is exactly why we need the &lt;strong&gt;t distribution&lt;/strong&gt; and the &lt;strong&gt;t-statistic&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;the-t-statistic-definition-and-meaning&quot;&gt;The T-statistic: Definition and Meaning&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;t-statistic&lt;/strong&gt; (or t-value) is defined analogously to the z-statistic, but uses the sample standard deviation \(s\) instead of \(\sigma\):&lt;/p&gt;

\[t = \frac{\bar{x} - \mu_0}{s / \sqrt{n}}\]

&lt;p&gt;Here, \(\bar{x}\) is the sample mean, \(\mu_0\) is the hypothesized value, usually coming from \(H_0\), \(s\) is the sample standard deviation, \(n\) is the sample size, and \(s / \sqrt{n}\) is called the &lt;strong&gt;standard error of the mean&lt;/strong&gt; (SE), i.e., the uncertainty of the sample mean.&lt;/p&gt;

&lt;h3 id=&quot;interpreting-the-t-value&quot;&gt;Interpreting the T-value&lt;/h3&gt;

&lt;p&gt;The t-value measures the &lt;strong&gt;number of standard errors&lt;/strong&gt; by which the sample mean is away from the hypothesized value:&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;If **$$&lt;/td&gt;
      &lt;td&gt;t&lt;/td&gt;
      &lt;td&gt;\(is large**, the sample mean is a considerable number of standard errors away from\)\mu_0\(, and that creates evidence against\)H_0\(; conversely, if **\)&lt;/td&gt;
      &lt;td&gt;t&lt;/td&gt;
      &lt;td&gt;\(is small**, the sample mean lies close to\)\mu_0$$ so the data has not created much weight against the null hypothesis.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: The four figures below separate each level of extremeness of the t-value so you can clearly see how the p-value changes.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_value_small_example.png&quot; alt=&quot;A small t-value with weak evidence against H0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1a: With \(t = 0.5\) and \(df = 15\), the p-value is large at about 0.62 so the data is fairly consistent with \(H_0\).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_value_borderline_example.png&quot; alt=&quot;A t-value in the middle zone near the 0.05 threshold&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1b: With \(t = 2.0\), the p-value is about 0.064 so the result is in a borderline state, close to the 0.05 threshold.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_value_large_example.png&quot; alt=&quot;A large t-value with stronger evidence against H0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1c: With \(t = 3.0\), the p-value is small at about 0.009 so the evidence against \(H_0\) is markedly stronger.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_value_chocolate_example.png&quot; alt=&quot;A chocolate example with a t of small magnitude and negative sign&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1d: In the chocolate example with \(t = -0.70\), p = 0.495 shows there is not yet enough evidence against the null hypothesis.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The shaded region in each panel represents the “extreme region” used to compute the p-value (two-tailed test).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A concrete example:&lt;/strong&gt; returning to the height example, we have \(\bar{x} = 172.5\) cm, \(\mu_0 = 170\) cm, \(s = 6.2\) cm, and \(n = 25\).&lt;/p&gt;

\[t = \frac{172.5 - 170}{6.2 / \sqrt{25}} = \frac{2.5}{1.24} = 2.02\]

&lt;p&gt;A t-value = 2.02 means the sample mean is about 2 standard errors away from the hypothesized value. This is a considerable distance, suggesting there is evidence against the null hypothesis.&lt;/p&gt;

&lt;h2 id=&quot;the-t-distribution-why-not-the-normal-distribution&quot;&gt;The T Distribution: Why Not the Normal Distribution?&lt;/h2&gt;

&lt;p&gt;When we use \(s\) instead of \(\sigma\), the t-statistic does not follow the normal distribution, but follows the &lt;strong&gt;t distribution&lt;/strong&gt; (Student’s t-distribution).&lt;/p&gt;

&lt;h3 id=&quot;characteristics-of-the-t-distribution&quot;&gt;Characteristics of the T Distribution&lt;/h3&gt;

&lt;p&gt;The t distribution has a shape quite similar to the normal distribution but with heavier tails, and this very characteristic reflects the additional uncertainty when we must estimate \(\sigma\) by \(s\). The t distribution also depends on a parameter called the &lt;strong&gt;degrees of freedom&lt;/strong&gt;, usually equal to \(df = n - 1\) in the one-sample t-test, and as \(n\) increases it converges to the normal distribution; so with a large enough sample, for example more than 30 observations, the two distributions are usually very hard to tell apart by eye.&lt;/p&gt;

&lt;h3 id=&quot;why-heavier-tails&quot;&gt;Why Heavier Tails?&lt;/h3&gt;

&lt;p&gt;When the sample is small, \(s\) is an uncertain estimate of \(\sigma\). Sometimes \(s\) is smaller than the true \(\sigma\), making the t-value larger than it should be. The heavier tails of the t distribution “adjust” for this variability, making it harder for us to reject \(H_0\) when the sample is small - a reasonably cautious approach.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_vs_normal_distribution.png&quot; alt=&quot;Comparison of the T Distribution and the Normal Distribution&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates the comparison of the t distribution and the normal distribution. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The figure above compares the t distribution at several different df values. With &lt;strong&gt;df = 2&lt;/strong&gt;, corresponding to a very small sample, the tails of the distribution are extremely heavy because the uncertainty in estimating \(\sigma\) is still very large; with &lt;strong&gt;df = 5&lt;/strong&gt; the tails are still clearly heavier than the normal; with &lt;strong&gt;df = 10&lt;/strong&gt; the difference has shrunk; and with &lt;strong&gt;df = 30&lt;/strong&gt; the curve is almost indistinguishable from the normal distribution, which can be viewed as the limiting case when \(df = \infty\).&lt;/p&gt;

&lt;p&gt;Note how the critical values change: with df = 2 and \(\alpha = 0.05\) (two-tailed), the critical value is ±4.303, whereas for the normal distribution it is only ±1.96. This makes rejecting \(H_0\) much harder when the sample is small - a cautious and reasonable property.&lt;/p&gt;

&lt;h3 id=&quot;experiment-the-t-distribution-with-a-small-sample&quot;&gt;Experiment: the t distribution with a small sample&lt;/h3&gt;

&lt;p&gt;Simulates the t statistic and compares it with the t and normal densities as n grows.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;pvalue-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;tdist&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;types-of-t-tests&quot;&gt;Types of T-tests&lt;/h2&gt;

&lt;p&gt;There are three common types of t-tests, depending on the study design:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_test_type_summary_table.png&quot; alt=&quot;Summary table of the three types of t-tests&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 2: A quick summary table of the purpose, formula and degrees of freedom of the three common types of t-tests.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;1-one-sample-t-test&quot;&gt;1. One-sample T-test&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Purpose:&lt;/strong&gt; Compare the mean of one sample with a known value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;

\[t = \frac{\bar{x} - \mu_0}{s / \sqrt{n}}\]

&lt;p&gt;&lt;strong&gt;Degrees of freedom:&lt;/strong&gt; \(df = n - 1\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt; Check whether the average height of male students differs from 170 cm.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_test_type_one_sample.png&quot; alt=&quot;One-sample t-test comparing one sample with a hypothesized value&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 2a: The one-sample t-test compares the mean of one sample with a known or pre-hypothesized value.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;2-independent-two-sample-t-test-unpaired&quot;&gt;2. Independent Two-sample T-test (Unpaired)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Purpose:&lt;/strong&gt; Compare the means of two independent groups.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Formula (assuming equal variances):&lt;/strong&gt;&lt;/p&gt;

\[t = \frac{\bar{x}_1 - \bar{x}_2}{s_p \sqrt{\frac{1}{n_1} + \frac{1}{n_2}}}\]

&lt;p&gt;Here \(s_p\) is the &lt;strong&gt;pooled standard deviation&lt;/strong&gt;:&lt;/p&gt;

\[s_p = \sqrt{\frac{(n_1-1)s_1^2 + (n_2-1)s_2^2}{n_1 + n_2 - 2}}\]

&lt;p&gt;&lt;strong&gt;Degrees of freedom:&lt;/strong&gt; \(df = n_1 + n_2 - 2\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt; Compare the average height of male students in department A and department B.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_test_type_independent.png&quot; alt=&quot;Independent two-sample t-test comparing two independent groups&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 2b: The independent two-sample t-test compares two independent groups, for example height between two different departments.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;3-paired-t-test-dependent&quot;&gt;3. Paired T-test (Dependent)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Purpose:&lt;/strong&gt; Compare the means of two measurements on the same group of subjects (before-after, matched pairs).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;

\[t = \frac{\bar{d}}{s_d / \sqrt{n}}\]

&lt;p&gt;Where:
Here, \(\bar{d}\) is the mean of the differences, and \(s_d\) is the standard deviation of those differences.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Degrees of freedom:&lt;/strong&gt; \(df = n - 1\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt; Compare the weight of patients before and after taking a weight-loss drug.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/t_test_type_paired.png&quot; alt=&quot;Paired t-test comparing before and after on the same group&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 2c: The paired t-test tracks the same group at two time points, so the focus is on the difference of each measured pair.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;assumptions-of-the-t-test&quot;&gt;Assumptions of the T-test&lt;/h2&gt;

&lt;p&gt;The t-test relies on several important assumptions. When these assumptions are violated, the results may not be reliable:&lt;/p&gt;

&lt;h3 id=&quot;1-data-follow-a-normal-distribution-or-n-is-large-enough&quot;&gt;1. Data follow a normal distribution (or n is large enough)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Assumption:&lt;/strong&gt; The data in each group follow a normal distribution, or the sample size is large enough (n &amp;gt; 30 is a rule of thumb) for the Central Limit Theorem to take effect.&lt;/p&gt;

&lt;p&gt;We can check this assumption with a histogram, a Q-Q plot, or the Shapiro-Wilk test, although we must remember that the latter test is usually very sensitive when the sample size is large.&lt;/p&gt;

&lt;p&gt;If the violation occurs with a small sample, we should consider non-parametric tests such as Wilcoxon; with a large sample, the t-test is usually still fairly robust thanks to the central limit theorem.&lt;/p&gt;

&lt;h3 id=&quot;2-independence-among-observations&quot;&gt;2. Independence among observations&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Assumption:&lt;/strong&gt; The observations in the sample are independent of each other.&lt;/p&gt;

&lt;p&gt;Common violations include repeated measurements on the same subject, hierarchically structured data, or time series data with serial dependence.&lt;/p&gt;

&lt;h3 id=&quot;3-equal-variances-for-the-two-sample-t-test&quot;&gt;3. Equal variances (for the two-sample t-test)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Assumption:&lt;/strong&gt; The two groups have the same variance (homogeneity of variance).&lt;/p&gt;

&lt;p&gt;We can check using Levene’s test or use the rule of thumb that the ratio \(\frac{s_1}{s_2}\) should not exceed 2 by too much.&lt;/p&gt;

&lt;p&gt;If this assumption is violated, Welch’s t-test is usually the safer choice because it does not require equal variances.&lt;/p&gt;

&lt;h2 id=&quot;interpreting-t-test-results&quot;&gt;Interpreting T-test Results&lt;/h2&gt;

&lt;p&gt;When we run a t-test, we get two main pieces of information:&lt;/p&gt;

&lt;h3 id=&quot;1-the-t-value&quot;&gt;1. The T-value&lt;/h3&gt;

&lt;p&gt;The t-value tells the &lt;strong&gt;degree of difference&lt;/strong&gt; between the data and the null hypothesis; the larger its absolute value, the farther the data lie from the expectation under \(H_0\), and therefore the stronger the evidence against \(H_0\).&lt;/p&gt;

&lt;h3 id=&quot;2-the-p-value&quot;&gt;2. The P-value&lt;/h3&gt;

&lt;p&gt;The p-value tells the &lt;strong&gt;probability of observing a t-value at least as extreme&lt;/strong&gt; if \(H_0\) is true; a small p, for example below 0.05, is usually interpreted as statistically significant, while a large p only shows that there is not yet enough evidence to reject \(H_0\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IMPORTANT NOTE:&lt;/strong&gt; The p-value does &lt;strong&gt;not&lt;/strong&gt; tell the probability that \(H_0\) is true, does &lt;strong&gt;not&lt;/strong&gt; tell the practical importance of the result, and therefore should always be reported together with the &lt;strong&gt;effect size&lt;/strong&gt; and &lt;strong&gt;confidence intervals&lt;/strong&gt; rather than standing alone.&lt;/p&gt;

&lt;h2 id=&quot;a-complete-example-one-sample-t-test&quot;&gt;A Complete Example: One-sample T-test&lt;/h2&gt;

&lt;p&gt;Let us work through a complete example with real data:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context:&lt;/strong&gt; A chocolate manufacturer claims their chocolate bars weigh 100g. We doubt this claim and weigh 16 random bars.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data (grams):&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;98, 102, 97, 99, 101, 103, 98, 100, 
99, 101, 97, 102, 100, 98, 101, 99
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Set up the hypotheses.&lt;/strong&gt; We set \(H_0: \mu = 100\), i.e., the chocolate bar weighs exactly 100g as claimed; \(H_1: \mu \neq 100\), i.e., the mean weight differs from 100g; and use a significance level \(\alpha = 0.05\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Compute the sample statistics.&lt;/strong&gt; From the data, we have \(n = 16\), \(\bar{x} = 99.69\) g, and \(s = 1.78\) g.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Compute the t-statistic&lt;/strong&gt;&lt;/p&gt;

\[t = \frac{99.69 - 100}{1.78 / \sqrt{16}} = \frac{-0.31}{0.445} = -0.70\]

&lt;p&gt;&lt;strong&gt;Step 4: Determine the degrees of freedom&lt;/strong&gt;&lt;/p&gt;

\[df = n - 1 = 16 - 1 = 15\]

&lt;p&gt;&lt;strong&gt;Step 5: Find the p-value&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With \(t = -0.70\) and \(df = 15\), consulting a t table or using software:&lt;/p&gt;

&lt;p&gt;\(p = 0.495\) (two-tailed)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 6: Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;\(p = 0.495 &amp;gt; 0.05\), we &lt;strong&gt;fail to reject&lt;/strong&gt; \(H_0\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interpretation:&lt;/strong&gt; There is not enough evidence to conclude that the mean weight of the chocolate differs from 100g. The observed difference (99.69g) could easily occur due to random variation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;95% Confidence Interval:&lt;/strong&gt;&lt;/p&gt;

\[\bar{x} \pm t_{0.025, 15} \times \frac{s}{\sqrt{n}} = 99.69 \pm 2.131 \times 0.445 = [98.74, 100.64]\]

&lt;p&gt;This confidence interval contains 100g, consistent with the conclusion of not rejecting \(H_0\).&lt;/p&gt;

&lt;h3 id=&quot;an-additional-reading-via-effect-size&quot;&gt;An Additional Reading via Effect Size&lt;/h3&gt;

&lt;p&gt;We can also standardize the mean deviation by the sample standard deviation:&lt;/p&gt;

\[d=\frac{99.69-100}{1.78}\approx -0.17\]

&lt;p&gt;This is a very small effect size. That means not only is the p-value not small enough to reject \(H_0\), but even the observed deviation is small in a practical sense. This example reminds us that a statistical result should be read through at least three layers at once: the sign of the effect, the magnitude of the effect, and the uncertainty around it.&lt;/p&gt;

&lt;h2 id=&quot;comparing-the-t-test-with-the-z-test&quot;&gt;Comparing the T-test with the Z-test&lt;/h2&gt;

&lt;p&gt;\vert  Feature \vert  Z-test \vert  T-test \vert 
\vert ———-\vert ——–\vert ——–\vert 
\vert  &lt;strong&gt;When to use&lt;/strong&gt; \vert  Population \(\sigma\) known \vert  \(\sigma\) unknown (use \(s\)) \vert 
\vert  &lt;strong&gt;Distribution&lt;/strong&gt; \vert  Normal(0, 1) \vert  t-distribution (df) \vert 
\vert  &lt;strong&gt;Tails&lt;/strong&gt; \vert  Thinner \vert  Heavier \vert 
\vert  &lt;strong&gt;Critical values&lt;/strong&gt; \vert  Fixed \vert  Depend on df \vert 
\vert  &lt;strong&gt;In practice&lt;/strong&gt; \vert  Rarely used \vert  Very common \vert&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Relationship:&lt;/strong&gt; As \(n \to \infty\), t-distribution \(\to\) Normal distribution&lt;/p&gt;

&lt;h2 id=&quot;limitations-of-the-t-test-and-the-bayesian-direction&quot;&gt;Limitations of the T-test and the Bayesian Direction&lt;/h2&gt;

&lt;p&gt;Although the t-test is very useful, it still carries limitations close to those of the p-value. It gives us \(P(\text{data} \mid H_0)\) rather than \(P(H_0 \mid \text{data})\), tends to be pulled toward binary decisions based on arbitrary thresholds, does not integrate prior knowledge about the plausibility of the hypothesis, and can give wrong conclusions if the underlying assumptions are substantially violated.&lt;/p&gt;

&lt;h3 id=&quot;the-bayesian-approach&quot;&gt;The Bayesian Approach&lt;/h3&gt;

&lt;p&gt;In later chapters, you will see how the Bayesian approach addresses these limitations. &lt;strong&gt;Bayesian estimation&lt;/strong&gt; provides the full distribution of the parameter instead of just a single t-value, &lt;strong&gt;credible intervals&lt;/strong&gt; have a more direct interpretation than confidence intervals, &lt;strong&gt;Bayes factors&lt;/strong&gt; allow comparing evidence between hypotheses, and &lt;strong&gt;priors&lt;/strong&gt; allow prior knowledge to be incorporated into inference transparently.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-one-sample-t-test-on-a-small-batch-n--4-vs-n--25&quot;&gt;Worked Numerical Example: One-Sample \(t\)-Test on a Small Batch (\(n = 4\) vs. \(n = 25\))&lt;/h3&gt;

&lt;p&gt;Suppose Guinness tests \(n = 4\) barley batches and measures yield difference from target (\(\mu_0 = 0\)): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[2, 4, 6, 8]&lt;/code&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sample mean &amp;amp; SD:&lt;/strong&gt; \(\bar{x} = 5.0\); sum of squared deviations \((-3)^2 + (-1)^2 + 1^2 + 3^2 = 20\); sample variance \(s^2 = \frac{20}{4-1} = 6.667 \implies s \approx 2.582\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Standard error &amp;amp; \(t\)-statistic:&lt;/strong&gt;
\(\mathrm{SE} = \frac{2.582}{\sqrt{4}} = 1.291, \qquad t = \frac{5.0 - 0}{1.291} = \mathbf{3.873} \quad (df = 3).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare \(t\) critical value vs. naive Normal \(z\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Naive \(z\)-test (WRONG for \(n=4\)!): 95% critical value \(1.960\) \(\implies\) CI \(5.0 \pm 2.53 = [2.47, 7.53]\) (falsely narrow!).&lt;/li&gt;
      &lt;li&gt;Proper \(t\)-test (\(df = 3\)): 95% critical value \(t_{0.025;\,3} = \mathbf{3.182}\) \(\implies\) CI \(5.0 \pm 4.11 = [0.89, 9.11]\) (&lt;strong&gt;62% wider&lt;/strong&gt;!).
Since \(3.873 &amp;gt; 3.182\) (\(p \approx 0.030 &amp;lt; 0.05\)), we still reject \(H_0\), but with an &lt;em&gt;honest&lt;/em&gt; uncertainty interval!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-using-student-t-effectively&quot;&gt;Explanation: Four Rules for Using Student-\(t\) Effectively&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always prefer Welch’s two-sample \(t\)-test (unequal variances):&lt;/strong&gt; Assuming two groups have identical variance (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;equal_var=True&lt;/code&gt;) is rarely justified; Welch’s \(t\)-test adjusts degrees of freedom automatically with virtually zero loss of power.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use paired \(t\)-tests when measurements share a subject:&lt;/strong&gt; Before/after measurements on the same person cancel out individual baseline variation—dramatically boosting power compared to an unpaired test.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Remember Student-\(t\)’s Bayesian upgrade (BEST — Kruschke):&lt;/strong&gt; Instead of a two-sample \(t\)-test, Bayesian Estimation Supersedes the \(t\)-test fits a Student-\(t\) model to both groups and gives you the full posterior distribution over the difference in means &lt;em&gt;and&lt;/em&gt; difference in variances!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Watch extreme skewness at tiny \(n\):&lt;/strong&gt; When \(n &amp;lt; 10\) and data is wildly skewed, check residuals or use a non-parametric / Bayesian model matching the true data shape.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Why does the 95% critical value of the \(t\)-distribution shrink from \(3.182\) at \(df = 3\) down toward \(1.960\) as sample size \(n\) grows large?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Uv6nGIgZMVw&quot;&gt;Introduction to the t Distribution (non-technical)&lt;/a&gt; — jbstatistics, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch why we must use the t distribution when the standard deviation is only estimated from the sample, exactly the reason the lesson replaces the Normal with t.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=a2rd4Qy8yNI&quot;&gt;Introduction to t statistics \vert  Confidence intervals \vert  AP Statistics \vert  Khan Academy&lt;/a&gt; — Khan Academy, English. Watch the t statistic and the corresponding confidence interval, supporting the example of comparing a sample mean with a given value.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=nnBJeb_I-q8&quot;&gt;StatQuickie: Which t test to use&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch how to choose the form of t-test according to the sampling design, used for the part of the lesson that distinguishes testing situations.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1: Computing the T-statistic by Hand.&lt;/strong&gt; A study measures the test scores of 10 students after learning with a new method. The national average score is 75. Data: 78, 82, 75, 80, 77, 83, 79, 81, 76, 84. (a) Compute \(\bar{x}\) and \(s\). (b) Compute the t-statistic to test \(H_0: \mu = 75\). (c) With \(\alpha = 0.05\) (two-tailed), consult the t table and decide whether to reject \(H_0\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2: Distinguishing Types of T-tests.&lt;/strong&gt; For each of the following situations, determine which type of t-test is appropriate: (a) Compare the exam scores of male and female students. (b) Compare blood pressure before and after exercise for the same group of people. (c) Check whether the daily average temperature differs from 25°C. (d) Compare the effectiveness of two drugs on two different groups of patients.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3: Interpreting Results.&lt;/strong&gt; A t-test gives the result: \(t(24) = 2.35, p = 0.027\). (a) What does df = 24 mean? (b) With \(\alpha = 0.05\), what is the conclusion? (c) If this were a one-tailed test instead of two-tailed, how would the p-value change? (d) Write a correct interpretation of the meaning of this p-value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4: Checking Assumptions.&lt;/strong&gt; You have height data for 15 people with an obvious outlier. (a) Which assumption of the t-test might be violated? (b) How can you check the normality assumption? (c) If the assumption is seriously violated, what should you do? (d) Is there a better option than the t-test in this case?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5: T-test vs Bayesian (Reflection).&lt;/strong&gt; Read the chocolate example above. (a) What exactly does the confidence interval [98.74, 100.64] mean from the frequentist perspective? (b) If you were the manufacturer, would you be satisfied with the conclusion “not enough evidence”? (c) What information does the t-test not provide that you would like to know? (d) How do you think the Bayesian approach could address these problems?&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;h3 id=&quot;primary-references&quot;&gt;Primary References:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., &amp;amp; Rubin, D. B. (2013).&lt;/strong&gt; &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 4: Asymptotics and connections to non-Bayesian approaches&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kruschke, J. K. (2015).&lt;/strong&gt; &lt;em&gt;Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan&lt;/em&gt; (2nd Edition). Academic Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 11: Null Hypothesis Significance Testing&lt;/li&gt;
  &lt;li&gt;Chapter 16: Metric-Predicted Variable on One or Two Groups&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;classic-reference&quot;&gt;Classic Reference:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Student (W.S. Gosset). (1908).&lt;/strong&gt; The probable error of a mean. &lt;em&gt;Biometrika&lt;/em&gt;, 6(1), 1-25.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;The original paper introducing the t distribution&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;supplementary-reading&quot;&gt;Supplementary Reading:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Zimmerman, D. W. (1997).&lt;/strong&gt; A note on interpretation of the paired-samples t test. &lt;em&gt;Journal of Educational and Behavioral Statistics&lt;/em&gt;, 22(3), 349-360.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Delacre, M., Lakens, D., &amp;amp; Leys, C. (2017).&lt;/strong&gt; Why psychologists should by default use Welch’s t-test instead of Student’s t-test. &lt;em&gt;International Review of Social Psychology&lt;/em&gt;, 30(1), 92-101.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_11_joint_distribution/&quot;&gt;0.13 Joint Distribution&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.11: P-values and Hypothesis Testing</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_08_pvalues_and_hypothesis_testing/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_08_pvalues_and_hypothesis_testing</id>
   <content type="html">&lt;p&gt;Before appreciating &lt;em&gt;why&lt;/em&gt; Bayesian inference became a scientific revolution, you need to understand the exact machinery—and exact blind spots—of classical &lt;strong&gt;Null Hypothesis Significance Testing (NHST)&lt;/strong&gt; and &lt;strong&gt;p-values&lt;/strong&gt;. Every day, papers and dashboards misread &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p = 0.03&lt;/code&gt; as &lt;em&gt;“there is only a 3% chance the null hypothesis is true.”&lt;/em&gt; In reality, a p-value answers a completely different, backward conditional question: &lt;em&gt;“assuming the null is true, how surprising is this data?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This lesson unpacks frequentist hypothesis testing honestly—null/alternative framing, Type I/II errors, statistical power, and exact p-value arithmetic—setting the stage for Chapter 1’s direct Bayesian alternative.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-frequentist-testing-mechanics-vs-what-people-wish-it-answered&quot;&gt;Key ideas: Frequentist Testing Mechanics vs. What People Wish It Answered&lt;/h2&gt;

&lt;p&gt;Four distinctions clarify exactly what p-values can and cannot tell you:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;The Exact Conditional Direction of a p-value:&lt;/strong&gt; \(p\text{-value} = P(\text{data as or more extreme} \mid H_0\text{ true})\). It conditions on \(H_0\); it &lt;strong&gt;cannot&lt;/strong&gt; compute \(P(H_0 \mid \text{data})\) without a prior!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Type I (\(\alpha\)) vs. Type II (\(\beta\)) Error &amp;amp; Power (\(1-\beta\)):&lt;/strong&gt; Fixing \(\alpha = 0.05\) bounds the long-run false-positive rate under \(H_0\), while power measures your ability to detect a true effect of size \(\delta\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Statistical Significance vs. Practical Effect Size:&lt;/strong&gt; With \(n = 100{,}000\) users, a microscopic \(0.1\%\) lift produces \(p &amp;lt; 0.001\) even if it is commercially worthless.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Bayesian Contrast:&lt;/strong&gt; Instead of a binary reject/fail-to-reject threshold on a hypothetical sampling tail, Bayesian analysis directly computes \(P(\theta &amp;gt; 0 \mid \text{data})\) and a full credible distribution over effect sizes.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;p&gt;After completing this lesson, you will deeply understand &lt;strong&gt;p-values&lt;/strong&gt; and hypothesis testing from the frequentist perspective, not only to apply them correctly, but more importantly to recognize their fundamental limitations. You will understand why &lt;strong&gt;p-values&lt;/strong&gt; are often misinterpreted, why they do not answer the questions scientists actually care about, and why &lt;strong&gt;the Bayesian approach offers a more natural and coherent approach to statistical inference&lt;/strong&gt;. This lesson is not meant for you to abandon hypothesis testing entirely, but for you to use it critically and know when to look for alternative methods.&lt;/p&gt;

&lt;h2 id=&quot;introduction-why-do-we-need-to-talk-about-p-values&quot;&gt;Introduction: Why Do We Need to Talk About P-values?&lt;/h2&gt;

&lt;p&gt;In a course on Bayesian data analysis, why do we spend time discussing p-values and frequentist hypothesis testing? The answer has three important reasons.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;First, p-values and hypothesis testing remain the most widely used statistical tools in modern scientific research. Whether you work in medicine, psychology, economics, or any other field, you will meet p-values in most of the scientific papers you read. To be able to read and evaluate research critically, you need to understand what p-values really mean.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Second, p-values are one of the most misunderstood statistical concepts, even within the research community. Many scientists use p-values every day without really understanding what they measure. Understanding p-values correctly will help you avoid these common and dangerous mistakes.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Third, and most importantly, understanding the limitations of p-values clearly will help you appreciate the power and naturalness of the Bayesian approach. When you see clearly what p-values cannot tell you, you will understand why the Bayesian approach offers a better way to approach many research questions.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson will build a deep understanding of p-values, not so that you become an advocate for them, but so that you can use them responsibly and know when to go beyond them.&lt;/p&gt;

&lt;h2 id=&quot;the-hypothesis-testing-framework-an-indirect-approach&quot;&gt;The Hypothesis Testing Framework: An Indirect Approach&lt;/h2&gt;

&lt;p&gt;Frequentist hypothesis testing is based on a somewhat counterintuitive indirect logic. Instead of directly evaluating the evidence for the hypothesis we care about, we construct a &lt;strong&gt;null hypothesis&lt;/strong&gt;, usually denoted \(H_0\), representing the state of “no effect” or “no difference”, and then try to find evidence against it.&lt;/p&gt;

&lt;p&gt;For example, suppose we want to know whether a new drug is effective at lowering blood pressure. Instead of directly asking “Is this drug effective?” or “How large is the drug’s effect?”, the hypothesis testing framework requires us to set up:&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;null hypothesis&lt;/strong&gt; \(H_0\) says that the drug has no effect, i.e., the mean change in blood pressure equals 0, while the &lt;strong&gt;alternative hypothesis&lt;/strong&gt; \(H_1\) says that the drug has an effect, i.e., that mean change is not 0.&lt;/p&gt;

&lt;p&gt;The logic of hypothesis testing is: &lt;strong&gt;if the observed data would be very unusual if \(H_0\) were true, then we have evidence against \(H_0\) and can “reject” it&lt;/strong&gt;. This is a form of proof by contradiction, similar to mathematics, but with an important difference: &lt;strong&gt;in statistics, we can never prove anything with certainty, we can only talk about how unusual the data is&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This indirect approach has historical roots in the work of Ronald Fisher, Jerzy Neyman, and Egon Pearson in the early 20th century. It was designed to provide an objective procedure for making decisions based on data. However, as we will see, this objectivity comes at a steep price.&lt;/p&gt;

&lt;h2 id=&quot;the-p-value-the-precise-definition&quot;&gt;The P-value: The Precise Definition&lt;/h2&gt;

&lt;p&gt;The p-value is the central concept of hypothesis testing, but also one of the most misunderstood concepts in statistics. Let us start with the precise definition:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The p-value is the probability of observing data at least as unusual as the actual data (or more unusual), given that the null hypothesis is true.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Formally, if \(T\) is a &lt;strong&gt;test statistic&lt;/strong&gt; computed from the data, and \(t_{obs}\) is its observed value, then:&lt;/p&gt;

\[p = P(T \geq t_{obs} \mid H_0)\]

&lt;p&gt;(for a one-sided test, or a similar formula for a two-sided test)&lt;/p&gt;

&lt;p&gt;Let us analyze this definition carefully, because every part is important:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;“Probability”&lt;/strong&gt;: The p-value is a probability, lying between 0 and 1.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;“Observing data at least as unusual as…“&lt;/strong&gt;: We do not compute only the probability of the exact data we observe, but the probability of this data plus all the outcomes that are “more extreme” in a given direction.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;“Given that the null hypothesis is true”&lt;/strong&gt;: This is the most important part and is often overlooked. The p-value does &lt;strong&gt;not&lt;/strong&gt; tell you the probability that the null hypothesis is true. It tells you the probability of the data &lt;strong&gt;if&lt;/strong&gt; the null hypothesis is true.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The difference between \(P(\text{data} \mid H_0)\) and \(P(H_0 \mid \text{data})\) is fundamental. The p-value gives you the former, but what scientists really want to know is usually the latter. This is one of the main sources of misunderstanding about p-values.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;explaining-each-component&quot;&gt;Explaining Each Component&lt;/h3&gt;

&lt;h4 id=&quot;1-the-null-hypothesis-is-true-h_0-is-true&quot;&gt;(1) “The null hypothesis is true” (\(H_0\) is true)&lt;/h4&gt;

&lt;p&gt;This condition is extremely important:&lt;/p&gt;

&lt;p&gt;We always &lt;strong&gt;assume in advance&lt;/strong&gt; that \(H_0\) is true, and only then ask: if \(H_0\) really is true, is data that looks like this rare?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If \(H_0\) says the drug has no effect but the data gives the impression that the drug seems effective, then the p-value answers the question: if the drug really has no effect, what is the probability of still observing a result at least this extreme?&lt;/p&gt;

&lt;h4 id=&quot;2-what-does-unusual-data-mean&quot;&gt;(2) What does “unusual data” mean?&lt;/h4&gt;

&lt;p&gt;“Unusual” is not a feeling, but is defined by:&lt;/p&gt;

&lt;p&gt;“Unusual” here is not a subjective feeling but is defined through a &lt;strong&gt;test statistic&lt;/strong&gt; such as the z-score, t-statistic or \(\chi^2\), i.e., how far the data lies from the expectation under \(H_0\).&lt;/p&gt;

&lt;p&gt;For example, the sample mean may deviate far from the mean expected under \(H_0\), the difference between two groups may be very large, or the statistic may fall deep into the tail of the distribution; the farther from the center of expectation, the more extreme the data and therefore the more it is regarded as unusual.&lt;/p&gt;

&lt;h4 id=&quot;3-at-least-as-unusual-as-the-observed-data-or-more-unusual&quot;&gt;(3) “At least as unusual as the observed data (or more unusual)”&lt;/h4&gt;

&lt;p&gt;This is the part that is often missed but very important.&lt;/p&gt;

&lt;p&gt;The p-value &lt;strong&gt;does not only&lt;/strong&gt; compute the probability of exactly the result you see, but computes:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The probability of the observed result &lt;strong&gt;and all the more extreme results&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Example (two-sided test):&lt;/strong&gt; suppose we observe \(z = 2.1\). Then the p-value is \(P(\mid Z \mid \geq 2.1 \mid H_0 \text{ true})\). In other words, we do not compute only the probability of exactly 2.1, but also values such as 2.5, 3.0, and every more extreme value on both sides.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;what-the-p-value-does-not-say&quot;&gt;What the P-value Does NOT Say&lt;/h3&gt;

&lt;p&gt;This is a point that is very often misunderstood: the p-value is not the probability that the null hypothesis is false, is not the probability that the result is “due to chance”, and is also not a direct measure of effect size.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Wrong example:&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“P-value = 0.03 means there is a 97% chance \(H_0\) is false” ❌&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Correct interpretation:&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“If \(H_0\) is true, then the probability of observing data at least this extreme is 3%.” ✅&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;a-brief-intuitive-interpretation&quot;&gt;A Brief Intuitive Interpretation&lt;/h3&gt;

&lt;p&gt;A simple way of putting it that is true to its nature:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The p-value measures how “hard to believe” the data is, if we believe the null hypothesis is true.&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;put-more-briefly-a-small-p-shows-the-data-is-unlikely-if-h_0-is-true-so-we-have-more-reason-to-doubt-h_0-while-a-large-p-only-shows-the-data-does-not-strongly-contradict-h_0&quot;&gt;Put more briefly, a small p shows the data is unlikely if \(H_0\) is true so we have more reason to doubt \(H_0\), while a large p only shows the data does not strongly contradict \(H_0\).&lt;/h2&gt;

&lt;h2 id=&quot;a-concrete-example-the-t-test&quot;&gt;A Concrete Example: The T-test&lt;/h2&gt;

&lt;p&gt;Let us consider a concrete example to clarify the concepts. Suppose we want to test whether the average height of male students at a university differs from 170 cm. We measure the height of 25 randomly chosen male students and compute the sample mean height \(\bar{x} = 172.5\) cm with sample standard deviation \(s = 6.2\) cm.&lt;/p&gt;

&lt;p&gt;We set up \(H_0\) that \(\mu = 170\), i.e., the population mean height is 170 cm, and \(H_1\) that \(\mu \neq 170\), i.e., the population mean height differs from 170 cm.&lt;/p&gt;

&lt;p&gt;The t test statistic is computed as:&lt;/p&gt;

\[t = \frac{\bar{x} - \mu_0}{s / \sqrt{n}} = \frac{172.5 - 170}{6.2 / \sqrt{25}} = \frac{2.5}{1.24} \approx 2.02\]

&lt;p&gt;With \(n - 1 = 24\) degrees of freedom, we consult the t distribution table (or use software) to find the probability of observing a value \(\mid t \mid \geq 2.02\) if \(H_0\) is true. Suppose we find \(p \approx 0.054\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_ttest_illustration.png&quot; alt=&quot;Illustration of the P-value in a T-test&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates the p-value in the t-test. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;What does this mean? It means that &lt;strong&gt;if&lt;/strong&gt; the population mean height truly is 170 cm, and we repeat this experiment many times (each time taking 25 random samples), then in about 5.4% of the repetitions we would observe a t value with magnitude at least 2.02.&lt;/p&gt;

&lt;p&gt;This p-value does not tell us that the probability \(H_0\) is true is 5.4%, nor that the probability \(H_1\) is true is 94.6%; it also does not directly say how large the effect size is or how practically meaningful the study is.&lt;/p&gt;

&lt;h3 id=&quot;a-more-correct-reading-of-p--0054&quot;&gt;A More Correct Reading of \(p = 0.054\)&lt;/h3&gt;

&lt;p&gt;The number \(0.054\) is often irritating because it sits very close to the 0.05 threshold. A more reasonable reading is not “a complete failure”, but: this data creates a moderate level of conflict with \(H_0\), but not strong enough to reach a definitive conclusion under the traditional convention. If a nearly identical study gave \(p=0.049\), in terms of practical evidence the two results are barely different.&lt;/p&gt;

&lt;p&gt;This is why many statisticians advise against turning the p-value into an on/off binary switch. More important is to also look at the effect size, the confidence interval, the quality of the study design, and the scientific context of the question under consideration.&lt;/p&gt;

&lt;h3 id=&quot;experiment-the-p-value-under-h-is-uniformly-distributed&quot;&gt;Experiment: the p-value under H₀ is uniformly distributed&lt;/h3&gt;

&lt;p&gt;Repeat the experiment many times: when there is no effect, about 5% of experiments still give p &amp;lt; 0.05.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;pvalue-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;pnull&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/public/js/explainers/bayes-explainer.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;significance-thresholds-and-decisions-the-alpha--005-convention&quot;&gt;Significance Thresholds and Decisions: The \(\alpha = 0.05\) Convention&lt;/h2&gt;

&lt;p&gt;In practice, p-values are often compared with a pre-specified &lt;strong&gt;significance level&lt;/strong&gt;, usually denoted \(\alpha\). The most common convention is \(\alpha = 0.05\), although other values such as 0.01 or 0.10 are also sometimes used.&lt;/p&gt;

&lt;h4 id=&quot;a-simple-decision-rule&quot;&gt;A simple decision rule:&lt;/h4&gt;

&lt;p&gt;Under the traditional convention, if \(p &amp;lt; \alpha\) we reject \(H_0\) and call the result “statistically significant”; and if \(p \geq \alpha\) we do not reject \(H_0\) and say that there is not yet enough statistical evidence against it.&lt;/p&gt;

&lt;p&gt;In our height example, with \(p = 0.054\) and \(\alpha = 0.05\), we would &lt;strong&gt;fail to reject&lt;/strong&gt; \(H_0\). We would conclude that there is not enough evidence to say that the mean height differs from 170 cm.&lt;/p&gt;

&lt;p&gt;But let us stop and think about this. The difference between \(p = 0.054\) and \(p = 0.049\) is very small, but it leads to two completely different conclusions under this rule. One result is called “statistically significant” and the other “not statistically significant”, even though the evidence in the data is nearly identical.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_misinterpretation_alpha_cutoff.png&quot; alt=&quot;Two nearby p-values falling on two sides of the alpha threshold&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Illustration: When the p-value sits right at the \(\alpha = 0.05\) threshold, a very small difference can still be interpreted as two completely different binary conclusions.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Moreover, the threshold \(\alpha = 0.05\) is completely arbitrary. Ronald Fisher, who proposed it, said explicitly that it was only a rough guideline, not a rigid rule. In practice, however, it has become a magic threshold that researchers feel they must cross to publish their results.&lt;/p&gt;

&lt;p&gt;Relying on this rigid threshold has many negative consequences: it encourages “p-hacking”, pushes researchers into binary thinking of the “effect or no effect” kind, and obscures more important information such as the effect size or the uncertainty of the estimate.&lt;/p&gt;

&lt;h3 id=&quot;experiment-the-power-of-a-t-test&quot;&gt;Experiment: the power of a t-test&lt;/h3&gt;

&lt;p&gt;Power increases with sample size and effect size; at d = 0 it equals α.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;pvalue-explainer&quot; data-lang=&quot;en&quot; data-tab=&quot;power&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;common-misconceptions-about-p-values&quot;&gt;Common Misconceptions About P-values&lt;/h2&gt;

&lt;p&gt;P-values are one of the most misunderstood concepts in science. Let us look at some common misconceptions:&lt;/p&gt;

&lt;h3 id=&quot;misconception-1-the-p-value-is-the-probability-that-the-null-hypothesis-is-true&quot;&gt;Misconception 1: The p-value is the probability that the null hypothesis is true&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Wrong:&lt;/strong&gt; “\(p = 0.03\) means there is a 3% chance the null hypothesis is true.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Correct:&lt;/strong&gt; The p-value is the probability of the data (or more extreme data) &lt;strong&gt;if&lt;/strong&gt; the null hypothesis is true, not the probability that the null hypothesis is true after seeing the data.&lt;/p&gt;

&lt;p&gt;This difference is fundamental. To compute \(P(H_0 \mid \text{data})\), we need Bayes’ theorem and a prior probability for \(H_0\), which the frequentist framework does not provide.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_misinterpretation_h0_probability.png&quot; alt=&quot;The p-value is not the probability of the null hypothesis&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Illustration: The p-value lives in the direction of \(P(\text{data} \mid H_0)\), not the direction of \(P(H_0 \mid \text{data})\) that researchers usually actually want to know.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;misconception-2-1---p-is-the-probability-that-the-alternative-hypothesis-is-true&quot;&gt;Misconception 2: \(1 - p\) is the probability that the alternative hypothesis is true&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Wrong:&lt;/strong&gt; “If \(p = 0.05\), then there is a 95% chance the alternative hypothesis is true.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Correct:&lt;/strong&gt; The p-value gives you no direct information about the probability of the alternative hypothesis.&lt;/p&gt;

&lt;h3 id=&quot;misconception-3-a-small-p-value-means-a-large-effect&quot;&gt;Misconception 3: A small p-value means a large effect&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Wrong:&lt;/strong&gt; “\(p &amp;lt; 0.001\) means the effect is very strong.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Correct:&lt;/strong&gt; A small p-value only means the data would be very unusual if \(H_0\) were true. This can happen because of a large effect, but it can also happen because of a large sample size with a small effect.&lt;/p&gt;

&lt;p&gt;For example, with a large enough sample, you can find a “statistically significant” difference between two groups even when the actual difference is very small and has no practical significance.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_misinterpretation_small_p_large_effect.png&quot; alt=&quot;A small p-value does not mean a large effect&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Illustration: A very small p-value can still come from a small effect if the sample size is large enough.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_large_n_small_effect.png&quot; alt=&quot;Large sample with a small effect&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1a: With a large sample (n = 1000), a very small effect can still give a “statistically significant” p-value.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_small_n_large_effect.png&quot; alt=&quot;Small sample with a large effect&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1b: With a small sample (n = 20), even a large effect may fail to reach the statistical significance threshold. The p-value therefore does not directly measure effect size.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;misconception-4-a-large-p-value-proves-the-null-hypothesis-is-true&quot;&gt;Misconception 4: A large p-value proves the null hypothesis is true&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Wrong:&lt;/strong&gt; “\(p = 0.80\) means the null hypothesis is true.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Correct:&lt;/strong&gt; A large p-value only means the data is not unusual if \(H_0\) is true. This can happen because \(H_0\) really is true, or because we do not have enough data to detect a difference.&lt;/p&gt;

&lt;p&gt;“Absence of evidence of an effect” is not the same as “evidence of no effect”.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pvalue_misinterpretation_large_p_h0_true.png&quot; alt=&quot;A large p-value does not prove the null hypothesis is true&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Illustration: A large p-value only shows the data does not strongly contradict \(H_0\); it does not prove \(H_0\) is true.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;misconception-5-the-p-value-measures-reproducibility&quot;&gt;Misconception 5: The p-value measures reproducibility&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Wrong:&lt;/strong&gt; “\(p = 0.05\) means if I repeat the study, I have a 95% chance of finding a similar result.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Correct:&lt;/strong&gt; The p-value tells you nothing about reproducibility. In fact, research shows that many results with \(p\) near 0.05 cannot be replicated.&lt;/p&gt;

&lt;h2 id=&quot;the-problem-with-null-hypothesis-testing&quot;&gt;The Problem with Null Hypothesis Testing&lt;/h2&gt;

&lt;p&gt;A fundamental problem with the hypothesis testing framework is that the null hypothesis itself is often implausible. In many real situations, we know in advance that the null hypothesis is almost certainly false.&lt;/p&gt;

&lt;p&gt;For example, consider the null hypothesis “drug A and drug B have exactly the same effectiveness”. In reality, two different drugs will almost certainly have some difference, however small, in their effectiveness. With a large enough sample, we can always reject this null hypothesis, but that tells us nothing useful about whether the difference is large enough to matter.&lt;/p&gt;

&lt;p&gt;The real question scientists care about is usually not “Is there any effect?” but “How large is the effect?” and “How sure are we of our estimate?” Hypothesis testing does not answer these questions directly.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/multiple_testing_false_positive_example.png&quot; alt=&quot;An example of a false positive when testing repeatedly&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 2a: When running many independent tests, chance alone can produce a few results that exceed the statistical significance threshold.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/multiple_testing_uniform_pvalues.png&quot; alt=&quot;The p-value distribution is nearly uniform when H0 is true&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 2b: When \(H_0\) is true, p-values tend to spread nearly uniformly over \([0,1]\), so trying enough times almost guarantees a few very small p-values.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;That is the nature of the multiple testing problem (p-hacking): when running 20 independent tests with \(\alpha = 0.05\), even if \(H_0\) is true for all of the tests (no real effect), we still expect to find about 1 “statistically significant” result by chance. This is one of the main sources of the replication crisis in science.&lt;/p&gt;

&lt;h2 id=&quot;confidence-intervals-a-better-approach&quot;&gt;Confidence Intervals: A Better Approach?&lt;/h2&gt;

&lt;p&gt;An alternative frequentist method to hypothesis testing is the &lt;strong&gt;confidence interval&lt;/strong&gt;. A 95% confidence interval for a parameter \(\theta\) is an interval \([L, U]\) constructed from the data such that:&lt;/p&gt;

\[P(L \leq \theta \leq U) = 0.95\]

&lt;p&gt;where the probability is computed over all possible samples (with \(\theta\) fixed).&lt;/p&gt;

&lt;p&gt;Confidence intervals seem more attractive than p-values because they provide information about the effect size and the uncertainty. However, they still have a fundamental interpretation problem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Correct interpretation:&lt;/strong&gt; “If we repeat the experiment many times and compute a 95% confidence interval each time, then 95% of the intervals will contain the true value of \(\theta\).”&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/confidence_interval_repeated_experiments.png&quot; alt=&quot;Many confidence intervals across repeated experiments&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 3a: A confidence interval is a statement about a repeated procedure; looking across many experiments, about 95% of the intervals contain the true value.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Wrong (but common) interpretation:&lt;/strong&gt; “There is a 95% chance the true value of \(\theta\) lies in this interval.”&lt;/p&gt;

&lt;p&gt;The difference is subtle but important. In the frequentist framework, \(\theta\) is a fixed value (though unknown), not a random variable, so it is meaningless to talk about its “probability”. The probability in the definition of a confidence interval is about the intervals, not about the parameter.&lt;/p&gt;

&lt;p&gt;However, what scientists really want to know is the second interpretation: given this specific data, how likely is the parameter to lie in this interval? This is exactly what the &lt;strong&gt;Bayesian credible interval&lt;/strong&gt; provides.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/credible_interval_single_posterior.png&quot; alt=&quot;A credible interval on the posterior of a specific experiment&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 3b: A credible interval is a direct statement on the posterior of the current experiment, so we can immediately talk about the probability that the parameter lies in that interval.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;why-are-p-values-still-widely-used&quot;&gt;Why Are P-values Still Widely Used?&lt;/h2&gt;

&lt;p&gt;With all these problems, why do p-values and hypothesis testing still dominate scientific research? The first reason is history and academic inertia: p-values have been taught and used for decades, so changing the statistical practice of the whole scientific community happens very slowly. The second reason is their superficial simplicity: a single number and a decision rule seem clear, even though that simplicity actually hides many problems. The third reason comes from the publishing mechanism, since many journals still prefer “statistically significant” results with \(p &amp;lt; 0.05\). Finally, many researchers have not been fully trained in alternative methods such as Bayesian or other modern statistical methods.&lt;/p&gt;

&lt;p&gt;However, there are signs that this is changing. Many statistical organizations and scientific journals have issued statements warning about the misuse of p-values and encouraging alternative methods.&lt;/p&gt;

&lt;h3 id=&quot;experiment-confidence-intervals-and-credible-intervals&quot;&gt;Experiment: confidence intervals and credible intervals&lt;/h3&gt;

&lt;p&gt;Repeat the experiment many times to see the frequentist meaning of “95%”.&lt;/p&gt;

&lt;div class=&quot;interactive-demo&quot;&gt;
  &lt;div data-demo=&quot;interval-explainer&quot; data-lang=&quot;en&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;the-bayesian-approach-a-more-natural-approach&quot;&gt;The Bayesian Approach: A More Natural Approach&lt;/h2&gt;

&lt;p&gt;The Bayesian approach offers a more natural and direct approach to the questions that hypothesis testing tries to answer. Instead of asking “How unusual would this data be if the null hypothesis were true?”, the Bayesian approach asks “Given this data, what should our belief about the parameter be?”&lt;/p&gt;

&lt;p&gt;In the Bayesian framework:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;We start with a prior&lt;/strong&gt;: Before seeing the data, we encode our initial belief about the parameter in a prior distribution \(P(\theta)\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;We update with data&lt;/strong&gt;: Using Bayes’ theorem, we combine the prior with the likelihood of the data to obtain the posterior distribution:&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

\[P(\theta \mid \text{data}) = \frac{P(\text{data} \mid \theta) \cdot P(\theta)}{P(\text{data})}\]

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;We interpret the posterior directly&lt;/strong&gt;: The posterior distribution tells us directly about the probability of different values of \(\theta\) given the observed data.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For example, instead of saying “we reject the hypothesis that the drug effect is 0 with \(p = 0.03\)”, we can say “given this data, there is a 95% posterior probability that the drug effect lies between 2 and 8 mmHg”. The latter answers directly the question scientists care about.&lt;/p&gt;

&lt;p&gt;Moreover, the Bayesian approach lets us compute the probabilities of different hypotheses, combine information from many studies naturally, make predictions for future data, and quantify uncertainty in a more direct, more interpretable way.&lt;/p&gt;

&lt;h2 id=&quot;when-should-we-use-p-values&quot;&gt;When Should We Use P-values?&lt;/h2&gt;

&lt;p&gt;Despite their many limitations, p-values are not always useless. They can still be useful as a quick screening tool to find data patterns worth investigating further, as a preliminary check of model fit, or in contexts that truly need a clear binary decision, such as some quality-control problems.&lt;/p&gt;

&lt;p&gt;However, even in these cases, p-values should be used with a full understanding of their limitations and should be supplemented by other measures such as the effect size and confidence intervals.&lt;/p&gt;

&lt;h2 id=&quot;practical-guidelines&quot;&gt;Practical Guidelines&lt;/h2&gt;

&lt;p&gt;If you must use or interpret p-values, you should not report the p-value alone but accompany it with the effect size, the confidence interval, and the sample size; nor should you use a rigid threshold to turn inference into a simple binary decision. The important thing is to always remember that the p-value is \(P(\text{data} \mid H_0)\) and not \(P(H_0 \mid \text{data})\), and also to place the result in the context of effect size, practical significance, and the quality of the study design. In many questions, Bayesian or estimation-based methods will be the more appropriate choice.&lt;/p&gt;

&lt;h2 id=&quot;implications-for-bayesian-data-analysis&quot;&gt;Implications for Bayesian Data Analysis&lt;/h2&gt;

&lt;p&gt;This lesson on p-values and hypothesis testing is not just an academic exercise. It provides important motivation for learning Bayesian methods.&lt;/p&gt;

&lt;p&gt;As you progress through this course, you will see that the Bayesian approach solves many of the problems we have discussed. It lets us speak directly about the probability of hypotheses and parameters, provides more interpretable uncertainty estimates, does not depend on arbitrary decision thresholds, supports incorporating prior knowledge naturally, and shifts the focus from mere testing to estimation and prediction.&lt;/p&gt;

&lt;p&gt;However, the Bayesian approach is not a magic solution to all problems. It has its own challenges, especially in computation and the choice of priors. But for many research questions, it provides a more natural and coherent approach than traditional hypothesis testing.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-one-sample-z-test-by-hand-and-why-sample-size-drives-p-values&quot;&gt;Worked Numerical Example: One-Sample Z-Test by Hand (and Why Sample Size Drives p-values)&lt;/h3&gt;

&lt;p&gt;Suppose a factory claims lightbulbs last \(\mu_0 = 1000\text{ hours}\) (known \(\sigma = 100\text{ hours}\)). You test \(n = 25\) bulbs and observe \(\bar{x} = 955\text{ hours}\) (two-sided test, \(\alpha = 0.05\)):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Standard error of the mean:&lt;/strong&gt; \(\mathrm{SE} = \frac{100}{\sqrt{25}} = 20\text{ hours}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Test statistic:&lt;/strong&gt; \(z = \frac{955 - 1000}{20} = -2.25\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Two-sided p-value:&lt;/strong&gt; \(P(\lvert Z
vert \ge 2.25) = 2 \times 0.0122 = \mathbf{0.0244} &amp;lt; 0.05\) \(\implies\) reject \(H_0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Now check the sample-size sensitivity:&lt;/strong&gt; Suppose the true difference were a tiny &lt;strong&gt;5 hours&lt;/strong&gt; (\(\bar{x} = 995\)):
    &lt;ul&gt;
      &lt;li&gt;At \(n = 25\): \(z = -5/20 = -0.25 \implies p = 0.80\) (not significant).&lt;/li&gt;
      &lt;li&gt;At \(n = 25{,}000\): \(\mathrm{SE} = 100/\sqrt{25{,}000} \approx 0.632 \implies z = -7.91 \implies p &amp;lt; 10^{-14}\) (“highly significant” for a trivial 0.5% change!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-reading-p-values-without-falling-into-traps&quot;&gt;Explanation: Four Rules for Reading p-values Without Falling Into Traps&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Never translate &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p = 0.024&lt;/code&gt; as “2.4% chance \(H_0\) is true”:&lt;/strong&gt; That flips \(P(D\mid H_0)\) into \(P(H_0\mid D)\), ignoring the prior plausibility of \(H_0\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never interpret &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p = 0.20&lt;/code&gt; as “proof of no effect”:&lt;/strong&gt; High p-values often just mean low sample size / low statistical power.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always pair p-values with effect size and confidence/credible intervals:&lt;/strong&gt; Knowing the bulb lasts \(955 \pm 39.2\text{ hours}\) tells you &lt;em&gt;how much&lt;/em&gt; shorter it lasts, not just whether it differs from 1000.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Watch out for multiple comparisons and stopping early:&lt;/strong&gt; Testing 20 hypotheses at \(\alpha = 0.05\) gives a \(1 - 0.95^{20} = 64.2\%\) chance of at least one false positive!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the lightbulb test above (\(\mu_0 = 1000, \sigma = 100, \bar{x} = 955\)), if you had only tested \(n = 9\) bulbs instead of \(25\), what would the new \(z\)-statistic be, and would you still reject \(H_0\) at \(\alpha = 0.05\) (\(\lvert z
vert &amp;gt; 1.96\))?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vemZtEM63GY&quot;&gt;p-values: What they are and how to interpret them&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the definition of the p-value as the probability of extreme data under the null hypothesis, exactly the part where the lesson wants p-values read correctly.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=0oc49DyA3hU&quot;&gt;Hypothesis Testing and The Null Hypothesis, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch the role of the null hypothesis and the testing procedure, supporting the first half of the lesson on the frequentist framework.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=TqOeMYtOc1w&quot;&gt;Confidence Intervals, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch how a frequentist confidence interval is built from repeated samples, to contrast with the part of the lesson on the limits of this interpretation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1: Interpreting P-values.&lt;/strong&gt; A study compares two teaching methods and reports “\(p = 0.04\)”. Write three interpretations: (a) a correct interpretation of the meaning of this p-value, (b) a common wrong interpretation, and (c) an explanation of why the wrong interpretation is wrong and why the difference matters.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2: Sample Size and P-values.&lt;/strong&gt; Suppose the average height of men in population A is 175.0 cm and in population B is 175.5 cm (a very small difference). The standard deviation in both populations is 7 cm. (a) Using the two-sample t-test formula, estimate the sample size needed to have \(p &amp;lt; 0.05\) when comparing these two populations. (b) Discuss the meaning of this result: is “statistical significance” equivalent to “practical significance”?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/sample_size_calculation.png&quot; alt=&quot;Sample Size Calculation&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates the sample size calculation. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The figure above shows the relationship between the effect size and the sample size needed to detect that effect with power = 0.80 and α = 0.05. Note that to detect a small effect (0.5 cm), we need a very large sample (more than 1500 people per group), whereas a large effect (2.0 cm) needs only about 100 people per group.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3: P-hacking.&lt;/strong&gt; A researcher collects data on 20 different variables and tests whether each variable is correlated with an outcome of interest, using \(\alpha = 0.05\) for each test. (a) If in reality none of the variables is correlated with the outcome, what is the probability of finding at least one “statistically significant” result? (b) What kind of problem is this an example of? (c) Propose two ways to address this problem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4: Comparing Confidence Intervals and Credible Intervals.&lt;/strong&gt; Suppose you read two reports: (a) “The 95% confidence interval for the drug effect is [2, 8] mmHg” (frequentist), and (b) “The 95% credible interval for the drug effect is [2, 8] mmHg” (Bayesian). Write the precise interpretation for each interval. Which interval answers more directly the question a doctor cares about? Why?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5: Case Study.&lt;/strong&gt; Find a scientific paper in a field you are interested in that uses p-values. (a) Do the authors interpret p-values correctly? (b) Do they report effect sizes and confidence intervals? (c) If you were a reviewer, what improvements would you suggest for the statistical analysis? (d) Would a Bayesian approach be more suitable for this research question? Why?&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;h3 id=&quot;primary-references&quot;&gt;Primary References:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., &amp;amp; Rubin, D. B. (2013).&lt;/strong&gt; &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 4: Asymptotics and connections to non-Bayesian approaches&lt;/li&gt;
  &lt;li&gt;Chapter 6: Model checking&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kruschke, J. K. (2015).&lt;/strong&gt; &lt;em&gt;Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan&lt;/em&gt; (2nd Edition). Academic Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 11: Null Hypothesis Significance Testing&lt;/li&gt;
  &lt;li&gt;Chapter 12: Bayesian Approaches to Testing a Point (“Null”) Hypothesis&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;critical-papers-on-p-values&quot;&gt;Critical Papers on P-values:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Wasserstein, R. L., &amp;amp; Lazar, N. A. (2016).&lt;/strong&gt; The ASA’s statement on p-values: context, process, and purpose. &lt;em&gt;The American Statistician&lt;/em&gt;, 70(2), 129-133.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ioannidis, J. P. (2005).&lt;/strong&gt; Why most published research findings are false. &lt;em&gt;PLoS Medicine&lt;/em&gt;, 2(8), e124.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nuzzo, R. (2014).&lt;/strong&gt; Scientific method: statistical errors. &lt;em&gt;Nature&lt;/em&gt;, 506(7487), 150-152.&lt;/p&gt;

&lt;h3 id=&quot;supplementary-reading&quot;&gt;Supplementary Reading:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;McShane, B. B., Gal, D., Gelman, A., Robert, C., &amp;amp; Tackett, J. L. (2019).&lt;/strong&gt; Abandon statistical significance. &lt;em&gt;The American Statistician&lt;/em&gt;, 73(sup1), 235-245.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Greenland, S., Senn, S. J., Rothman, K. J., Carlin, J. B., Poole, C., Goodman, S. N., &amp;amp; Altman, D. G. (2016).&lt;/strong&gt; Statistical tests, P values, confidence intervals, and power: a guide to misinterpretations. &lt;em&gt;European Journal of Epidemiology&lt;/em&gt;, 31(4), 337-350.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_09_t_test_and_t_distribution/&quot;&gt;0.12 T-test and the T Distribution&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.10: Probability Density Function (PDF) - In Detail</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_07_probability_density_functions/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_07_probability_density_functions</id>
   <content type="html">&lt;p&gt;A student plots a continuous probability distribution, sees a peak value of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;f(x) = 3.5&lt;/code&gt;, and panics: &lt;em&gt;“Wait—how can a probability be greater than 1?!”&lt;/em&gt; That moment of confusion is one of the most important conceptual hurdles in continuous probability: &lt;strong&gt;a Probability Density Function (PDF) is NOT a probability&lt;/strong&gt;—it is probability &lt;em&gt;per unit length&lt;/em&gt; (density), just as physical density (kg/m\(^3\)) only becomes mass when you multiply by volume!&lt;/p&gt;

&lt;p&gt;This lesson builds crystal-clear intuition for continuous PDFs, CDFs, why \(P(X = c) = 0\) at any exact point, and how density values greater than 1 arise routinely in tight Bayesian posteriors.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-density-area-and-continuous-bayesian-posteriors&quot;&gt;Key ideas: Density, Area, and Continuous Bayesian Posteriors&lt;/h2&gt;

&lt;p&gt;Four concepts eliminate every misconception about continuous densities:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Density vs. Probability Mass:&lt;/strong&gt; For a continuous variable \(X\), \(f(x) \ge 0\) can be &lt;em&gt;arbitrarily large&lt;/em&gt; (e.g., \(f(x) = 10\) on \([0, 0.1]\)) as long as the total &lt;strong&gt;area&lt;/strong&gt; integrates to 1: \(\int_{-\infty}^{\infty} f(x)\,dx = 1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Intervals Carry Probability, Points Have Zero Area:&lt;/strong&gt; \(P(a \le X \le b) = \int_a^b f(x)\,dx = F(b) - F(a)\), whereas for any single exact point \(c\), \(P(X = c) = 0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;PDF–CDF Derivative Pair:&lt;/strong&gt; The Cumulative Distribution Function \(F(x) = P(X \le x)\) climbs monotonically from 0 to 1, and its slope is the PDF: \(f(x) = F&apos;(x)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why Posterior PDFs Easily Exceed 1:&lt;/strong&gt; As you collect more data, a Bayesian posterior narrows around the true parameter (say width \(\approx 0.02\)); to keep total area equal to 1, its peak height &lt;em&gt;must&lt;/em&gt; shoot up to roughly \(1 / 0.02 = 50\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;This lesson presents a systematic treatment of the &lt;strong&gt;probability density function (PDF), the essential difference between the PDF and the probability mass function (PMF)&lt;/strong&gt;, as well as how to correctly interpret the PDF in continuous models.&lt;/p&gt;

&lt;h2 id=&quot;1-from-discrete-to-continuous&quot;&gt;1. From Discrete to Continuous&lt;/h2&gt;

&lt;h3 id=&quot;11-discrete-random-variables---pmf&quot;&gt;1.1. Discrete Random Variables - PMF&lt;/h3&gt;

&lt;p&gt;For a &lt;strong&gt;discrete&lt;/strong&gt; random variable \(X\), we have the &lt;strong&gt;Probability Mass Function (PMF)&lt;/strong&gt; \(P(X = x)\). This function gives the exact probability that the random variable takes a specific value. For example, when rolling a fair die, each face from 1 to 6 has probability \(P(X = k) = 1/6\). The important thing to remember is that for a discrete variable, \(P(X = x)\) &lt;strong&gt;is a true probability&lt;/strong&gt;, with values from 0 to 1, and the sum of all probabilities equals 1.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;properties of the PMF&lt;/strong&gt; can be summarized briefly as follows: \(P(X = x) \geq 0\) for all \(x\), the sum of all probabilities \(\sum_{\text{all } x} P(X = x)\) equals 1, and most importantly \(P(X = x)\) in the discrete case really is a probability with a direct meaning.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_pmf_dice.png&quot; alt=&quot;PMF of a fair die&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: Look at each bar individually, because in a PMF each bar is exactly the probability at a specific value.&lt;/em&gt;
&lt;em&gt;Figure 1: The PMF of a fair die. Each value from 1 to 6 carries exactly probability \(1/6\), and the sum of all the bars equals 1.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;12-the-problem-with-continuous-variables&quot;&gt;1.2. The Problem with Continuous Variables&lt;/h3&gt;

&lt;p&gt;Now consider a continuous random variable. Suppose adult height follows a normal distribution \(X \sim \mathcal{N}(170, 10^2)\) cm. A natural question is: what is \(P(X = 170)\)?&lt;/p&gt;

&lt;p&gt;The surprising answer is &lt;strong&gt;0&lt;/strong&gt;! In fact, \(P(X = k)\) equals 0 for &lt;strong&gt;every&lt;/strong&gt; specific value \(k\), whether 170, 170.5, or 170.000001. The reason is that there are &lt;strong&gt;infinitely many&lt;/strong&gt; possible values the height can take. Between 170 cm and 171 cm, there are infinitely many different values: 170.1, 170.01, 170.001, and so on to infinity. If each value had a positive probability, the sum of all probabilities would be infinite, violating the basic principle that the sum must equal 1.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_continuous_height.png&quot; alt=&quot;A continuous variable and the probability at a single point&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: Distinguish the red dot from the whole curve. The red dot shows the density value at 170 cm, while probability must still be understood as the area over an interval.&lt;/em&gt;
&lt;em&gt;Figure 2: For a continuous variable such as height, \(P(X=170)=0\) even though \(f(170)\) is nonzero. What is meaningful is the probability over an interval of heights, not at a single point.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Instead of asking for the probability at a point, we ask for the probability over an &lt;strong&gt;interval&lt;/strong&gt;:&lt;/p&gt;

\[P(a \leq X \leq b)\]

&lt;p&gt;For example, \(P(169.5 \leq X \leq 170.5)\) is the probability that the height lies between 169.5 cm and 170.5 cm. This probability can be computed and is nonzero.&lt;/p&gt;

&lt;h2 id=&quot;2-the-probability-density-function-pdf&quot;&gt;2. The Probability Density Function (PDF)&lt;/h2&gt;

&lt;h3 id=&quot;21-formal-definition&quot;&gt;2.1. Formal Definition&lt;/h3&gt;

&lt;p&gt;For a continuous random variable \(X\), the &lt;strong&gt;Probability Density Function (PDF)&lt;/strong&gt; \(f(x)\) is the function satisfying:&lt;/p&gt;

\[P(a \leq X \leq b) = \int_a^b f(x) \, dx\]

&lt;p&gt;This is the most important definition of the lesson. The probability that \(X\) lies in the interval \([a, b]\) is computed by the &lt;strong&gt;integral&lt;/strong&gt; (the area under the curve) of the density function \(f(x)\) from \(a\) to \(b\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The most important note&lt;/strong&gt; is that \(f(x)\) is not a probability. It is a probability density, and only the integral, i.e., the area under the curve of \(f(x)\), carries real probability meaning.&lt;/p&gt;

&lt;p&gt;This is the source of many common misunderstandings about the PDF. Many people confuse this and think \(f(x)\) is the probability at the point \(x\), but this is completely wrong. Remember: \(f(x)\) is only a density, like mass density in physics.&lt;/p&gt;

&lt;h3 id=&quot;22-why-is-it-called-density&quot;&gt;2.2. Why Is It Called “Density”?&lt;/h3&gt;

&lt;p&gt;The concept of “density” in statistics is analogous to &lt;strong&gt;mass density&lt;/strong&gt; in physics. In physics, the mass density \(\rho(x)\) (unit: kg/m³) is not a mass, but only tells how mass is distributed in space. To compute the actual mass, we must integrate: \(\text{Mass} = \int \rho(x) \, dx\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_mass_density_analogy.png&quot; alt=&quot;Mass density in physics&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 3: In physics, \(\rho(x)\) is only the mass density; the real mass comes from the area under the curve \(\rho(x)\) over the interval of interest.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Similarly in statistics, the probability density \(f(x)\) is not a probability, but tells how probability is “concentrated” around \(x\); to get an actual probability, we must integrate \(\int f(x)\,dx\), i.e., the area under the curve over the interval of interest.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_probability_density_analogy.png&quot; alt=&quot;Probability density in statistics&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 4: In statistics too, \(f(x)\) is not a probability; probability appears only when we take the area under the curve over an interval, for example \([-1,1]\).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;When \(f(x)\) is high at a point \(x\), it means probability is “concentrated” around that point - in other words, in a small interval around \(x\) there is more probability. When \(f(x)\) is low, probability is “sparser” around that point.&lt;/p&gt;

&lt;h3 id=&quot;23-properties-of-the-pdf&quot;&gt;2.3. Properties of the PDF&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Property 1: Non-negativity&lt;/strong&gt;: \(f(x) \geq 0\) for all \(x\)&lt;/p&gt;

&lt;p&gt;A probability density is never negative. This makes sense because a negative density would lead to negative probability (when integrated), which is meaningless.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Property 2: The integral equals 1&lt;/strong&gt;:&lt;/p&gt;

\[\int_{-\infty}^{\infty} f(x) \, dx = 1\]

&lt;p&gt;The total area under the whole PDF curve must equal 1, because the total probability of all possible outcomes must equal 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Property 3: \(f(x)\) can be greater than 1!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is an important point and often causes confusion. Since \(f(x)\) is not a probability, it can perfectly well be greater than 1. As long as the integral (total area) still equals 1, the PDF is valid.&lt;/p&gt;

&lt;p&gt;A first example is a very narrow normal distribution. When the standard deviation is small enough, the peak of the curve will exceed 1 and still be valid because the total area is still 1.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_exceeds_one_normal.png&quot; alt=&quot;A narrow normal distribution can have a peak greater than 1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 5: With \(X \sim \mathcal{N}(0, 0.3^2)\), the peak \(f(0)\) exceeds 1, but the entire area under the curve is still 1.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A second example is the uniform distribution on the interval \([0, 0.5]\). Here the PDF is exactly 2 over the whole interval, so the height is greater than 1 but the area is still only \(2 \times 0.5 = 1\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_exceeds_one_uniform.png&quot; alt=&quot;The uniform distribution on [0, 0.5] has density equal to 2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 6: The uniform distribution on \([0, 0.5]\) has \(f(x)=2&amp;gt;1\). What makes it valid is not the height, but that the total area is still 1.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Finally, there are distributions such as Beta(0.5, 0.5) that go even further: the density can shoot up near the endpoints 0 and 1. Even so, as long as the total integral is finite and equals 1, this is still a valid PDF.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_exceeds_one_beta.png&quot; alt=&quot;A Beta distribution whose density rises sharply at the endpoints&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 7: With Beta(0.5, 0.5), the density becomes very high near 0 and 1. This again reminds us that \(f(x)\) is not a point probability.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-a-deeper-understanding-of-the-pdf&quot;&gt;3. A Deeper Understanding of the PDF&lt;/h2&gt;

&lt;h3 id=&quot;31-the-pdf-as-the-limit-of-a-histogram&quot;&gt;3.1. The PDF as the Limit of a Histogram&lt;/h3&gt;

&lt;p&gt;An intuitive way to understand the PDF is through the histogram. When we draw a histogram of data with an increasing sample size and a decreasing bin width, the histogram gradually approaches the theoretical PDF curve. Mathematically, as the sample size \(n \to \infty\) and the bin width \(\Delta x \to 0\), the histogram converges to the PDF.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the sequence of figures below: go from small \(n\) to large \(n\) and watch the blue histogram gradually hug the red theoretical PDF curve.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n100.png&quot; alt=&quot;Histogram with n = 100&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 8: With \(n=100\), the histogram is still rough and fluctuates strongly around the theoretical curve.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n500.png&quot; alt=&quot;Histogram with n = 500&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 9: When \(n=500\), the bell shape begins to be clearer but there are still significant differences in individual bins.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n1000.png&quot; alt=&quot;Histogram with n = 1,000&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 10: With \(n=1{,}000\), the histogram already mimics the PDF fairly well, although sampling noise is still clearly visible.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n5000.png&quot; alt=&quot;Histogram with n = 5,000&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 11: At \(n=5{,}000\), the overall outline of the histogram is close to the theoretical PDF.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n10000.png&quot; alt=&quot;Histogram with n = 10,000&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 12: When \(n=10{,}000\), the difference is mostly just small fluctuations due to sampling.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_histogram_n50000.png&quot; alt=&quot;Histogram with n = 50,000&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 13: With \(n=50{,}000\), the histogram almost coincides with the theoretical PDF, showing that the PDF is the ideal limit when there is a great deal of data.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This observation is very important because it connects the theoretical PDF with real data. In practice, we never have infinite data, so we work with histograms or other estimates of the PDF. But as we get more data, our estimate gets closer to the true PDF.&lt;/p&gt;

&lt;h3 id=&quot;32-probability-over-small-intervals&quot;&gt;3.2. Probability over Small Intervals&lt;/h3&gt;

&lt;p&gt;Another useful way to understand the PDF is through approximation over small intervals. For a very small interval \([x, x + \Delta x]\):&lt;/p&gt;

\[P(x \leq X \leq x + \Delta x) \approx f(x) \cdot \Delta x\]

&lt;p&gt;This formula shows that the probability in a small interval is approximately the height of the PDF times the width of the interval. This is exactly the formula for the area of a rectangle with height \(f(x)\) and width \(\Delta x\).&lt;/p&gt;

&lt;p&gt;The smaller \(\Delta x\) is, the more accurate the approximation. Mathematically, we can write:&lt;/p&gt;

\[f(x) = \lim_{\Delta x \to 0} \frac{P(x \leq X \leq x + \Delta x)}{\Delta x}\]

&lt;p&gt;This formula shows that the PDF is the “derivative” of probability with respect to the variable \(x\). In other words, \(f(x)\) measures the rate of change of probability as we move along the \(x\) axis.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the sequence of figures below: compare the dashed green rectangle with the orange area as \(\Delta x\) gets smaller and smaller.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_small_interval_dx_05.png&quot; alt=&quot;Approximation with delta x equal to 0.5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 14: With \(\Delta x = 0.5\), the approximating rectangle is still rather coarse so the error is still clearly visible.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_small_interval_dx_01.png&quot; alt=&quot;Approximation with delta x equal to 0.1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 15: When \(\Delta x = 0.1\), the rectangle hugs the true area much more closely.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_small_interval_dx_001.png&quot; alt=&quot;Approximation with delta x equal to 0.01&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 16: With \(\Delta x = 0.01\), the approximation \(f(x)\Delta x\) almost coincides with the true probability over a very small interval.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;33-the-units-of-the-pdf&quot;&gt;3.3. The Units of the PDF&lt;/h3&gt;

&lt;p&gt;An important but often overlooked aspect of the PDF is its units. If the random variable \(X\) has units, such as cm, kg, or seconds, then \(f(x)\) has units of &lt;strong&gt;1/(units of X)&lt;/strong&gt;, and \(f(x)\cdot dx\) becomes a unitless quantity, which is exactly why it can be interpreted as a probability.&lt;/p&gt;

&lt;p&gt;For example, if \(X\) is height in cm, then \(f(x)\) has units of 1/cm. If we convert to meters, \(f(x)\) will have units of 1/m, and its numerical value will change accordingly. Specifically, if \(f(170 \text{ cm}) = 0.04 \text{ (1/cm)}\), then \(f(1.70 \text{ m}) = 4.0 \text{ (1/m)}\) - increased by a factor of 100 because we switched from cm to m.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_units_cm_only.png&quot; alt=&quot;PDF when measuring height in cm&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 17: When measured in cm, the value at the center is about \(f(170)=0.04\) with units of 1/cm.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_units_m_only.png&quot; alt=&quot;PDF when measuring height in m&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 18: The same distribution but switched to meters, the value at the center rises to about \(f(1.70)=4.0\) with units of 1/m. The physical shape of the distribution does not change, only the scale and the units of the density change.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;However, &lt;strong&gt;probability does not depend on units&lt;/strong&gt;. \(P(160 \text{ cm} \leq X \leq 180 \text{ cm}) = P(1.60 \text{ m} \leq X \leq 1.80 \text{ m})\). This makes sense because probability is an abstract concept with no physical unit of measurement.&lt;/p&gt;

&lt;p&gt;The dependence of \(f(x)\) on units is another important reason why we cannot regard \(f(x)\) as a probability. Probability must be unchanged regardless of which unit system we use, but \(f(x)\) changes with the units.&lt;/p&gt;

&lt;h2 id=&quot;4-comparing-the-pmf-and-the-pdf&quot;&gt;4. Comparing the PMF and the PDF&lt;/h2&gt;

&lt;p&gt;To consolidate understanding, let us compare the PMF and the PDF directly:&lt;/p&gt;

&lt;p&gt;On the discrete side, a typical PMF such as Binomial(10, 0.5) assigns probability directly to each integer value.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_binomial_pmf_example.png&quot; alt=&quot;Example PMF of a Binomial distribution&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 19: In a PMF, the bar at \(x=5\) is exactly the probability \(P(X=5)=0.246\) and can be read directly from the figure.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;On the continuous side, a typical PDF such as Normal(0,1) gives us only the density at each point and not the point probability.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_normal_density_example.png&quot; alt=&quot;Example PDF of the standard normal distribution&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 20: In a PDF, the value \(f(0)=0.399\) is only the density at the point 0, while \(P(X=0)=0\) because this is a continuous variable.&lt;/em&gt;&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Feature&lt;/th&gt;
      &lt;th&gt;PMF (Discrete)&lt;/th&gt;
      &lt;th&gt;PDF (Continuous)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Notation&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;\(P(X = x)\)&lt;/td&gt;
      &lt;td&gt;\(f(x)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Meaning&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Probability&lt;/td&gt;
      &lt;td&gt;Probability density&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Value&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;\(0 \leq P(X=x) \leq 1\)&lt;/td&gt;
      &lt;td&gt;\(f(x) \geq 0\) (can be &amp;gt; 1)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;P(X = x)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Meaningful&lt;/td&gt;
      &lt;td&gt;= 0 (meaningless)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Sum/Integral&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;\(\sum P(X=x) = 1\)&lt;/td&gt;
      &lt;td&gt;\(\int f(x)dx = 1\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Interval probability&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;\(\sum_{a}^{b} P(X=x)\)&lt;/td&gt;
      &lt;td&gt;\(\int_a^b f(x)dx\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Units&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Unitless&lt;/td&gt;
      &lt;td&gt;1/(units of X)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The core difference is: with a PMF, \(P(X=x)\) &lt;strong&gt;is a probability&lt;/strong&gt;, whereas with a PDF, \(f(x)\) &lt;strong&gt;is not a probability&lt;/strong&gt; but only a density. Only when we sum (discrete) or integrate (continuous) do we get real probability.&lt;/p&gt;

&lt;h2 id=&quot;5-common-mistakes&quot;&gt;5. Common Mistakes&lt;/h2&gt;

&lt;h3 id=&quot;mistake-1-thinking-fx-is-a-probability&quot;&gt;Mistake 1: Thinking \(f(x)\) is a probability&lt;/h3&gt;

&lt;p&gt;This is the most common mistake. Many people look at the normal distribution with mean 170 cm and standard deviation 10 cm, compute \(f(170) = 0.04\), and then say “the probability that the height equals 170 cm is 0.04”. This is completely &lt;strong&gt;wrong&lt;/strong&gt;. The wrong interpretation would be to write “\(P(X = 170) = f(170) = 0.04\)”, whereas the correct interpretation must be “\(P(X = 170) = 0\) because this is a continuous variable, and \(f(170) = 0.04\) is only the density at that point”.&lt;/p&gt;

&lt;h3 id=&quot;mistake-2-thinking-fx-leq-1&quot;&gt;Mistake 2: Thinking \(f(x) \leq 1\)&lt;/h3&gt;

&lt;p&gt;Because probability never exceeds 1, many people automatically assume the PDF cannot exceed 1 either. But as we have seen, this is &lt;strong&gt;wrong&lt;/strong&gt;. The statement “\(f(x)\) must be less than or equal to 1” is false, while the correct statement is “\(f(x) \geq 0\) and can perfectly well be greater than 1, as long as the total integral \(\int f(x)dx = 1\)”.&lt;/p&gt;

&lt;p&gt;For example, the uniform distribution on \([0, 0.2]\) has \(f(x) = 5 &amp;gt; 1\), but is perfectly valid because the area is \(5 \times 0.2 = 1\).&lt;/p&gt;

&lt;h3 id=&quot;mistake-3-comparing-fx-across-different-units&quot;&gt;Mistake 3: Comparing \(f(x)\) across different units&lt;/h3&gt;

&lt;p&gt;Because \(f(x)\) depends on units, comparing \(f(170 \text{ cm})\) with \(f(1.70 \text{ m})\) is meaningless. They have different units and different numerical values, so what can be compared meaningfully is not the density at a point but the probabilities over corresponding intervals, because probability carries no units.&lt;/p&gt;

&lt;h2 id=&quot;6-applications-in-bayesian-statistics&quot;&gt;6. Applications in Bayesian Statistics&lt;/h2&gt;

&lt;h3 id=&quot;61-prior-and-posterior-are-pdfs&quot;&gt;6.1. Prior and Posterior Are PDFs&lt;/h3&gt;

&lt;p&gt;In Bayesian analysis, both the prior distribution \(p(\theta)\) and the posterior distribution \(p(\theta \mid x)\) are PDFs if the parameter \(\theta\) is continuous. This means \(p(\theta)\) is not a point probability but a &lt;strong&gt;density of belief&lt;/strong&gt;, so an expression such as \(p(\theta = 0.5)\) has no direct probabilistic interpretation; what is meaningful is the probability over an interval, for example \(P(a \leq \theta \leq b) = \int_a^b p(\theta)\,d\theta\), and because it is a density, \(p(\theta)\) can also be greater than 1.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_bayesian_prior_posterior.png&quot; alt=&quot;Prior and posterior as two density functions&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 21: In Bayesian analysis, the prior and the posterior are both PDF curves over the parameter space. They describe the density of belief before and after observing data.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;For example, suppose we have a prior \(\theta \sim \text{Beta}(2, 2)\) for the success probability of an experiment, and observe 7 successes in 10 trials. The posterior will be \(\theta \mid x \sim \text{Beta}(9, 5)\). When we say “the 95% credible interval is [0.395, 0.827]”, the precise meaning is:&lt;/p&gt;

\[P(0.395 \leq \theta \leq 0.827 \mid x) = \int_{0.395}^{0.827} p(\theta \mid x) \, d\theta = 0.95\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/pdf_bayesian_credible_interval.png&quot; alt=&quot;A credible interval as the area under the posterior&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 22: The 95% credible interval is the blue area under the posterior PDF, not the height of the curve at some point.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is the integral (area) of the posterior PDF, not the value of the PDF at any point.&lt;/p&gt;

&lt;h3 id=&quot;62-the-likelihood-function&quot;&gt;6.2. The Likelihood Function&lt;/h3&gt;

&lt;p&gt;The likelihood function \(L(\theta) = p(x \mid \theta)\) is also proportional to a PDF. When the data \(x\) is fixed, the likelihood is a function of the parameter \(\theta\). If the model is \(X \sim \mathcal{N}(\mu, \sigma^2)\) with known \(\sigma\), then:&lt;/p&gt;

\[L(\mu) = \prod_{i=1}^{n} f(x_i \mid \mu) = \prod_{i=1}^{n} \frac{1}{\sigma\sqrt{2\pi}} \exp\left(-\frac{(x_i-\mu)^2}{2\sigma^2}\right)\]

&lt;p&gt;Here, each \(f(x_i \mid \mu)\) is the value of the PDF at the data point \(x_i\), with parameter \(\mu\). The Maximum Likelihood Estimate (MLE) is the value \(\hat{\mu}\) that maximizes \(L(\mu)\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-a-tight-triangularuniform-density-whose-height-exceeds-1&quot;&gt;Worked Numerical Example: A Tight Triangular/Uniform Density Whose Height Exceeds 1&lt;/h3&gt;

&lt;p&gt;Consider a narrow uniform posterior \(\theta \sim \mathrm{Uniform}(0.40,\; 0.65)\) (width \(w = 0.65 - 0.40 = 0.25\)):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Constant PDF height:&lt;/strong&gt; To make total area equal 1, the density height must be:
\(f(\theta) = \frac{1}{0.25} = \mathbf{4.0} \quad \text{for } \theta \in [0.40, 0.65]\)
—four times larger than 1, and 100% mathematically valid!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Probability of a small interval \([0.45, 0.50]\) (width \(0.05\)):&lt;/strong&gt;
\(P(0.45 \le \theta \le 0.50) = \text{height} \times \text{width} = 4.0 \times 0.05 = \mathbf{0.20} \quad (20\%).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check a Normal density peak:&lt;/strong&gt; For \(\mathcal{N}(0, \sigma^2)\) with \(\sigma = 0.1\), the peak height at \(x=0\) is \(f(0) = \frac{1}{\sigma\sqrt{2\pi}} = \frac{1}{0.1 \times 2.5066} \approx \mathbf{3.99} &amp;gt; 1\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-reading-continuous-pdfs-correctly&quot;&gt;Explanation: Four Rules for Reading Continuous PDFs Correctly&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check the units of the horizontal axis:&lt;/strong&gt; If you change units from meters to kilometers, interval widths shrink by \(1000\times\), so PDF heights multiply by \(1000\times\) to keep total area equal to 1!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Read &lt;em&gt;ratios&lt;/em&gt; of densities, not raw heights:&lt;/strong&gt; Saying \(f(0.7) / f(0.5) = 2.28\) means a tiny interval around \(0.7\) is \(2.28\times\) as probable as an equally wide interval around \(0.5\)—this ratio is scale-free and drives Metropolis–Hastings acceptance!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use the CDF (or quantiles) for tail probabilities:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;F(b) - F(a)&lt;/code&gt; answers probability questions directly without hand integration.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Don’t panic when log-density is positive:&lt;/strong&gt; Whenever \(f(x) &amp;gt; 1\) (a tight posterior!), \(\log f(x) &amp;gt; 0\)—completely normal for continuous PDFs (only discrete PMFs must satisfy \(\log P \le 0\))!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If a continuous random variable has a positive log-density \(\log f(x) = +2.3\) at a point \(x\), is there a bug in your code—or what is the density height \(f(x) = e^{2.3}\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=hDjcxi9p0ak&quot;&gt;Probability density and mass functions&lt;/a&gt; — Intelligent Systems Lab, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch to separate the probability mass function from the density function, exactly the PMF vs PDF distinction the lesson places at its center.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YXLVjCKVP7U&quot;&gt;Probability Distribution Functions (PMF, PDF, CDF)&lt;/a&gt; — zedstatistics, English. Watch the relationship among the PMF, PDF and cumulative distribution function, supporting the part on reading probability over an interval.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Why “probability of 0” does not mean “impossible”&lt;/td&gt;
          &lt;td&gt;Probabilities of probabilities, part 2](https://www.youtube.com/watch?v=ZA4JkHKZM50) — 3Blue1Brown, English. Watch why the density at a point is not the probability of that point, used when the lesson interprets the PDF of a continuous variable.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1&lt;/strong&gt;: Explain why \(P(X = 170) = 0\) for a continuous variable, but \(f(170)\) can be nonzero. What is the difference between these two quantities?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2&lt;/strong&gt;: Given \(f(x) = 2x\) on \([0, 1]\) and \(f(x) = 0\) outside.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Check that this is a valid PDF (integral equals 1)&lt;/li&gt;
  &lt;li&gt;Compute \(P(0.2 \leq X \leq 0.5)\)&lt;/li&gt;
  &lt;li&gt;Is \(f(0.3) = 0.6\) a probability? If not, what does it mean?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3&lt;/strong&gt;: Create two normal distributions with the same mean but different standard deviations (for example \(\sigma = 1\) and \(\sigma = 2\)). Compare the values of \(f(x)\) at the mean. Which distribution has the larger \(f(\mu)\)? Why?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4&lt;/strong&gt;: Height \(X \sim \mathcal{N}(170 \text{ cm}, 10^2)\).&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;If \(f(170 \text{ cm}) = 0.04 \text{ (1/cm)}\), what is \(f(1.70 \text{ m})\) (in units of 1/m)?&lt;/li&gt;
  &lt;li&gt;Compute \(P(160 \leq X \leq 180)\) in both unit systems. Are the results the same?&lt;/li&gt;
  &lt;li&gt;Explain why the probability stays the same but \(f(x)\) changes with the units.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5&lt;/strong&gt;: Given the prior \(\theta \sim \text{Beta}(1, 1)\) (uniform distribution) and data: 3 successes in 5 trials.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Find the posterior \(p(\theta \mid x)\)&lt;/li&gt;
  &lt;li&gt;Is \(p(0.5 \mid x)\) a probability? If not, what does it mean?&lt;/li&gt;
  &lt;li&gt;Compute the 90% credible interval for \(\theta\)&lt;/li&gt;
  &lt;li&gt;Explain the meaning of “\(P(a \leq \theta \leq b \mid x) = 0.90\)” in the language of the PDF integral&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Wasserman, L. (2004).&lt;/strong&gt; &lt;em&gt;All of Statistics: A Concise Course in Statistical Inference&lt;/em&gt;. Springer.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 2: Random Variables - The part on the PDF and its difference from the PMF&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Casella, G., &amp;amp; Berger, R. L. (2002).&lt;/strong&gt; &lt;em&gt;Statistical Inference&lt;/em&gt; (2nd Edition). Duxbury.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 1: Probability Theory - Detailed explanation of the PDF and its mathematical properties&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., et al. (2013).&lt;/strong&gt; &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Appendix A: Standard probability distributions - Using the PDF in a Bayesian context&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Seeing Theory - Probability Distributions&lt;/strong&gt;: &lt;a href=&quot;https://seeing-theory.brown.edu/&quot;&gt;https://seeing-theory.brown.edu/&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Interactive visualization of PDF concepts&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;A correct understanding of the PDF is an important foundation for Bayesian Statistics! Remember: \(f(x)\) is density, not probability. Only the integral of \(f(x)\) gives probability.&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_08_pvalues_and_hypothesis_testing/&quot;&gt;0.11 P-values and Hypothesis Testing&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.9: Basic Calculus</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_06_calculus_basics/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_06_calculus_basics</id>
   <content type="html">&lt;p&gt;Every continuous Bayesian inference problem quietly runs on two engines from calculus: &lt;strong&gt;integration&lt;/strong&gt; (summing area under the prior \(\times\) likelihood curve to compute the normalizing evidence \(P(D) = \int P(D\mid\theta)P(\theta)\,d\theta\)) and &lt;strong&gt;differentiation&lt;/strong&gt; (finding the peak MAP estimate where \(abla_\theta \log p(\theta\mid D) = 0\) and steering &lt;strong&gt;Hamiltonian Monte Carlo / NUTS&lt;/strong&gt; along the gradient of the log-posterior!).&lt;/p&gt;

&lt;p&gt;This lesson refreshes single- and multi-variable calculus directly through a Bayesian lens: derivatives, gradients, Hessians (curvature = precision!), and integrals as expectations.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-where-calculus-shows-up-inside-bayesian-inference&quot;&gt;Key ideas: Where Calculus Shows Up Inside Bayesian Inference&lt;/h2&gt;

&lt;p&gt;Four calculus tools power almost every algorithm in this course:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Derivatives &amp;amp; Optimization (MLE / MAP):&lt;/strong&gt; Setting the first derivative of the log-posterior \(\frac{d}{d\theta}\log p(\theta\mid D) = 0\) locates the &lt;strong&gt;Maximum A Posteriori (MAP)&lt;/strong&gt; mode cleanly without ever needing to compute the normalizing integral!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Second Derivative / Hessian = Curvature = Posterior Precision:&lt;/strong&gt; The negative second derivative \(-\frac{d^2}{d\theta^2}\log p(\theta\mid D)\) at the mode measures how sharply peaked the posterior is—giving the &lt;strong&gt;Laplace approximation&lt;/strong&gt; variance \(\sigma_{\text{post}}^2 \approx \left(-\ell&apos;&apos;(\hat{\theta})
ight)^{-1}\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradients &amp;amp; Automatic Differentiation (HMC / NUTS):&lt;/strong&gt; Modern Bayesian samplers (Stan, PyMC) treat \(-\log p(\theta\mid D)\) as a gravitational potential energy landscape and use exact gradients \(abla_\theta \log p(\theta\mid D)\) to glide efficiently across high-dimensional posteriors.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Integrals as Expectations &amp;amp; Marginalization:&lt;/strong&gt; Posterior means \(\mathbb{E}[\theta\mid D] = \int \theta\,p(\theta\mid D)\,d\theta\) and posterior predictive distributions are integrals—computed analytically for conjugate models or approximated by Monte Carlo averages \(\frac{1}{S}\sum \theta^{(s)}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will grasp the roles of derivatives, integrals, and optimization in Bayesian statistical inference. Specifically, you will understand the derivative as a tool for sensitivity analysis and finding extrema, the integral as normalization and computing probabilities over continuous domains, and optimization as the step of finding approximate solutions (for example the MAP) before or alongside sampling the posterior.&lt;/p&gt;

&lt;h2 id=&quot;introduction-why-is-calculus-at-the-core-of-continuous-bayes&quot;&gt;Introduction: why is calculus at the core of continuous Bayes?&lt;/h2&gt;

&lt;p&gt;Many Bayesian models work with continuous parameters. In that case, three mathematical operations appear again and again: taking derivatives to optimize the log-posterior function, taking integrals to normalize distributions and marginalize latent variables, and using gradients to design efficient computational algorithms. So calculus is not an auxiliary part; it is the core that turns a probability model into computable inference.&lt;/p&gt;

&lt;p&gt;In this lesson, every formula will be read on two levels: the formal level (mathematical notation) and the statistical meaning level (which question it answers in data analysis). This two-level reading is an important skill for the MCMC, Bayesian regression, and model checking chapters.&lt;/p&gt;

&lt;h2 id=&quot;a-framework-connecting-to-the-bayesian-workflow&quot;&gt;A framework connecting to the Bayesian workflow&lt;/h2&gt;

&lt;p&gt;A typical workflow can be written briefly:&lt;/p&gt;

\[\text{prior} \times \text{likelihood} \propto \text{posterior (unnormalized)}.\]

&lt;p&gt;From here, calculus takes part at two points:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Derivatives&lt;/strong&gt;: find the extrema of the log-posterior (MAP, Laplace approximation).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Integrals&lt;/strong&gt;: normalize the posterior or compute probabilities/expectations over a continuous domain.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;1-derivatives&quot;&gt;1. Derivatives&lt;/h2&gt;

&lt;h3 id=&quot;11-definition&quot;&gt;1.1. Definition&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;derivative&lt;/strong&gt; measures the rate of change of a function:&lt;/p&gt;

\[f&apos;(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}\]

&lt;p&gt;&lt;strong&gt;Geometric meaning&lt;/strong&gt;: The slope of the tangent line at the point \(x\).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Function
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Derivative (analytical)
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Numerical derivative
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;numerical_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot the function and the tangent line
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;slope&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tangent line: y - y0 = slope * (x - x0)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tangent_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;slope&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x) = x²&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tangent_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tangent at x=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zorder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;The Derivative is the Slope of the Tangent&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compare analytical vs numerical derivative
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;numerical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;numerical_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Derivative at x=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Analytical: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Numerical: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numerical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;12-basic-derivative-rules&quot;&gt;1.2. Basic Derivative Rules&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Function&lt;/th&gt;
      &lt;th&gt;Derivative&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(c\) (constant)&lt;/td&gt;
      &lt;td&gt;\(0\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(x^n\)&lt;/td&gt;
      &lt;td&gt;\(nx^{n-1}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(e^x\)&lt;/td&gt;
      &lt;td&gt;\(e^x\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\ln(x)\)&lt;/td&gt;
      &lt;td&gt;\(\frac{1}{x}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\sin(x)\)&lt;/td&gt;
      &lt;td&gt;\(\cos(x)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\cos(x)\)&lt;/td&gt;
      &lt;td&gt;\(-\sin(x)\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Sum rule&lt;/strong&gt;: \((f + g)&apos; = f&apos; + g&apos;\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Product rule&lt;/strong&gt;: \((fg)&apos; = f&apos;g + fg&apos;\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quotient rule&lt;/strong&gt;: \(\left(\frac{f}{g}\right)&apos; = \frac{f&apos;g - fg&apos;}{g^2}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Chain rule&lt;/strong&gt;: \((f(g(x)))&apos; = f&apos;(g(x)) \cdot g&apos;(x)\)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Example: f(x) = (x² + 1)³
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Derivative by the chain rule:
# f&apos;(x) = 3(x² + 1)² · 2x = 6x(x² + 1)²
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Check
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;numerical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;numerical_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x) = (x² + 1)³ at x=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Analytical: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Numerical: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numerical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;13-partial-derivatives&quot;&gt;1.3. Partial Derivatives&lt;/h3&gt;

&lt;p&gt;Given a function of several variables \(f(x, y)\), the partial derivative with respect to \(x\):&lt;/p&gt;

\[\frac{\partial f}{\partial x} = \lim_{h \to 0} \frac{f(x+h, y) - f(x, y)}{h}\]

&lt;p&gt;(holding \(y\) fixed)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Function of 2 variables: f(x, y) = x²y + y³
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Partial derivatives
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;df_dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;df_dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot the 3D function
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mpl_toolkits.mplot3d&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Axes3D&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;meshgrid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Surface plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;add_subplot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;121&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;projection&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;3d&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot_surface&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;viridis&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_zlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x, y)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x, y) = x²y + y³&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Contour plot with gradient
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;add_subplot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;122&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;contour&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;contour&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;levels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;viridis&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;contour&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inline&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot the gradient at some points
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;xi&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yi&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;df_dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;df_dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;yi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.003&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Contour and Gradient&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_aspect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compute at a specific point
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;At (x, y) = (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  f = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ∂f/∂x = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;df_dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ∂f/∂y = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;df_dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;14-gradient&quot;&gt;1.4. Gradient&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;gradient&lt;/strong&gt; is the vector of all partial derivatives:&lt;/p&gt;

\[\nabla f = \begin{bmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_n} \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Meaning&lt;/strong&gt;: The direction in which the function increases fastest.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;df_dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;df_dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient at (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Magnitude: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;2-integrals&quot;&gt;2. Integrals&lt;/h2&gt;

&lt;h3 id=&quot;21-definite-integrals&quot;&gt;2.1. Definite Integrals&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Meaning&lt;/strong&gt;: The area under a curve.&lt;/p&gt;

\[\int_a^b f(x) dx\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Function
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Analytical integral: ∫x² dx = x³/3
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Integral from 0 to 2
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;integral_analytical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Numerical integral
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;integrate&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;integral_numerical&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;integrate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Integral ∫₀² x² dx:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Analytical: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;integral_analytical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Numerical: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;integral_numerical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x) = x²&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Shade the region of integration
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_fill&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fill_between&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Area = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;integral_analytical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Integral = Area under the Curve&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;22-integrals-in-probability&quot;&gt;2.2. Integrals in Probability&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;PDF&lt;/strong&gt; (Probability Density Function) must satisfy:&lt;/p&gt;

\[\int_{-\infty}^{\infty} f(x) dx = 1\]

&lt;p&gt;&lt;strong&gt;Probability&lt;/strong&gt;:&lt;/p&gt;

\[P(a \leq X \leq b) = \int_a^b f(x) dx\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Normal distribution
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pdf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compute P(-1 ≤ X ≤ 1)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;integrate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;N(0, 1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Shade the probability region
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pdf_fill&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fill_between&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pdf_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;P(-1 ≤ X ≤ 1) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Probability = Area under the PDF&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compare with the CDF
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob_cdf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;P(-1 ≤ X ≤ 1):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Integral: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  CDF: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob_cdf&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;23-multivariable-integrals&quot;&gt;2.3. Multivariable Integrals&lt;/h3&gt;

\[\int \int f(x, y) \, dx \, dy\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Function of 2 variables
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Integral over [0,1] × [0,2]
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;integrate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dblquad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;∫₀¹ ∫₀² xy dy dx = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Analytical: ∫₀¹ x dx · ∫₀² y dy = [x²/2]₀¹ · [y²/2]₀² = 0.5 · 2 = 1
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Analytical: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;analytical&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;3-optimization&quot;&gt;3. Optimization&lt;/h2&gt;

&lt;h3 id=&quot;31-extrema&quot;&gt;3.1. Extrema&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Necessary condition&lt;/strong&gt;:&lt;/p&gt;

\[f&apos;(x) = 0\]

&lt;p&gt;&lt;strong&gt;Sufficient condition&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(f&apos;&apos;(x) &amp;gt; 0\): Minimum&lt;/li&gt;
  &lt;li&gt;\(f&apos;&apos;(x) &amp;lt; 0\): Maximum&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Function: f(x) = x³ - 6x² + 9x + 1
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_double_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Find the critical points: f&apos;(x) = 0
# 3x² - 12x + 9 = 0
# x² - 4x + 3 = 0
# (x-1)(x-3) = 0
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;critical_points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;critical_points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;yc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;f2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f_double_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Minimum
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Min at x=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Maximum
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Max at x=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;yc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
               &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zorder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  f(x) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;yc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(x) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;f_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(x) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f2&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  → &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Minimum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Maximum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;f(x)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Finding Extrema&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;32-gradient-descent&quot;&gt;3.2. Gradient Descent&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Algorithm&lt;/strong&gt; for finding the minimum:&lt;/p&gt;

\[x_{n+1} = x_n - \alpha \nabla f(x_n)\]

&lt;p&gt;where \(\alpha\) is the learning rate.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Function of 2 variables: f(x, y) = x² + y²
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Gradient descent
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;path&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Run from the starting point
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;meshgrid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;contour&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;contour&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;levels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;viridis&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;contour&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inline&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot the path
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ro-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;markersize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient Descent&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;300&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;gold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
           &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Minimum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zorder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient Descent&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient Descent:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Start: (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;), f = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;End: (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;), f = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;33-maximum-likelihood-estimation-mle&quot;&gt;3.3. Maximum Likelihood Estimation (MLE)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: Estimate the parameter \(\mu\) of a Normal distribution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Likelihood&lt;/strong&gt;:&lt;/p&gt;

\[L(\mu) = \prod_{i=1}^{n} \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x_i - \mu)^2}{2\sigma^2}\right)\]

&lt;p&gt;&lt;strong&gt;Log-likelihood&lt;/strong&gt;:&lt;/p&gt;

\[\ell(\mu) = -\frac{n}{2}\log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\sum_{i=1}^{n}(x_i - \mu)^2\]

&lt;p&gt;&lt;strong&gt;Find the maximum&lt;/strong&gt;: \(\frac{d\ell}{d\mu} = 0\)&lt;/p&gt;

\[\Rightarrow \hat{\mu} = \frac{1}{n}\sum_{i=1}^{n} x_i\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;true_mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Log-likelihood function
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;log_likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot the log-likelihood
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_range&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ll_values&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sigma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu_range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# MLE
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ll_values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Log-likelihood&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
           &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;MLE: μ̂ = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mle&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
           &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True: μ = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_mu&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;μ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Log-likelihood&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Maximum Likelihood Estimation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True μ: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_mu&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;MLE μ̂: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mle&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sample mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;4-applications-in-bayesian-statistics&quot;&gt;4. Applications in Bayesian Statistics&lt;/h2&gt;

&lt;h3 id=&quot;41-posterior-mode-map&quot;&gt;4.1. Posterior Mode (MAP)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Maximum A Posteriori&lt;/strong&gt; (MAP): Find the mode of the posterior.&lt;/p&gt;

\[\hat{\theta}_{MAP} = \arg\max_\theta p(\theta \mid \mathbf{x})\]

&lt;p&gt;Equivalently:&lt;/p&gt;

\[\hat{\theta}_{MAP} = \arg\max_\theta [\log p(\mathbf{x} \mid \theta) + \log p(\theta)]\]

&lt;h3 id=&quot;42-laplace-approximation&quot;&gt;4.2. Laplace Approximation&lt;/h3&gt;

&lt;p&gt;Approximate the posterior by a Normal distribution at the mode:&lt;/p&gt;

\[p(\theta \mid \mathbf{x}) \approx \mathcal{N}\left(\hat{\theta}, \left[-\frac{d^2 \log p(\theta \mid \mathbf{x})}{d\theta^2}\bigg\vert _{\hat{\theta}}\right]^{-1}\right)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Example: Beta posterior
# Prior: Beta(2, 2)
# Likelihood: Binomial(n, theta)
# Data: 7 successes in 10 trials
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;alpha_prior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n_success&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Posterior: Beta(alpha_prior + n_success, beta_prior + n_total - n_success)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_success&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_success&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Log posterior (unnormalized)
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;log_posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;or&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inf&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;log_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;log_lik&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_success&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_success&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_prior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_lik&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# MAP (mode)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Laplace approximation
# Compute the second derivative
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;log_posterior_second_deriv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;variance_laplace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;log_posterior_second_deriv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;std_laplace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;variance_laplace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.99&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;laplace_approx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pdf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std_laplace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;posterior&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True Posterior (Beta)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;laplace_approx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Laplace Approximation (Normal)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
           &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;MAP: θ̂ = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;θ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Density&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Laplace Approximation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;MAP: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_map&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Laplace std: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std_laplace&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True std: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_post&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-finding-the-map-mode-and-laplace-variance-of-mathrmbeta8-12-by-hand&quot;&gt;Worked Numerical Example: Finding the MAP Mode and Laplace Variance of \(\mathrm{Beta}(8, 12)\) by Hand&lt;/h3&gt;

&lt;p&gt;Take the unnormalized log-posterior of \(\mathrm{Beta}(\alpha=8, \beta=12)\):&lt;/p&gt;

\[g(p) = \ln\!\bigl(p^{8-1}(1-p)^{12-1}\bigr) = 7\ln p + 11\ln(1-p).\]

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;First derivative \(\to\) exact MAP mode:&lt;/strong&gt;
\(g&apos;(p) = \frac{7}{p} - \frac{11}{1-p} = 0 \implies 7(1-p) = 11p \implies 18p = 7 \implies \hat{p}_{\text{MAP}} = \frac{7}{18} \approx \mathbf{0.3889}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Second derivative at the mode \(\to\) Laplace curvature &amp;amp; SD:&lt;/strong&gt;
\(g&apos;&apos;(p) = -\frac{7}{p^2} - \frac{11}{(1-p)^2}.\)
Evaluate at \(\hat{p} = 7/18\) (so \(1-\hat{p} = 11/18\)):
\(-g&apos;&apos;(\hat{p}) = \frac{7}{(7/18)^2} + \frac{11}{(11/18)^2} = \frac{18^2}{7} + \frac{18^2}{11} = 324\!\left(\frac{18}{77}
ight) \approx 75.74.\)
Invert to get the Laplace approximate variance and SD:
\(\sigma_{\text{Laplace}} = \frac{1}{\sqrt{75.74}} \approx \mathbf{0.1149}\)
&lt;em&gt;(remarkably close to the exact \(\mathrm{Beta}(8,12)\) standard deviation \(0.1069\)!)&lt;/em&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-calculus-insights-that-make-bayesian-algorithms-click&quot;&gt;Explanation: Four Calculus Insights That Make Bayesian Algorithms Click&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always differentiate the &lt;em&gt;log&lt;/em&gt;-posterior, never the raw posterior:&lt;/strong&gt; Taking logs turns products of \(n\) likelihood terms into sums, makes derivatives linear, and guarantees concavity for exponential families.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Higher curvature means &lt;em&gt;less&lt;/em&gt; uncertainty:&lt;/strong&gt; A sharp, narrow log-posterior peak has a large negative second derivative \(-g&apos;&apos;(\hat{\theta})\), which translates directly into a small posterior variance!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never confuse an integral over &lt;em&gt;data&lt;/em&gt; with an integral over &lt;em&gt;parameters&lt;/em&gt;:&lt;/strong&gt; Normalization integrates over \(\theta\) (\(\int p(D\mid\theta)p(\theta)\,d\theta\)), which is why a likelihood function \(L(\theta)\) by itself does &lt;em&gt;not&lt;/em&gt; integrate to 1 over \(\theta\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Change-of-variables requires a Jacobian:&lt;/strong&gt; If you transform a parameter (e.g., \(\phi = \log \sigma\) for unconstrained HMC sampling), you must multiply the density by \(\lvert \frac{d\sigma}{d\phi}
vert\) so total probability mass is conserved.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; For \(\mathrm{Beta}(8, 12)\), the exact posterior mean is \(8/20 = 0.400\) while the MAP mode we just found is \(7/18 \approx 0.389\). Why is the mode slightly smaller than the mean? &lt;em&gt;(Hint: check which direction \(\mathrm{Beta}(8,12)\) is skewed!)&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[The paradox of the derivative&lt;/td&gt;
          &lt;td&gt;Chapter 2, Essence of calculus](https://www.youtube.com/watch?v=9vKqVkMQHKk) — 3Blue1Brown, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the derivative as sensitivity when the input is nudged a little, exactly the part of the lesson that uses derivatives to read the log-posterior.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Integration and the fundamental theorem of calculus&lt;/td&gt;
          &lt;td&gt;Chapter 8, Essence of calculus](https://www.youtube.com/watch?v=rfG8ce4nNh0) — 3Blue1Brown, English. Watch the integral as the accumulation of small changes, supporting the part on normalizing distributions and computing probabilities over a continuous domain.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, English. Watch gradient descent as walking against the steepest slope; the context is neural networks, but the mechanism matches the optimization part of the lesson.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Derivatives&lt;/strong&gt;: Compute the derivative of:
    &lt;ul&gt;
      &lt;li&gt;
\[f(x) = 3x^4 - 2x^2 + 5\]
      &lt;/li&gt;
      &lt;li&gt;
\[g(x) = e^{x^2}\]
      &lt;/li&gt;
      &lt;li&gt;
\[h(x) = \ln(x^2 + 1)\]
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Partial derivatives&lt;/strong&gt;: Given \(f(x, y) = x^2y + xy^2\). Compute \(\frac{\partial f}{\partial x}\) and \(\frac{\partial f}{\partial y}\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Integrals&lt;/strong&gt;: Compute:
    &lt;ul&gt;
      &lt;li&gt;
\[\int_0^1 x^2 dx\]
      &lt;/li&gt;
      &lt;li&gt;
\[\int_1^e \frac{1}{x} dx\]
      &lt;/li&gt;
      &lt;li&gt;\(\int_{-\infty}^{\infty} e^{-x^2} dx\) (hint: \(\sqrt{\pi}\))&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Optimization&lt;/strong&gt;: Find the extrema of \(f(x) = x^3 - 3x + 1\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;MLE&lt;/strong&gt;: Given data from Exponential(\(\lambda\)). Find the MLE of \(\lambda\).
    &lt;ul&gt;
      &lt;li&gt;Likelihood: \(L(\lambda) = \prod_{i=1}^{n} \lambda e^{-\lambda x_i}\)&lt;/li&gt;
      &lt;li&gt;Hint: \(\hat{\lambda} = \frac{n}{\sum x_i}\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Stewart, J. (2015).&lt;/strong&gt; &lt;em&gt;Calculus: Early Transcendentals&lt;/em&gt;. Cengage Learning.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;3Blue1Brown - Essence of Calculus&lt;/strong&gt; - https://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SciPy Integrate&lt;/strong&gt; - https://docs.scipy.org/doc/scipy/reference/integrate.html&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;This lesson completes the basic prerequisite knowledge. You are ready for Bayesian Statistics!&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_07_probability_density_functions/&quot;&gt;0.10 Probability Density Functions (PDF)&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.8: Basic Linear Algebra</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_05_linear_algebra/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_05_linear_algebra</id>
   <content type="html">&lt;p&gt;One-parameter coin flips only take you so far. The moment you model real-world data—predicting house prices from 10 features, modeling correlated gene expressions, or running a &lt;strong&gt;Multivariate Normal&lt;/strong&gt; Bayesian regression—scalars turn into vectors and matrices, and variance turns into a &lt;strong&gt;covariance matrix \(\Sigma\)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This lesson builds the exact geometric and matrix intuition you need for multi-parameter Bayesian models: dot products, linear transformations, &lt;strong&gt;positive-definite covariance matrices&lt;/strong&gt;, &lt;strong&gt;eigenvalues/eigenvectors&lt;/strong&gt; (which reveal the principal axes of a correlated posterior!), and &lt;strong&gt;Cholesky decomposition&lt;/strong&gt; (the engine that samples correlated Gaussian draws!).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-how-linear-algebra-powers-multi-parameter-bayes&quot;&gt;Key ideas: How Linear Algebra Powers Multi-Parameter Bayes&lt;/h2&gt;

&lt;p&gt;Four linear-algebra ideas reappear constantly across Bayesian regression and MCMC:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Design Matrix \(\mathbf{X}\) &amp;amp; Linear Predictors \(\mathbf{X}\boldsymbol{\beta}\):&lt;/strong&gt; Packs \(n\) observations and \(p\) predictors into one matrix multiply, turning regression into vector geometry.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Symmetric Positive-Definite (SPD) Covariance &amp;amp; Precision Matrices:&lt;/strong&gt; A valid covariance matrix \(\Sigma\) is symmetric with all eigenvalues \(&amp;gt; 0\). Its inverse \(\Lambda = \Sigma^{-1}\) (the &lt;strong&gt;precision matrix&lt;/strong&gt;) adds linearly in Multivariate Normal Bayesian updating!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Eigenvalues &amp;amp; Posterior Geometry:&lt;/strong&gt; The eigenvectors of \(\Sigma\) point along the principal axes of the elliptical posterior contour, and the square roots of the eigenvalues give the standard deviations along those axes—explaining why highly correlated parameters create narrow “diagonal bananas/ridges” that slow down naive MCMC!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cholesky Decomposition (\(\Sigma = L L^T\)):&lt;/strong&gt; The matrix square root of a covariance matrix—multiplying standard independent Normal draws \(\mathbf{z} \sim \mathcal{N}(\mathbf{0}, I)\) by \(L\) instantly generates correlated draws \(\boldsymbol{\mu} + L\mathbf{z} \sim \mathcal{N}(\boldsymbol{\mu}, \Sigma)\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will understand why linear algebra is the mathematical infrastructure of Bayesian statistical models: data is represented as vectors and matrices, regression parameters are written as linear operators, and many inference algorithms rely directly on linear transformations. You will also be able to read the geometric meaning of formulas instead of just manipulating symbols.&lt;/p&gt;

&lt;h2 id=&quot;introduction-from-scattered-formulas-to-linear-structure&quot;&gt;Introduction: from scattered formulas to linear structure&lt;/h2&gt;

&lt;p&gt;As the number of variables grows, writing a model with individual equations becomes hard to follow. Linear algebra solves this problem by gathering quantities into vectors and matrices, helping us see the model as a unified structure. This is an important step because most modern Bayesian models (linear regression, GLMs, hierarchical models) are implemented efficiently on this structure.&lt;/p&gt;

&lt;p&gt;Methodologically, you can regard this lesson as the “formal language” for the modeling chapters: if lesson 0.7 provides the programming tools, this lesson provides the mathematical framework for expressing and reasoning.&lt;/p&gt;

&lt;h2 id=&quot;a-bridge-to-bayesian-inference&quot;&gt;A bridge to Bayesian inference&lt;/h2&gt;

&lt;p&gt;Many basic Bayesian expressions can be written compactly with linear algebra. For example the Gaussian regression model:&lt;/p&gt;

\[\mathbf{y}=\mathbf{X}\boldsymbol{\beta}+\boldsymbol{\epsilon},\qquad
\boldsymbol{\epsilon}\sim\mathcal{N}(\mathbf{0},\sigma^2\mathbf{I}).\]

&lt;p&gt;This representation lets us clearly separate three components: the data \(\mathbf{X}\), the parameters \(\boldsymbol{\beta}\), and the noise structure. As we move on to posterior inference, these objects will appear repeatedly in both formulas and computation code.&lt;/p&gt;

&lt;h2 id=&quot;1-vectors&quot;&gt;1. Vectors&lt;/h2&gt;

&lt;h3 id=&quot;11-definition&quot;&gt;1.1. Definition&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;vector&lt;/strong&gt; is an ordered array of numbers. It can represent a point in space or a direction.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Column vector&lt;/strong&gt; (commonly used):&lt;/p&gt;

\[\mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Row vector&lt;/strong&gt;:&lt;/p&gt;

\[\mathbf{x}^T = \begin{bmatrix} x_1 &amp;amp; x_2 &amp;amp; \cdots &amp;amp; x_n \end{bmatrix}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create vectors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Vector 2D
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Vector 3D
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dimension: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Length: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;12-visualizing-vectors&quot;&gt;1.2. Visualizing Vectors&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Plot vectors in 2D
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;vectors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;for &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vectors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angles&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale_units&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
             &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₁&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₂&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vectors in 2D space&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_aspect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;13-operations-with-vectors&quot;&gt;1.3. Operations with Vectors&lt;/h3&gt;

&lt;h4 id=&quot;vector-additionsubtraction&quot;&gt;Vector Addition/Subtraction&lt;/h4&gt;

\[\mathbf{x} + \mathbf{y} = \begin{bmatrix} x_1 + y_1 \\ x_2 + y_2 \\ \vdots \\ x_n + y_n \end{bmatrix}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Add
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v + w = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Subtract
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_minus_w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v - w = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_minus_w&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vector v (red)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angles&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale_units&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
         &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vector w (blue)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angles&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale_units&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
         &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vector v+w (green)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angles&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale_units&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
         &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.015&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v+w&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Draw the parallelogram
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_plus_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₁&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₂&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vector Addition&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_aspect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;scalar-multiplication&quot;&gt;Scalar Multiplication&lt;/h4&gt;

\[c \mathbf{x} = \begin{bmatrix} c x_1 \\ c x_2 \\ \vdots \\ c x_n \end{bmatrix}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Multiply by different scalars
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;scalars&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;orange&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;purple&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scalar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scalars&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scaled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scalar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quiver&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scaled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scaled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angles&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale_units&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
             &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scalar&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₁&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x₂&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Multiplying a Vector by a Scalar&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_aspect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;dot-product&quot;&gt;Dot Product&lt;/h4&gt;

\[\mathbf{x} \cdot \mathbf{y} = \sum_{i=1}^{n} x_i y_i = x_1 y_1 + x_2 y_2 + \cdots + x_n y_n\]

&lt;p&gt;&lt;strong&gt;Geometric meaning&lt;/strong&gt;:&lt;/p&gt;

\[\mathbf{x} \cdot \mathbf{y} = \|\mathbf{x}\| \|\mathbf{y}\| \cos(\theta)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Dot product
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot_product&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v · w = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot_product&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Or
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot_product2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;v @ w = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot_product2&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compute the angle between 2 vectors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm_v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;norm_w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;cos_theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dot_product&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm_v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;norm_w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_rad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arccos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cos_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_deg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;degrees&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;||v|| = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm_v&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;||w|| = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm_w&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Angle between v and w: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_deg&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;°&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Important properties&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;If \(\mathbf{x} \cdot \mathbf{y} = 0\): the 2 vectors are perpendicular (orthogonal)&lt;/li&gt;
  &lt;li&gt;If \(\mathbf{x} \cdot \mathbf{y} &amp;gt; 0\): Acute angle&lt;/li&gt;
  &lt;li&gt;If \(\mathbf{x} \cdot \mathbf{y} &amp;lt; 0\): Obtuse angle&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;length-norm&quot;&gt;Length (Norm)&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Euclidean norm (L2 norm)&lt;/strong&gt;:&lt;/p&gt;

\[\|\mathbf{x}\| = \sqrt{\sum_{i=1}^{n} x_i^2} = \sqrt{\mathbf{x} \cdot \mathbf{x}}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;||v|| = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 5.0
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Unit vector
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_unit&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Unit vector: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_unit&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Length: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_unit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1.0
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;2-matrices&quot;&gt;2. Matrices&lt;/h2&gt;

&lt;h3 id=&quot;21-definition&quot;&gt;2.1. Definition&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;matrix&lt;/strong&gt; is a 2-dimensional array of numbers.&lt;/p&gt;

\[\mathbf{A} = \begin{bmatrix} 
a_{11} &amp;amp; a_{12} &amp;amp; \cdots &amp;amp; a_{1n} \\
a_{21} &amp;amp; a_{22} &amp;amp; \cdots &amp;amp; a_{2n} \\
\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\
a_{m1} &amp;amp; a_{m2} &amp;amp; \cdots &amp;amp; a_{mn}
\end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Size&lt;/strong&gt;: \(m \times n\) (m rows, n columns)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Create matrices
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 3)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;B shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (3, 2)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Special matrices
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;I&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 3x3 identity matrix
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Zero matrix
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;O&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Matrix of ones
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;22-operations-with-matrices&quot;&gt;2.2. Operations with Matrices&lt;/h3&gt;

&lt;h4 id=&quot;additionsubtraction-same-size&quot;&gt;Addition/Subtraction (same size)&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A + B =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A - B =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;scalar-multiplication-1&quot;&gt;Scalar Multiplication&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2A =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;matrix-multiplication&quot;&gt;Matrix Multiplication&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Condition&lt;/strong&gt;: The number of columns of A = the number of rows of B&lt;/p&gt;

&lt;p&gt;If \(\mathbf{A}\) is \(m \times n\) and \(\mathbf{B}\) is \(n \times p\), then \(\mathbf{C} = \mathbf{AB}\) is \(m \times p\):&lt;/p&gt;

\[c_{ij} = \sum_{k=1}^{n} a_{ik} b_{kj}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2x3
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 3x2
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;C&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2x2
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A @ B =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Note: Matrix multiplication is not commutative
# A @ B ≠ B @ A (usually)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;transpose&quot;&gt;Transpose&lt;/h4&gt;

\[(\mathbf{A}^T)_{ij} = a_{ji}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;A_T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A^T =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Property: (A^T)^T = A
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(A^T)^T = A?&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array_equal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;23-the-inverse-matrix&quot;&gt;2.3. The Inverse Matrix&lt;/h3&gt;

&lt;p&gt;Given a square matrix \(\mathbf{A}\) (\(n \times n\)), the inverse matrix \(\mathbf{A}^{-1}\) satisfies:&lt;/p&gt;

\[\mathbf{A} \mathbf{A}^{-1} = \mathbf{A}^{-1} \mathbf{A} = \mathbf{I}\]

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: Not every matrix has an inverse (singular matrix).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compute the inverse
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_inv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A^(-1) =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Check
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;I_check&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A_inv&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A @ A^(-1) =&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;I_check&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Non-invertible matrix
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;singular&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                     &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Row 2 = 2 * Row 1
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;try&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;singular_inv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;singular&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;except&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LinAlgError&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A singular matrix has no inverse!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;24-determinant&quot;&gt;2.4. Determinant&lt;/h3&gt;

&lt;p&gt;Given a square matrix \(\mathbf{A}\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2×2&lt;/strong&gt;:&lt;/p&gt;

\[\det(\mathbf{A}) = \begin{vmatrix} a &amp;amp; b \\ c &amp;amp; d \end{vmatrix} = ad - bc\]

&lt;p&gt;&lt;strong&gt;Properties&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\det(\mathbf{A}) \neq 0\): the matrix is invertible&lt;/li&gt;
  &lt;li&gt;\(\det(\mathbf{A}) = 0\): the matrix is singular&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;det_A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;det&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;det(A) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;det_A&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Singular matrix
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;singular&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                     &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;det_singular&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;det&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;singular&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;det(singular) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;det_singular&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ≈ 0
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;3-systems-of-linear-equations&quot;&gt;3. Systems of Linear Equations&lt;/h2&gt;

&lt;p&gt;The system of equations:&lt;/p&gt;

\[\begin{cases}
a_{11}x_1 + a_{12}x_2 + \cdots + a_{1n}x_n = b_1 \\
a_{21}x_1 + a_{22}x_2 + \cdots + a_{2n}x_n = b_2 \\
\vdots \\
a_{m1}x_1 + a_{m2}x_2 + \cdots + a_{mn}x_n = b_m
\end{cases}\]

&lt;p&gt;&lt;strong&gt;Matrix form&lt;/strong&gt;: \(\mathbf{Ax} = \mathbf{b}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt; (if A is invertible): \(\mathbf{x} = \mathbf{A}^{-1}\mathbf{b}\)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# System of equations:
# 2x + 3y = 8
# 5x + 4y = 13
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Solve using the inverse
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Solution (using inv): x = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Solve using solve (more efficient)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_solve&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;solve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Solution (using solve): x = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_solve&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Check
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Check Ax = b: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;4-eigenvalues-and-eigenvectors&quot;&gt;4. Eigenvalues and Eigenvectors&lt;/h2&gt;

&lt;p&gt;Given a square matrix \(\mathbf{A}\), if:&lt;/p&gt;

\[\mathbf{A}\mathbf{v} = \lambda \mathbf{v}\]

&lt;p&gt;then \(\lambda\) is an &lt;strong&gt;eigenvalue&lt;/strong&gt; and \(\mathbf{v}\) is the corresponding &lt;strong&gt;eigenvector&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Meaning&lt;/strong&gt;: The vector \(\mathbf{v}\) is only scaled (its direction does not change) when multiplied by \(\mathbf{A}\).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compute eigenvalues and eigenvectors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvalues&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eigenvectors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Eigenvalues:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvalues&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Eigenvectors:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvectors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Check
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvalues&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambda_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eigenvalues&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eigenvectors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;Av&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambda_v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Eigenvalue &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: λ = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Av = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Av&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;λv = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lambda_v&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Match? &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Av&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lambda_v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-applications-in-statistics&quot;&gt;5. Applications in Statistics&lt;/h2&gt;

&lt;h3 id=&quot;51-covariance-matrix&quot;&gt;5.1. Covariance Matrix&lt;/h3&gt;

&lt;p&gt;Given data \(\mathbf{X}\) (\(n \times p\)), the covariance matrix:&lt;/p&gt;

\[\mathbf{\Sigma} = \frac{1}{n-1} \mathbf{X}^T \mathbf{X}\]

&lt;p&gt;(after centering the data)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Create data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;multivariate_normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compute the covariance matrix
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cov_matrix&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cov&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Covariance Matrix:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cov_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Scatter plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;X₁&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;X₂&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_aspect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Covariance matrix heatmap
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seaborn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;heatmap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cov_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;annot&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;coolwarm&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
           &lt;span class=&quot;n&quot;&gt;square&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Covariance Matrix&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;52-linear-regression&quot;&gt;5.2. Linear Regression&lt;/h3&gt;

&lt;p&gt;Model: \(\mathbf{y} = \mathbf{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;OLS solution&lt;/strong&gt; (Ordinary Least Squares):&lt;/p&gt;

\[\hat{\boldsymbol{\beta}} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Create data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;true_beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Add intercept
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_with_intercept&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;column_stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compute beta
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_with_intercept&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_with_intercept&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_with_intercept&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True beta:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Estimated beta:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Drop the intercept
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Intercept:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Predictions
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_with_intercept&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()],&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Linear Regression: True vs Predicted&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# R-squared
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ss_res&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ss_tot&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;r_squared&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ss_res&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ss_tot&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;R² = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r_squared&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;6-summary-of-important-formulas&quot;&gt;6. Summary of Important Formulas&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Operation&lt;/th&gt;
      &lt;th&gt;Notation&lt;/th&gt;
      &lt;th&gt;Formula&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Dot product&lt;/td&gt;
      &lt;td&gt;\(\mathbf{x} \cdot \mathbf{y}\)&lt;/td&gt;
      &lt;td&gt;\(\sum_{i=1}^{n} x_i y_i\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Norm&lt;/td&gt;
      &lt;td&gt;\(|\mathbf{x}|\)&lt;/td&gt;
      &lt;td&gt;\(\sqrt{\sum_{i=1}^{n} x_i^2}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Matrix multiplication&lt;/td&gt;
      &lt;td&gt;\(\mathbf{AB}\)&lt;/td&gt;
      &lt;td&gt;\(c_{ij} = \sum_{k} a_{ik}b_{kj}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Transpose&lt;/td&gt;
      &lt;td&gt;\(\mathbf{A}^T\)&lt;/td&gt;
      &lt;td&gt;\((\mathbf{A}^T)_{ij} = a_{ji}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Inverse&lt;/td&gt;
      &lt;td&gt;\(\mathbf{A}^{-1}\)&lt;/td&gt;
      &lt;td&gt;\(\mathbf{AA}^{-1} = \mathbf{I}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Determinant&lt;/td&gt;
      &lt;td&gt;\(\det(\mathbf{A})\)&lt;/td&gt;
      &lt;td&gt;Scalar value&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Eigenvalue&lt;/td&gt;
      &lt;td&gt;\(\lambda\)&lt;/td&gt;
      &lt;td&gt;\(\mathbf{Av} = \lambda\mathbf{v}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-hand-computing-cholesky--precision-updating-on-a-2times-2-covariance-matrix&quot;&gt;Worked Numerical Example: Hand-Computing Cholesky &amp;amp; Precision Updating on a \(2\times 2\) Covariance Matrix&lt;/h3&gt;

&lt;p&gt;Suppose a 2-parameter posterior has covariance matrix:&lt;/p&gt;

\[\Sigma = \begin{pmatrix} 4 &amp;amp; 2 \ 2 &amp;amp; 5 \end{pmatrix}.\]

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Check correlation &amp;amp; positive definiteness:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Standard deviations: \(\sigma_1 = \sqrt{4} = 2\), \(\sigma_2 = \sqrt{5} \approx 2.236\); correlation \(ho = \frac{2}{2\sqrt{5}} \approx 0.447\).&lt;/li&gt;
      &lt;li&gt;Determinant: \(\det(\Sigma) = 4(5) - 2^2 = 16 &amp;gt; 0\) and trace \(4+5=9 &amp;gt; 0\) \(\implies\) strictly positive definite!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute its lower-triangular Cholesky factor \(L\) (\(\Sigma = L L^T\)) by hand:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(L_{11} = \sqrt{4} = 2\).&lt;/li&gt;
      &lt;li&gt;\(L_{21} = \frac{2}{L_{11}} = \frac{2}{2} = 1\).&lt;/li&gt;
      &lt;li&gt;\(L_{22} = \sqrt{5 - L_{21}^2} = \sqrt{5 - 1} = 2\).
So \(L = \begin{pmatrix} 2 &amp;amp; 0 \ 1 &amp;amp; 2 \end{pmatrix}\)! Verify: \(L L^T = \begin{pmatrix} 2 &amp;amp; 0 \ 1 &amp;amp; 2 \end{pmatrix}\begin{pmatrix} 2 &amp;amp; 1 \ 0 &amp;amp; 2 \end{pmatrix} = \begin{pmatrix} 4 &amp;amp; 2 \ 2 &amp;amp; 5 \end{pmatrix}\)—exact!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Generate one correlated draw from \(\mathbf{z} = (1, -1)^T\):&lt;/strong&gt;
\(L\mathbf{z} = \begin{pmatrix} 2(1) + 0 \ 1(1) + 2(-1) \end{pmatrix} = \begin{pmatrix} 2 \ -1 \end{pmatrix}.\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-linear-algebra-habits-for-bayesian-modeling&quot;&gt;Explanation: Four Linear-Algebra Habits for Bayesian Modeling&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Never invert a matrix explicitly when solving \(A\mathbf{x}=\mathbf{b}\):&lt;/strong&gt; Use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.linalg.solve(A, b)&lt;/code&gt; or Cholesky solves instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.linalg.inv(A) @ b&lt;/code&gt; for far higher speed and numerical stability.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Watch the condition number of \(\mathbf{X}^T\mathbf{X}\):&lt;/strong&gt; Collinear predictors create tiny eigenvalues in \(\mathbf{X}^T\mathbf{X}\), stretching the posterior into a razor-thin ridge—standardizing predictors (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(x - mean)/sd&lt;/code&gt;) immediately improves geometry!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Think in precision matrices (\(\Sigma^{-1}\)) for Gaussian Bayes:&lt;/strong&gt; Just as 1D precisions add (\(\tau_{\text{post}} = \tau_{\text{prior}} + \tau_{\text{data}}\)), in \(d\) dimensions \(\Sigma_{\text{post}}^{-1} = \Sigma_{\text{prior}}^{-1} + \frac{1}{\sigma^2}\mathbf{X}^T\mathbf{X}\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use Cholesky for non-centered parameterizations in Stan/PyMC:&lt;/strong&gt; Sampling standard Normal \(\mathbf{z}\) and transforming via \(L\mathbf{z}\) lets Hamiltonian Monte Carlo explore correlated posteriors effortlessly.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; For the matrix \(\Sigma = \begin{pmatrix} 4 &amp;amp; 2 \ 2 &amp;amp; 5 \end{pmatrix}\) above (with \(\det(\Sigma) = 16\)), what is its inverse—the &lt;strong&gt;precision matrix&lt;/strong&gt; \(\Lambda = \Sigma^{-1}\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Vectors&lt;/td&gt;
          &lt;td&gt;Chapter 1, Essence of linear algebra](https://www.youtube.com/watch?v=fNk_zzaMoSs) — 3Blue1Brown, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch to see a vector as a geometric object, exactly the part of the lesson that gathers data and parameters into vectors.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Matrix multiplication as composition&lt;/td&gt;
          &lt;td&gt;Chapter 4, Essence of linear algebra](https://www.youtube.com/watch?v=XkY2DOUCWMU) — 3Blue1Brown, English. Watch matrix multiplication as a transformation, supporting the part that writes regression as a linear operator.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Eigenvectors and eigenvalues&lt;/td&gt;
          &lt;td&gt;Chapter 14, Essence of linear algebra](https://www.youtube.com/watch?v=PFDu9oVAE-g) — 3Blue1Brown, English. Watch eigenvalues and eigenvectors, used for the eigenvalues section of the lesson when talking about the structure of a matrix.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Vectors&lt;/strong&gt;: Given \(\mathbf{v} = [2, 3, -1]\) and \(\mathbf{w} = [1, -2, 4]\). Compute:
    &lt;ul&gt;
      &lt;li&gt;
\[\mathbf{v} + \mathbf{w}\]
      &lt;/li&gt;
      &lt;li&gt;
\[\mathbf{v} \cdot \mathbf{w}\]
      &lt;/li&gt;
      &lt;li&gt;
\[\|\mathbf{v}\|\]
      &lt;/li&gt;
      &lt;li&gt;The angle between \(\mathbf{v}\) and \(\mathbf{w}\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Matrices&lt;/strong&gt;: Given \(\mathbf{A} = \begin{bmatrix} 1 &amp;amp; 2 \\ 3 &amp;amp; 4 \end{bmatrix}\) and \(\mathbf{B} = \begin{bmatrix} 5 &amp;amp; 6 \\ 7 &amp;amp; 8 \end{bmatrix}\). Compute:
    &lt;ul&gt;
      &lt;li&gt;
\[\mathbf{A} + \mathbf{B}\]
      &lt;/li&gt;
      &lt;li&gt;
\[\mathbf{AB}\]
      &lt;/li&gt;
      &lt;li&gt;
\[\mathbf{A}^T\]
      &lt;/li&gt;
      &lt;li&gt;
\[\mathbf{A}^{-1}\]
      &lt;/li&gt;
      &lt;li&gt;
\[\det(\mathbf{A})\]
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Systems of equations&lt;/strong&gt;: Solve the system:
\(\begin{cases} 3x + 2y = 7 \\ x - y = 1 \end{cases}\)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Eigenvalues&lt;/strong&gt;: Find the eigenvalues and eigenvectors of \(\mathbf{A} = \begin{bmatrix} 3 &amp;amp; 1 \\ 1 &amp;amp; 3 \end{bmatrix}\)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Linear Regression&lt;/strong&gt;: Generate data \(y = 3x_1 - 2x_2 + \epsilon\) with 100 samples. Estimate \(\beta\) using the OLS formula.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Strang, G. (2016).&lt;/strong&gt; &lt;em&gt;Introduction to Linear Algebra&lt;/em&gt;. Wellesley-Cambridge Press.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;3Blue1Brown - Essence of Linear Algebra&lt;/strong&gt; - https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;NumPy Linear Algebra&lt;/strong&gt; - https://numpy.org/doc/stable/reference/routines.linalg.html&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;This lesson concludes the basic prerequisite knowledge. You are ready to start the Bayesian Statistics course!&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_06_calculus_basics/&quot;&gt;0.9 Basic Calculus&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.7: Basic Python for Data Science</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_04_python_basics/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_04_python_basics</id>
   <content type="html">&lt;p&gt;Modern Bayesian statistics is inseparable from computation: very few real-world posteriors have neat pencil-and-paper formulas, so we explore them by simulating thousands of draws, evaluating vectorized log-likelihoods, and plotting posterior diagnostics in &lt;strong&gt;Python (NumPy, SciPy, Matplotlib)&lt;/strong&gt;. Yet a single slow Python &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt;-loop inside an MCMC sampler can turn a 2-second grid evaluation into a 10-minute coffee break!&lt;/p&gt;

&lt;p&gt;This lesson gives you the practical Python + NumPy fluency required for Bayesian computing: clean array shapes, &lt;strong&gt;vectorization&lt;/strong&gt;, &lt;strong&gt;broadcasting&lt;/strong&gt;, reproducible random seeds (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.random.default_rng&lt;/code&gt;), and fast visual sanity checks.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-four-pythonnumpy-superpowers-for-bayesian-computing&quot;&gt;Key ideas: Four Python/NumPy Superpowers for Bayesian Computing&lt;/h2&gt;

&lt;p&gt;Four computational habits separate fast, bug-free Bayesian notebooks from fragile scripts:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Vectorization Over Python Loops:&lt;/strong&gt; NumPy pushes array arithmetic down into compiled C/SIMD loops—evaluating a Binomial log-likelihood across 10,000 grid points in a single vectorized expression runs &lt;strong&gt;50–100× faster&lt;/strong&gt; than a Python &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt; loop.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Broadcasting &amp;amp; Axis Discipline:&lt;/strong&gt; Knowing how shapes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, 1)&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(1, M)&lt;/code&gt; broadcast to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, M)&lt;/code&gt; lets you compute a full log-likelihood matrix across &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;N&lt;/code&gt; data points and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;M&lt;/code&gt; parameter values in one line—and prevents silent outer-product shape bugs!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Reproducible Randomness (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;default_rng(seed)&lt;/code&gt;):&lt;/strong&gt; Bayesian simulation and MCMC rely on pseudo-random draws; using explicit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rng = np.random.default_rng(42)&lt;/code&gt; makes every posterior summary 100% reproducible.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Log-Space Computation (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.special.logsumexp&lt;/code&gt;):&lt;/strong&gt; Multiplying 500 probabilities underflows &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt;; summing log-probabilities in NumPy keeps numerical inference rock-solid.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will have a Python foundation sufficient for the entire Bayesian workflow in this course: preparing data, numerical algebra computations, visualization, and writing reproducible blocks of code. The focus of the lesson is not memorizing scattered syntax, but understanding why basic programming operations are needed to turn a data-generating story into a verifiable statistical analysis.&lt;/p&gt;

&lt;h2 id=&quot;introduction-python-as-the-language-that-executes-models&quot;&gt;Introduction: Python as the language that executes models&lt;/h2&gt;

&lt;p&gt;In Bayesian analysis, a model does not stop at formulas. Every assumption about the data and parameters must eventually be realized as concrete computations: creating variables, transforming data, simulating, and checking results. If the math gives us the structure of inference, then Python is the execution layer that makes that inference runnable, repeatable, and shareable.&lt;/p&gt;

&lt;p&gt;For that reason, this lesson is organized from the basics to applications: starting with data structures and control flow, then moving to NumPy/Pandas/Matplotlib as the three core components of preprocessing and data exploration before entering probability models. You should read the lesson along the line “analytical meaning -&amp;gt; programming tool” rather than treating it as a list of commands.&lt;/p&gt;

&lt;h2 id=&quot;practice-principles-in-the-bayesian-course&quot;&gt;Practice principles in the Bayesian course&lt;/h2&gt;

&lt;p&gt;In later chapters, many problems will revolve around the chain:&lt;/p&gt;

\[\text{data} \rightarrow \text{cleaning/transform} \rightarrow \text{modeling} \rightarrow \text{diagnostics} \rightarrow \text{interpretation}.\]

&lt;p&gt;So, when learning Python in chapter 0, we prioritize three principles:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Reproducibility&lt;/strong&gt;: fix the seed when simulating and state the data source clearly.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Transparency&lt;/strong&gt;: every data transformation step must be readable by eye and explainable in words.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Interpretability&lt;/strong&gt;: visualization is not just to look “pretty”, but to check assumptions and detect model misfit.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;1-basic-python&quot;&gt;1. Basic Python&lt;/h2&gt;

&lt;h3 id=&quot;11-variables-and-data-types&quot;&gt;1.1. Variables and Data Types&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Numbers
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# int
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;3.14&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# float
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;3j&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# complex
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Strings
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bayesian&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;message&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Statistics&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Boolean
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;is_false&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Check the type
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# &amp;lt;class &apos;int&apos;&amp;gt;
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# &amp;lt;class &apos;str&apos;&amp;gt;
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Convert types
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 5.0
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_int&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;12-lists-tuples-dictionaries&quot;&gt;1.2. Lists, Tuples, Dictionaries&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# List (mutable)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;mixed&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;two&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Access
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1 (index starts at 0)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 5 (negative index: from the end)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [2, 3, 4] (slicing)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Add/remove
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Append to the end
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;insert&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Insert at a position
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;remove&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Remove the value 3
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;popped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Remove and return the last element
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Tuple (immutable)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coordinates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# coordinates[0] = 15  # Error!
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Dictionary (key-value pairs)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;person&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;city&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Hanoi&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# &apos;Alice&apos;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;26&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Update
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;email&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;alice@email.com&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Add new
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Loop over a dictionary
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;13-loops-and-conditionals&quot;&gt;1.3. Loops and Conditionals&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# If-else
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Positive&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Negative&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Zero&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# For loop
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 0, 1, 2, 3, 4
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# While loop
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;count&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# List comprehension (important!)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;squares&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;evens&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;14-functions&quot;&gt;1.4. Functions&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Define a function
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Hello, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;greet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Function with default arguments
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;power&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;power&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 9 (n=2 by default)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;power&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 27
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Multiple return values
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;count&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;stats&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Lambda functions (anonymous)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;square&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;square&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 25
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Map, filter
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;squared&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;evens&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;filter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numbers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;2-numpy---numerical-computing&quot;&gt;2. NumPy - Numerical Computing&lt;/h2&gt;

&lt;h3 id=&quot;21-arrays&quot;&gt;2.1. Arrays&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create arrays
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (5,)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 3)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# int64
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Create special arrays
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;zeros&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 3x4 matrix of all 0s
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ones&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2x3 matrix of all 1s
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 4x4 identity matrix
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Random [0, 1)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;22-indexing-and-slicing&quot;&gt;2.2. Indexing and Slicing&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Indexing
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 0
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 9
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Slicing
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [2, 3, 4]
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [0, 1, 2]
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [5, 6, 7, 8, 9]
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[::&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [0, 2, 4, 6, 8] (step 2)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 2D arrays
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [4, 5, 6] (row 1)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [2, 5, 8] (column 1)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Boolean indexing
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [6, 7, 8, 9]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;23-operations&quot;&gt;2.3. Operations&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;40&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Element-wise operations
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [11, 22, 33, 44]
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [10, 40, 90, 160]
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [1, 4, 9, 16]
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Broadcasting
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Add 10 to every element
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Aggregations
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 10
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2.5
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1.118...
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1, 4
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Axis operations
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [5, 7, 9] (sum by column)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [6, 15] (sum by row)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;24-important-functions&quot;&gt;2.4. Important Functions&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Random
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Reproducibility
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random_normal&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Normal(0, 1)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random_uniform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Uniform[0, 10]
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Linear algebra
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Matrix multiplication
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Alternative way
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Inverse matrix
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;det&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Determinant
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Reshape
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [0, 1, ..., 11]
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 3x4 matrix
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Back to 1D
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Stack
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;vstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Vertical stack
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Horizontal stack
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;3-pandas---data-processing&quot;&gt;3. Pandas - Data Processing&lt;/h2&gt;

&lt;h3 id=&quot;31-series-and-dataframe&quot;&gt;3.1. Series and DataFrame&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pandas&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Series (1D)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Series&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;s_named&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Series&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;index&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s_named&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 10
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# DataFrame (2D)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bob&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Charlie&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;35&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;City&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Hanoi&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;HCMC&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Danang&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;32-readingwriting-data&quot;&gt;3.2. Reading/Writing Data&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Read CSV
# df = pd.read_csv(&apos;data.csv&apos;)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Ghi CSV
# df.to_csv(&apos;output.csv&apos;, index=False)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Read Excel
# df = pd.read_excel(&apos;data.xlsx&apos;)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# From a dictionary
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;33-accessing-data&quot;&gt;3.3. Accessing Data&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bob&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Charlie&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;David&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;35&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;85&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;90&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;78&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;92&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Access a column
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Alternative way
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Access multiple columns
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Access rows by index
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iloc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# First row
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iloc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Rows 1-2
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Access by label
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_indexed&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_index&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_indexed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Boolean indexing
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;80&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;34-data-processing&quot;&gt;3.4. Data Processing&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Add a column
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Grade&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age_squared&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Drop a column
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_dropped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;drop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age_squared&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sort
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_sorted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sort_values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ascending&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Group by
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grouped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;groupby&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Grade&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grouped&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Apply function
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age_category&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;apply&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Young&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Old&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Missing values
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_with_nan&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df_with_nan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nan&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_with_nan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;isnull&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Count NaN
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_filled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df_with_nan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fillna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Fill NaN
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_dropped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df_with_nan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Drop NaN
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;35-merge-and-join&quot;&gt;3.5. Merge and Join&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Merge
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ID&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Name&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Alice&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bob&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Charlie&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;df2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ID&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;85&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;90&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;78&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;merged&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;on&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ID&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;how&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;inner&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# inner, left, right, outer
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;merged&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Concat
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df_concat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;concat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Vertical
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;4-matplotlib---visualization&quot;&gt;4. Matplotlib - Visualization&lt;/h2&gt;

&lt;h3 id=&quot;41-basic-plots&quot;&gt;4.1. Basic Plots&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Line plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sin(x)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;cos(x)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linestyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trigonometric Functions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Scatter plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Scatter Plot&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Histogram
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Value&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Frequency&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Histogram&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;42-subplots&quot;&gt;4.2. Subplots&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot 1
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Line Plot&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot 2
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Scatter Plot&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot 3
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Histogram&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Plot 4
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;boxplot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Box Plot&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;43-customization&quot;&gt;4.3. Customization&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Multiple styles
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;r-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Red solid&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b--&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Blue dashed&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;go&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;markersize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Green dots&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Colors: &apos;r&apos;, &apos;g&apos;, &apos;b&apos;, &apos;c&apos;, &apos;m&apos;, &apos;y&apos;, &apos;k&apos;, &apos;w&apos;
# Linestyles: &apos;-&apos;, &apos;--&apos;, &apos;-.&apos;, &apos;:&apos;
# Markers: &apos;o&apos;, &apos;s&apos;, &apos;^&apos;, &apos;*&apos;, &apos;+&apos;, &apos;x&apos;
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;X axis&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Y axis&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Customized Plot&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontweight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;bold&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;best&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-a-comprehensive-example&quot;&gt;5. A Comprehensive Example&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Create and analyze data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;170&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;M&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Add BMI
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Descriptive statistics
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=== Descriptive Statistics ===&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;describe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=== By Gender ===&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;groupby&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualization
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Histogram
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;black&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height (cm)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Frequency&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Distribution of Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Scatter
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gender&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;M&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gender&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; 
                      &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                      &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gender&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height (cm)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight (kg)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height vs Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Box plot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;boxplot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;column&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;by&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI by Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gender&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Correlation heatmap
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seaborn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;corr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Height&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Age&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;BMI&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;corr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;heatmap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;annot&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;coolwarm&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Correlation Matrix&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-vectorized-grid-posterior-in-4-lines-of-numpy&quot;&gt;Worked Numerical Example: Vectorized Grid Posterior in 4 Lines of NumPy&lt;/h3&gt;

&lt;p&gt;Suppose we observe \(k = 7\) heads in \(n = 10\) flips and evaluate a uniform-prior posterior on a tiny 5-point grid &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p = [0.1, 0.3, 0.5, 0.7, 0.9]&lt;/code&gt; by hand (matching exactly what vectorized NumPy computes!):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Grid Point \(p_i\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Unnormalized Likelihood \(p_i^7(1-p_i)^3\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Normalized Posterior \(w_i = L_i / \sum L_j\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(7.29\times 10^{-8}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0000\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(7.50\times 10^{-5}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0226\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(9.77\times 10^{-4}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.2943\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.7\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2.22\times 10^{-3}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.6699\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.9\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(4.78\times 10^{-5}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0144\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Sum&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(3.32\times 10^{-3}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(1.0000\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;In NumPy, this entire table is literally 3 vectorized operations: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;unnorm = (p**7) * ((1-p)**3)&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;post = unnorm / unnorm.sum()&lt;/code&gt;, and posterior mean &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(p * post).sum() ≈ 0.635&lt;/code&gt;!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-python-habits-that-save-hours-in-bayesian-labs&quot;&gt;Explanation: Four Python Habits That Save Hours in Bayesian Labs&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always print &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.shape&lt;/code&gt; when debugging NumPy expressions:&lt;/strong&gt; Most silent bugs in Bayesian code happen when a 1D array &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(100,)&lt;/code&gt; accidentally broadcasts against a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(100, 1)&lt;/code&gt; column into a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(100, 100)&lt;/code&gt; matrix!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never mutate shared arrays without &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.copy()&lt;/code&gt;:&lt;/strong&gt; Slicing a NumPy array returns a &lt;em&gt;view&lt;/em&gt; of the same memory; mutating the slice silently mutates your original data array.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pin random seeds at the top of every simulation:&lt;/strong&gt; Reproducibility lets you compare two priors or samplers fairly without wondering if a difference came from RNG luck.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats&lt;/code&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.logpdf()&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.logpmf()&lt;/code&gt; instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.pdf()&lt;/code&gt;:&lt;/strong&gt; Building the log-space habit in Chapter 0 prevents underflow crashes when you reach hierarchical models in later chapters.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the 5-point grid example above, why does &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;post = unnorm / unnorm.sum()&lt;/code&gt; give the exact same normalized weights even though we omitted the Binomial coefficient \(\binom{10}{7} = 120\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jZ952vChhuI&quot;&gt;Quick introduction to Jupyter Notebook&lt;/a&gt; — Michael Fudge, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch to see how a notebook keeps code, results and notes in one re-runnable file, exactly the reproducible workflow the lesson requires.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=lLRBYKwP8GQ&quot;&gt;Ultimate Guide to NumPy Arrays - VERY DETAILED TUTORIAL for beginners!&lt;/a&gt; — Python Simplified, English. Watch NumPy arrays and vectorized computation, supporting the numerical algebra part when simulating and transforming data.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2uvysYbKdjM&quot;&gt;Complete Python Pandas Data Science Tutorial! (2025 Updated Edition)&lt;/a&gt; — Keith Galli, English. Watch how Pandas loads and prepares tabular data, used for the part of the lesson that turns raw data into model input.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lists &amp;amp; Loops&lt;/strong&gt;: Create a list of the numbers 1-100. Compute the sum of the even and odd numbers separately.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Functions&lt;/strong&gt;: Write a function that computes the mean, median, std of a list of numbers.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;NumPy&lt;/strong&gt;: Create a random 5x5 matrix. Compute the mean of each row and each column.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pandas&lt;/strong&gt;: Create a DataFrame with 100 people (name, age, score). Do:
    &lt;ul&gt;
      &lt;li&gt;Filter people with age &amp;gt; 25&lt;/li&gt;
      &lt;li&gt;Compute the mean score by age group (18-30, 31-40, 41+)&lt;/li&gt;
      &lt;li&gt;Sort by score in descending order&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Visualization&lt;/strong&gt;: Create 2-variable data that is correlated. Plot:
    &lt;ul&gt;
      &lt;li&gt;Scatter plot with a regression line&lt;/li&gt;
      &lt;li&gt;Histogram of each variable&lt;/li&gt;
      &lt;li&gt;Box plot comparing the 2 variables&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Python Documentation&lt;/strong&gt; - https://docs.python.org/3/&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;NumPy Documentation&lt;/strong&gt; - https://numpy.org/doc/&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pandas Documentation&lt;/strong&gt; - https://pandas.pydata.org/docs/&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Matplotlib Documentation&lt;/strong&gt; - https://matplotlib.org/stable/contents.html&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Real Python Tutorials&lt;/strong&gt; - https://realpython.com/&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;This lesson introduced basic Python. Next, we will study basic linear algebra.&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_05_linear_algebra/&quot;&gt;0.8 Basic Linear Algebra&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.6: Descriptive Statistics - The First Language of Data</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_03_descriptive_statistics/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_03_descriptive_statistics</id>
   <content type="html">&lt;p&gt;When a tech billionaire walks into a neighborhood coffee shop with 9 ordinary customers, the &lt;em&gt;mean&lt;/em&gt; net worth inside the shop instantly shoots above $100 million—yet nine out of ten people in the room still can’t buy a yacht! That single anecdote explains why &lt;strong&gt;descriptive statistics&lt;/strong&gt; is never just busywork before modeling: choosing the wrong summary (mean vs. median, SD vs. IQR) can completely misrepresent a skewed dataset—and later, a skewed Bayesian posterior!&lt;/p&gt;

&lt;p&gt;This lesson builds sharp numerical intuition for measures of center, spread, and shape, showing how robust quantiles (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;median&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;IQR&lt;/code&gt;) protect you from outliers and prepare you to summarize MCMC posterior draws accurately.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-summarizing-dataand-summarizing-bayesian-posteriors&quot;&gt;Key ideas: Summarizing Data—and Summarizing Bayesian Posteriors&lt;/h2&gt;

&lt;p&gt;Every descriptive summary you compute on raw data reappears directly when summarizing posterior samples:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Measures of Location (Mean, Median, Mode):&lt;/strong&gt; The mean minimizes squared error (\(L_2\) loss), the median minimizes absolute error (\(L_1\) loss) and resists extreme outliers, and the mode marks the highest-density peak (analogous to MAP in Bayesian inference).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Measures of Spread (Variance, SD, IQR):&lt;/strong&gt; Standard deviation measures typical squared distance from the mean; &lt;strong&gt;Interquartile Range&lt;/strong&gt; (\(\mathrm{IQR} = Q_3 - Q_1\)) captures the middle 50% of data without being distorted by heavy tails.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Skewness &amp;amp; Quantile Intervals:&lt;/strong&gt; When a distribution is strongly right-skewed (income, waiting times, variance parameters \(\sigma^2\)), reporting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean ± 2 SD&lt;/code&gt; can even cross below zero—whereas quantile summaries (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;median [Q_2.5%, Q_97.5%]&lt;/code&gt;) stay honest.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bridge to Posterior Summaries:&lt;/strong&gt; In Bayesian analysis via MCMC, you summarize thousands of posterior draws using the exact same toolkit: posterior mean, posterior median, posterior SD, and 95% credible intervals!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;p&gt;After completing this lesson, you will understand that descriptive statistics is not just about computing summary numbers, but the art of telling a story about data. You will learn to use statistics such as the mean, median, and standard deviation not as mechanical formulas, but as tools for understanding the structure, trends, and variability in data. More importantly, you will develop intuition about when to use each statistic, and how to interpret them in the context of Bayesian analysis, where understanding the distribution of the data is an important first step before building a model.&lt;/p&gt;

&lt;h2 id=&quot;introduction-why-do-we-need-descriptive-statistics&quot;&gt;Introduction: Why Do We Need Descriptive Statistics?&lt;/h2&gt;

&lt;p&gt;Imagine you receive a dataset containing the heights of 10,000 adults. How can you understand this data? You cannot look at each individual number and draw meaningful conclusions. You need a way to summarize, to capture the essence of the data in a few numbers or comprehensible pictures.&lt;/p&gt;

&lt;p&gt;This is exactly the role of descriptive statistics. They give us a language for talking about data, a way to convey what we see in thousands or millions of data points as a few important characteristics. Descriptive statistics answers basic questions: What is the “typical” value? How is the data spread out? Are there any unusual values? Is the distribution symmetric or skewed?&lt;/p&gt;

&lt;p&gt;In Bayesian analysis, descriptive statistics plays a particularly important role. Before we build a complex probability model, we need to understand our data. We need to know which distribution might fit, which parameters need to be estimated, and which assumptions might be violated. Descriptive statistics is the first step on this journey, helping us build intuition about the data before we start modeling.&lt;/p&gt;

&lt;h2 id=&quot;measures-of-central-tendency-searching-for-the-typical-value&quot;&gt;Measures of Central Tendency: Searching for the “Typical” Value&lt;/h2&gt;

&lt;p&gt;One of the first questions we usually ask about a dataset is: “What is the typical value?” But “typical” can mean many different things, and that is why we have several different measures of central tendency.&lt;/p&gt;

&lt;h3 id=&quot;the-mean-the-balance-point&quot;&gt;The Mean: The Balance Point&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;arithmetic mean&lt;/strong&gt; is the most familiar measure of central tendency. For a dataset \(x_1, x_2, \ldots, x_n\), the mean is defined as:&lt;/p&gt;

\[\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i\]

&lt;p&gt;The mean has a beautiful geometric interpretation: it is the balance point of the data. If you imagine each data point as a mass on a straight rod, the mean is the point at which the rod would balance. More formally, the mean is the value for which the sum of deviations from it is zero: \(\sum_{i=1}^{n} (x_i - \bar{x}) = 0\).&lt;/p&gt;

&lt;p&gt;However, the mean has an important weakness: it is very sensitive to outliers. A single extreme value can pull the mean far away from most of the data. Consider an example: the incomes of 10 people, 9 of whom earn between 30,000 and 50,000 dollars per year, and one who earns 1,000,000 dollars. The mean would be about 130,000 dollars, a number that does not represent the “typical” income of this group.&lt;/p&gt;

&lt;p&gt;In Bayesian analysis, the mean often appears as the location parameter of the normal distribution. When we model data as \(y_i \sim \mathcal{N}(\mu, \sigma^2)\), \(\mu\) is the mean of the distribution, and its natural estimate from the data is the sample mean \(\bar{x}\).&lt;/p&gt;

&lt;h3 id=&quot;the-median-the-middle-value&quot;&gt;The Median: The Middle Value&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;median&lt;/strong&gt; is the middle value when the data is sorted in increasing order. If the number of observations \(n\) is odd, the median is the \((n+1)/2\)-th value. If \(n\) is even, the median is usually defined as the average of the two middle values.&lt;/p&gt;

&lt;p&gt;The median has an important property: it is &lt;strong&gt;robust&lt;/strong&gt; to outliers. You can change the extreme values in the data without affecting the median, as long as you do not change the order of the values around the middle. In the income example above, the median would still lie in the range of 30,000-50,000 dollars, better reflecting the “typical” income.&lt;/p&gt;

&lt;p&gt;The median also has a natural probabilistic interpretation: it is the value for which the probability of observing a smaller value is 50%, and the probability of observing a larger value is also 50%. This is the 50th percentile of the distribution.&lt;/p&gt;

&lt;p&gt;In Bayesian analysis, the median is often used to summarize the posterior distribution, especially when the distribution is asymmetric. Instead of reporting the posterior mean (which can be affected by a long tail), we often report the posterior median together with a credible interval.&lt;/p&gt;

&lt;h3 id=&quot;comparing-the-mean-and-median-detecting-skewness&quot;&gt;Comparing the Mean and Median: Detecting Skewness&lt;/h3&gt;

&lt;p&gt;The relationship between the mean and the median gives us information about the shape of the distribution. If the distribution is symmetric, the mean and median will be close to equal. If the distribution is right-skewed (with a long tail on the right), the mean will be larger than the median because it is pulled toward large values. If the distribution is left-skewed, the mean will be smaller than the median.&lt;/p&gt;

&lt;p&gt;This difference is not just a technical detail. It tells us whether the normal distribution is a suitable model. If the mean and median differ significantly, we may need to consider skewed distributions such as the log-normal, gamma, or beta, depending on the nature of the data.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: The two figures below separate the two cases so you can clearly see the positions of the mean and median in each type of distribution.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_mean_median_symmetric.png&quot; alt=&quot;Symmetric distribution with the mean close to the median&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1a: In a nearly symmetric distribution, the mean and median almost coincide.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_mean_median_right_skewed.png&quot; alt=&quot;Right-skewed distribution with the mean pulled toward the tail&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 1b: When data is right-skewed, the long tail pulls the mean to the right more strongly than the median. This is a very useful visual sign before choosing a model.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;a-very-short-example-the-mean-and-median-tell-two-different-stories&quot;&gt;A very short example: the mean and median tell two different stories&lt;/h3&gt;

&lt;p&gt;Suppose the monthly incomes (million VND) of 10 people are:&lt;/p&gt;

\[30,\ 31,\ 32,\ 33,\ 34,\ 35,\ 36,\ 37,\ 38,\ 120\]

&lt;p&gt;Then:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The mean is \(42.6\)&lt;/li&gt;
  &lt;li&gt;The median is \(34.5\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If we only report the mean, it is easy to think this group has a “typical” income of more than 40 million. But in fact 9 out of 10 people lie in the range of 30 to 38 million, and one very large value has pulled the mean up strongly. This example shows why descriptive statistics should always be read together, instead of looking at just a single number.&lt;/p&gt;

&lt;h2 id=&quot;measures-of-spread-quantifying-uncertainty&quot;&gt;Measures of Spread: Quantifying Uncertainty&lt;/h2&gt;

&lt;p&gt;Knowing the central value is not enough. Two datasets can have the same mean but be very different in spread. One may be tightly concentrated around the mean, while the other may be widely dispersed. Measures of spread help us quantify this variability.&lt;/p&gt;

&lt;h3 id=&quot;variance-and-standard-deviation-the-mean-squared-deviation&quot;&gt;Variance and Standard Deviation: The Mean Squared Deviation&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;sample variance&lt;/strong&gt; measures the average spread of the data around the mean:&lt;/p&gt;

\[s^2 = \frac{1}{n-1} \sum_{i=1}^{n} (x_i - \bar{x})^2\]

&lt;p&gt;Note that we divide by \(n-1\) rather than \(n\). This is &lt;strong&gt;Bessel’s correction&lt;/strong&gt;, used to make the sample variance an unbiased estimator of the population variance. The reason for this correction is that we have already used the data to estimate the mean \(\bar{x}\), and this removes one “degree of freedom”.&lt;/p&gt;

&lt;p&gt;Variance has a practical problem: its unit is the square of the original data’s unit. If we measure height in cm, the variance will have units of cm². This makes variance hard to interpret. To remedy this, we use the &lt;strong&gt;standard deviation&lt;/strong&gt;:&lt;/p&gt;

\[s = \sqrt{s^2}\]

&lt;p&gt;The standard deviation has the same unit as the original data and can be interpreted as the “typical deviation” from the mean.&lt;/p&gt;

&lt;p&gt;In Bayesian analysis, the variance (or the precision, the inverse of the variance) is an important parameter to be estimated. When we model data as \(y_i \sim \mathcal{N}(\mu, \sigma^2)\), \(\sigma^2\) is the variance, and its natural estimate is the sample variance \(s^2\).&lt;/p&gt;

&lt;h3 id=&quot;quantiles-and-the-interquartile-range-robust-statistics&quot;&gt;Quantiles and the Interquartile Range: Robust Statistics&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Quantiles&lt;/strong&gt; (or percentiles) divide the distribution into equal parts. The \(p\)-th quantile (\(0 &amp;lt; p &amp;lt; 1\)) is the value such that \(100p\%\) of the data is less than or equal to it. For example, the 0.25 quantile (also called the first quartile, Q1) is the value such that 25% of the data is less than or equal to it.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;interquartile range&lt;/strong&gt; (IQR) is the distance between the third quartile (Q3) and the first quartile (Q1):&lt;/p&gt;

\[\text{IQR} = Q3 - Q1\]

&lt;p&gt;The IQR contains the middle 50% of the data and is a measure of spread that is robust to outliers. It is often used to detect outliers: values lying outside the interval \([Q1 - 1.5 \times \text{IQR}, Q3 + 1.5 \times \text{IQR}]\) are usually regarded as potential outliers.&lt;/p&gt;

&lt;p&gt;In Bayesian analysis, quantiles are widely used to summarize the posterior distribution. Instead of only reporting the mean or median, we often report a &lt;strong&gt;credible interval&lt;/strong&gt;, for example a 95% interval that contains 95% of the posterior probability. This interval is usually constructed from quantiles, for example from the 0.025 quantile to the 0.975 quantile.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: The group of figures below separates the story about spread from the story about the IQR in the box plot.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_spread_same_mean_diff_sd.png&quot; alt=&quot;Two distributions with the same mean but different spread&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 2a: Two datasets with approximately the same mean but very different spread.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_boxplot_iqr_outliers.png&quot; alt=&quot;Box plot showing the IQR and outliers&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 2b: The box plot shows the box containing the middle 50% of the data, the median lying inside the box, and the red points being potential outliers under the \(1.5 \times \text{IQR}\) rule.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;visualization-seeing-the-story-in-the-data&quot;&gt;Visualization: Seeing the Story in the Data&lt;/h2&gt;

&lt;p&gt;Summary numbers are useful, but they cannot replace looking at the data. Visualization lets us see patterns, trends, and anomalies that summary statistics may miss. In Bayesian analysis, visualization is not only an initial exploration tool, but also the way we check models and communicate results.&lt;/p&gt;

&lt;h3 id=&quot;histogram-estimating-the-distribution&quot;&gt;Histogram: Estimating the Distribution&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;histogram&lt;/strong&gt; is one of the most basic visualization tools. It divides the data into intervals (bins) and counts the number of observations in each interval. The height of each bar is proportional to the frequency (or density) of the data in that interval.&lt;/p&gt;

&lt;p&gt;A histogram can be viewed as a rough estimate of the probability density function. As the amount of data grows and the bin width shrinks, the histogram approaches the true PDF of the distribution. This is the idea behind &lt;strong&gt;kernel density estimation&lt;/strong&gt;, a more sophisticated technique for estimating the PDF from data.&lt;/p&gt;

&lt;p&gt;An important question when drawing a histogram is: how many bins should we use? Too few bins lose detail, while too many bins create noise. There is no perfect answer, but rules such as Sturges’ rule (\(k = \lceil \log_2 n \rceil + 1\)) or Scott’s rule can provide a good starting point.&lt;/p&gt;

&lt;h3 id=&quot;box-plot-the-five-number-summary&quot;&gt;Box Plot: The Five-Number Summary&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;box plot&lt;/strong&gt; is a way of visualizing five important summary statistics: the minimum, Q1, the median, Q3, and the maximum. The box contains the middle 50% of the data (from Q1 to Q3), the line inside the box is the median, and the “whiskers” extend to the extreme values (usually \(1.5 \times \text{IQR}\) from the edges of the box). Points lying beyond the whiskers are drawn separately as potential outliers.&lt;/p&gt;

&lt;p&gt;Box plots are especially useful for comparing multiple groups. We can draw several box plots side by side to compare the distributions of different groups, helping detect differences in central location, spread, and skewness.&lt;/p&gt;

&lt;h3 id=&quot;scatter-plot-exploring-relationships&quot;&gt;Scatter Plot: Exploring Relationships&lt;/h3&gt;

&lt;p&gt;When we have two variables, a &lt;strong&gt;scatter plot&lt;/strong&gt; lets us see the relationship between them. Each point represents an observation, with x and y coordinates corresponding to the values of the two variables.&lt;/p&gt;

&lt;p&gt;A scatter plot helps us answer questions such as: Are the two variables correlated? Is the relationship linear or nonlinear? Are there outliers or distinct groups? These questions are very important in Bayesian analysis, because they guide us in choosing a suitable model.&lt;/p&gt;

&lt;h2 id=&quot;correlation-measuring-linear-relationships&quot;&gt;Correlation: Measuring Linear Relationships&lt;/h2&gt;

&lt;p&gt;When we observe the relationship between two variables in a scatter plot, we usually want to quantify how strong that relationship is. The &lt;strong&gt;Pearson correlation coefficient&lt;/strong&gt; provides a measure of linear relationships:&lt;/p&gt;

\[r = \frac{\sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_{i=1}^{n} (x_i - \bar{x})^2} \sqrt{\sum_{i=1}^{n} (y_i - \bar{y})^2}}\]

&lt;p&gt;The correlation coefficient always lies between -1 and 1. A value of \(r = 1\) indicates a perfect positive linear relationship, \(r = -1\) indicates a perfect negative linear relationship, and \(r = 0\) indicates no linear relationship.&lt;/p&gt;

&lt;p&gt;However, we must be careful when interpreting correlation. First, correlation only measures &lt;strong&gt;linear&lt;/strong&gt; relationships. Two variables can have a strong nonlinear relationship but zero correlation. Second, &lt;strong&gt;correlation does not imply causation&lt;/strong&gt;. Two variables being correlated does not mean one causes the other; there may be a hidden third variable affecting both, or the relationship may be due to chance.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: The three figures below separate each type of relationship so you can see why a single correlation coefficient can hide many important things.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_correlation_linear.png&quot; alt=&quot;Positive linear relationship in a scatter plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 3a: A positive linear relationship is a case that Pearson \(r\) describes quite well.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_correlation_nonlinear.png&quot; alt=&quot;Nonlinear relationship in a scatter plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 3b: A nonlinear relationship can be very clear by eye but Pearson \(r\) underestimates it.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/descriptive_correlation_hidden_groups.png&quot; alt=&quot;Correlation caused by a hidden group in a scatter plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Figure 3c: Correlation can appear because of a hidden group variable, so we should always look at the plot before trusting a summary coefficient.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In Bayesian analysis, we usually model correlation explicitly through parameters in the model. For example, in Bayesian linear regression, the regression coefficient \(\beta\) encodes the relationship between the predictor and the response variable, and we can quantify the uncertainty about this relationship through the posterior distribution of \(\beta\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-watching-one-outlier-hijack-the-mean--sd-while-median--iqr-hold-steady&quot;&gt;Worked Numerical Example: Watching One Outlier Hijack the Mean &amp;amp; SD While Median &amp;amp; IQR Hold Steady&lt;/h3&gt;

&lt;p&gt;Compare two tiny 5-person salary datasets (in thousands of dollars):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Clean sample:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[40, 45, 50, 55, 60]&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Outlier sample:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[40, 45, 50, 55, 500]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Summary Statistic&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Clean Sample &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[40,45,50,55,60]&lt;/code&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Outlier Sample &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[40,45,50,55,500]&lt;/code&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Change Caused by 1 Outlier&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Mean (\(\bar{x}\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(50.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(138.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(+176\%\) explosion!&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Median (\(Q_2\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(50.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(50.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0\%\) (unchanged!)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Sample SD (\(s\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(7.91\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(202.4\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(25.6\times\) larger!&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;IQR (\(Q_3 - Q_1\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(55 - 45 = 10.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(55 - 45 = 10.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0\%\) (unchanged!)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Look at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;138 ± 202&lt;/code&gt; on the outlier sample: it gives a lower bound of \(-64\) thousand dollars—completely nonsensical—while &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;median = 50, IQR = 10&lt;/code&gt; remains rock-solid!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-honest-data--posterior-summaries&quot;&gt;Explanation: Four Rules for Honest Data &amp;amp; Posterior Summaries&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always pair a location statistic with a spread statistic:&lt;/strong&gt; A mean without SD (or median without IQR/quantiles) hides half the story.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare mean vs. median as an instant skewness detector:&lt;/strong&gt; If &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean &amp;gt;&amp;gt; median&lt;/code&gt;, you have a heavy right tail; investigate outliers or consider log-transforming before assuming Gaussianity.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Plot the histogram or boxplot alongside numbers:&lt;/strong&gt; Summary numbers cannot detect bimodality (two distinct clusters with an empty middle!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply the same discipline to Bayesian posteriors:&lt;/strong&gt; For skewed parameters like variance \(\sigma^2\) or small-sample rates, report posterior median and 95% equal-tailed or HDI credible intervals alongside the mean.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If a dataset has 5 values &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[10, 12, 14, 16, 18]&lt;/code&gt; and you add &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+100&lt;/code&gt; to &lt;em&gt;every&lt;/em&gt; single value, how do the mean, median, SD, and IQR change?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qBigTkBLU6g&quot;&gt;StatQuest: Histograms, Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch to see that a histogram is a way of telling the shape of the data before computing a single summary number, exactly the spirit of the lesson’s opening.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Finding mean, median, and mode&lt;/td&gt;
          &lt;td&gt;Descriptive statistics&lt;/td&gt;
          &lt;td&gt;Probability and Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=k3aKKasOmIw) — Khan Academy, English. Watch how the mean, median and mode answer different questions, supporting the part on measures of location.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=xZ_z8KWkhXE&quot;&gt;Pearson’s Correlation, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch the Pearson correlation coefficient and its limits, used for the part of the lesson on measuring linear relationships.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1: Computing Descriptive Statistics.&lt;/strong&gt; Given the exam scores of 20 students: [45, 67, 78, 82, 55, 90, 88, 76, 95, 20, 85, 72, 68, 91, 77, 83, 65, 89, 74, 80]. (a) Compute the mean, median, and mode. (b) Compute the variance, standard deviation, and IQR. (c) Detect outliers using the \(1.5 \times \text{IQR}\) rule. (d) Explain why the mean and median differ, and what this says about the distribution of the data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2: Visualization and Interpretation.&lt;/strong&gt; Use Python to generate 1000 observations from: (a) The normal distribution \(\mathcal{N}(50, 10^2)\). (b) The log-normal distribution with parameters \(\mu = 3.5, \sigma = 0.5\). For each distribution, draw a histogram and box plot, compute the mean and median, and explain the difference between the two distributions based on the statistics and plots.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3: Correlation and Causation.&lt;/strong&gt; Consider two pairs of variables: (a) Ice cream sales and the number of drowning incidents (both are high in summer). (b) Hours of study and exam scores. For each pair, discuss: Are they correlated? Is there a causal relationship? If there is correlation but no causation, explain why. What does this teach us about interpreting correlation?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4: Identifying Distributions.&lt;/strong&gt; Given three datasets (you can generate them or use real data): (a) The heights of adults. (b) The number of emails received per day. (c) The waiting time between calls arriving at a call center. For each dataset, draw a histogram, compute descriptive statistics, and propose a suitable probability distribution (normal, Poisson, exponential, etc.). Explain the reasons for your choice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5: Exploring Real Data.&lt;/strong&gt; Download a real dataset (for example: Iris, Boston Housing, or any dataset you are interested in). Carry out a complete exploratory data analysis: (a) Compute descriptive statistics for all numeric variables. (b) Draw histograms and box plots for the continuous variables. (c) Draw scatter plots and compute correlations for pairs of variables. (d) Detect and discuss outliers. (e) Write a short paragraph summarizing what you learned about the data, and propose distributions and models that might suit a Bayesian analysis.&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;h3 id=&quot;primary-references&quot;&gt;Primary References:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., &amp;amp; Rubin, D. B. (2013).&lt;/strong&gt; &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 6: Model checking and improvement (posterior predictive checks)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kruschke, J. K. (2015).&lt;/strong&gt; &lt;em&gt;Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan&lt;/em&gt; (2nd Edition). Academic Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 3: The R Programming Language (data exploration)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;supplementary-reading&quot;&gt;Supplementary Reading:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Tukey, J. W. (1977).&lt;/strong&gt; &lt;em&gt;Exploratory Data Analysis&lt;/em&gt;. Addison-Wesley.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Classic text on EDA philosophy and techniques&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Wickham, H., &amp;amp; Grolemund, G. (2017).&lt;/strong&gt; &lt;em&gt;R for Data Science&lt;/em&gt;. O’Reilly Media.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 7: Exploratory Data Analysis&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_04_python_basics/&quot;&gt;0.7 Basic Python for Data Science&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.5: Beta and Gamma - Distributions for Probabilities and Positive Parameters</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_02_04_beta_gamma_bayesian/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_02_04_beta_gamma_bayesian</id>
   <content type="html">&lt;p&gt;If the Binomial and Poisson distributions describe &lt;em&gt;data&lt;/em&gt;, what distributions describe our &lt;strong&gt;uncertain beliefs about parameters&lt;/strong&gt;—like an unknown conversion rate \(p \in (0,1)\) or an unknown arrival rate \(\lambda &amp;gt; 0\)? Enter the two superheroes of Bayesian statistics: the &lt;strong&gt;Beta distribution&lt;/strong&gt; (living strictly on \([0,1]\)) and the &lt;strong&gt;Gamma distribution&lt;/strong&gt; (living strictly on \((0,\infty)\)).&lt;/p&gt;

&lt;p&gt;This lesson demystifies Beta and Gamma through the unforgettable &lt;strong&gt;pseudo-count intuition&lt;/strong&gt;: \(\mathrm{Beta}(\alpha, \beta)\) behaves like having already seen \(\alpha\) successes and \(\beta\) failures, turning Bayes’ theorem into elementary addition!&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-parameter-space-distributions--conjugacy&quot;&gt;Key ideas: Parameter-Space Distributions &amp;amp; Conjugacy&lt;/h2&gt;

&lt;p&gt;Four concepts make Beta and Gamma second nature for every Bayesian practitioner:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Domain Matching:&lt;/strong&gt; A valid prior must live strictly on the parameter’s legal domain—\(\mathrm{Beta}(\alpha,\beta)\) on \((0,1)\) for probabilities, and \(\mathrm{Gamma}(\alpha,\beta)\) on \((0,\infty)\) for positive rates/precisions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pseudo-Count Interpretation of \(\mathrm{Beta}(\alpha, \beta)\):&lt;/strong&gt; Mean is \(\frac{\alpha}{\alpha+\beta}\) and effective prior sample size is \(\alpha + \beta\). Special cases: \(\mathrm{Beta}(1,1)\) is flat Uniform; \(\mathrm{Beta}(0.5, 0.5)\) is U-shaped Jeffreys; \(\mathrm{Beta}(20, 80)\) concentrates tightly around \(0.20\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Shape–Rate Interpretation of \(\mathrm{Gamma}(\alpha, \beta)\):&lt;/strong&gt; Mean is \(\frac{\alpha}{\beta}\) and variance is \(\frac{\alpha}{\beta^2}\), behaving like \(\alpha\) pseudo-events observed over \(\beta\) pseudo-units of time!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Algebraic Conjugacy:&lt;/strong&gt; Multiplying \(\mathrm{Beta}(\alpha,\beta)\) by a Binomial likelihood \((k\text{ successes}, n-k\text{ failures})\) yields \(\mathrm{Beta}(\alpha+k,\; \beta+n-k)\); multiplying \(\mathrm{Gamma}(\alpha,\beta)\) by Poisson counts \(\sum k_i\) over \(T\) time units yields \(\mathrm{Gamma}(\alpha+\sum k_i,\; \beta+T)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will understand that the Beta arises from the need to describe quantities lying in the interval \([0,1]\), be able to read the meaning of the parameters \(\alpha,\beta\), and grasp the role of the normalizing constant in forming a valid distribution.&lt;/p&gt;

&lt;h2 id=&quot;1-starting-from-a-practical-problem-describing-an-unknown-proportion&quot;&gt;1) Starting from a practical problem: describing an unknown proportion&lt;/h2&gt;

&lt;p&gt;In practice, we often meet quantities in the form of proportions such as:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the proportion of customers who will click,&lt;/li&gt;
  &lt;li&gt;the proportion of defective products,&lt;/li&gt;
  &lt;li&gt;the proportion of students who complete a course.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These quantities have one thing in common: they always lie between 0 and 1.&lt;/p&gt;

&lt;p&gt;We need a distribution flexible enough to describe many different shapes on that interval: it can lean left, lean right, or concentrate around a central region. That is exactly the role of the Beta distribution.&lt;/p&gt;

&lt;h2 id=&quot;2-the-beta-for-probabilities&quot;&gt;2) The Beta for probabilities&lt;/h2&gt;

\[p\sim\text{Beta}(\alpha,\beta), \quad 0&amp;lt;p&amp;lt;1.\]

&lt;p&gt;Quick interpretation:&lt;/p&gt;

&lt;p&gt;\(\alpha-1\) can be understood as the part leaning toward “success”, while \(\beta-1\) leans toward “failure”.&lt;/p&gt;

&lt;p&gt;Mean:&lt;/p&gt;

\[\mathbb{E}[p]=\frac{\alpha}{\alpha+\beta}.\]

&lt;p&gt;When \(\alpha+\beta\) is large, the distribution is more concentrated; when small, the distribution is more spread out.&lt;/p&gt;

&lt;p&gt;The normalizing constant of the Beta is:&lt;/p&gt;

\[B(\alpha,\beta)=\int_0^1 p^{\alpha-1}(1-p)^{\beta-1}\,dp
=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}.\]

&lt;p&gt;Therefore the full density must be written:&lt;/p&gt;

\[f(p)=\frac{1}{B(\alpha,\beta)}p^{\alpha-1}(1-p)^{\beta-1},\quad 0&amp;lt;p&amp;lt;1.\]

&lt;h2 id=&quot;3-the-gamma-function-and-the-bridge-to-the-beta-function&quot;&gt;3) The Gamma function and the bridge to the Beta function&lt;/h2&gt;

&lt;p&gt;To understand the normalizing constant of the Beta better, we need the Gamma function:&lt;/p&gt;

\[\Gamma(z)=\int_0^{\infty} t^{z-1}e^{-t}\,dt,\quad z&amp;gt;0.\]

&lt;p&gt;The Gamma function is an extension of the factorial to positive reals, with the property:&lt;/p&gt;

\[\Gamma(z+1)=z\,\Gamma(z),\qquad \Gamma(n+1)=n!\;(n\in\mathbb{N}).\]

&lt;p&gt;Thanks to that, the normalizing constant of the Beta can be written compactly:&lt;/p&gt;

\[B(\alpha,\beta)=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}.\]

&lt;p&gt;Practical meaning: we turn a normalizing integral that is hard to compute directly into a ratio of Gammas, for more stable computation and a clearer structure.&lt;/p&gt;

&lt;h2 id=&quot;4-what-problem-does-the-beta-solve&quot;&gt;4) What problem does the Beta solve?&lt;/h2&gt;

&lt;p&gt;The Beta gives us a systematic way to describe the question: “which region of the interval \([0,1]\) does the true proportion tend to lie in, and how strongly or weakly concentrated is it?”&lt;/p&gt;

&lt;p&gt;In short:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\alpha\) and \(\beta\) control the shape,&lt;/li&gt;
  &lt;li&gt;\(\frac{\alpha}{\alpha+\beta}\) gives the central location,&lt;/li&gt;
  &lt;li&gt;\(\alpha+\beta\) gives the degree of concentration.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Thanks to this, the Beta gives not just a single proportion value, but also the uncertainty around that proportion.&lt;/p&gt;

&lt;h2 id=&quot;5-example-of-reading-a-beta-shape&quot;&gt;5) Example of reading a Beta shape&lt;/h2&gt;

&lt;p&gt;Suppose \(\alpha=2,\beta=5\); then the density leans toward the region near 0; if changed to \(\alpha=8,\beta=3\) then the density leans toward the region near 1.&lt;/p&gt;

&lt;p&gt;In other words, the pair \(\alpha,\beta\) controls both the location and the concentration of the distribution on the interval \([0,1]\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/beta_binomial_update_vi.png&quot; alt=&quot;Comparing Beta shapes with different parameter sets&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates how changing the parameters shifts and stretches the shape of the Beta distribution on the interval \([0,1]\).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;6-the-gamma-for-positive-parameters&quot;&gt;6) The Gamma for positive parameters&lt;/h2&gt;

&lt;p&gt;A commonly used shape-rate parameterization:&lt;/p&gt;

\[\lambda\sim\text{Gamma}(\alpha,\beta), \quad
f(\lambda)=\frac{\beta^\alpha}{\Gamma(\alpha)}\lambda^{\alpha-1}e^{-\beta\lambda},\; \lambda&amp;gt;0.\]

&lt;p&gt;Expectation:&lt;/p&gt;

\[\mathbb{E}[\lambda]=\frac{\alpha}{\beta}.\]

&lt;p&gt;Here \(\frac{\beta^\alpha}{\Gamma(\alpha)}\) is the normalizing constant so that:&lt;/p&gt;

\[\int_0^{\infty} f(\lambda)\,d\lambda=1.\]

&lt;p&gt;If this ratio is dropped, we only have the “shape” \(\lambda^{\alpha-1}e^{-\beta\lambda}\), not yet a valid distribution.&lt;/p&gt;

&lt;h2 id=&quot;7-an-intuitive-example-with-the-gamma&quot;&gt;7) An intuitive example with the Gamma&lt;/h2&gt;

&lt;p&gt;With shape-rate:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;if we keep \(\alpha\) and increase \(\beta\), the distribution shifts closer to 0,&lt;/li&gt;
  &lt;li&gt;if we increase \(\alpha\), the distribution has a clearer peak and is less skewed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is useful when describing positive quantities such as waiting times, event intensity, or variables with a right tail.&lt;/p&gt;

&lt;h2 id=&quot;8-unnormalized-and-normalized-forms&quot;&gt;8) Unnormalized and normalized forms&lt;/h2&gt;

&lt;p&gt;In practice, we often meet the “kernel” form first, for example:&lt;/p&gt;

\[g(p)=p^{\alpha-1}(1-p)^{\beta-1}.\]

&lt;p&gt;This is not yet a valid density because the integral over \([0,1]\) is not necessarily 1. To become a density, we need to divide by the normalizing constant:&lt;/p&gt;

\[f(p)=\frac{1}{B(\alpha,\beta)}g(p).\]

&lt;p&gt;A similar idea applies to the Gamma: the exponential and power parts give the shape, while the front coefficient ensures the total probability equals 1.&lt;/p&gt;

&lt;h2 id=&quot;9-practical-tip&quot;&gt;9) Practical tip&lt;/h2&gt;

&lt;p&gt;When using the Gamma, always state clearly whether the parameterization is shape-rate or shape-scale. When reading documentation, check the notation carefully to avoid confusing the rate \(\beta\) with the scale \(\theta=1/\beta\).&lt;/p&gt;

&lt;h2 id=&quot;10-extending-from-the-factorial-to-the-gamma&quot;&gt;10) Extending from the factorial to the Gamma&lt;/h2&gt;

&lt;p&gt;For positive integers, we have the factorial:&lt;/p&gt;

\[n!=1\cdot 2\cdot 3\cdots n.\]

&lt;p&gt;The Gamma function extends this idea to positive reals. So we can quickly understand:&lt;/p&gt;

\[x!=\Gamma(x+1),\quad x&amp;gt;0.\]

&lt;p&gt;Example:&lt;/p&gt;

\[\Gamma(1)=1,\quad \Gamma(2)=1!,\quad \Gamma(3)=2!,\quad \Gamma(6)=5!.\]

&lt;h2 id=&quot;11-common-special-values&quot;&gt;11) Common special values&lt;/h2&gt;

&lt;p&gt;A famous value:&lt;/p&gt;

\[\Gamma\!\left(\frac{1}{2}\right)=\sqrt{\pi}.\]

&lt;p&gt;From the recurrence formula we deduce:&lt;/p&gt;

\[\Gamma\!\left(\frac{3}{2}\right)=\frac{\sqrt{\pi}}{2},
\qquad
\Gamma\!\left(\frac{5}{2}\right)=\frac{3\sqrt{\pi}}{4}.\]

&lt;p&gt;This is why \(\pi\) appears in many continuous distribution formulas.&lt;/p&gt;

&lt;h2 id=&quot;12-a-short-example-with-the-beta-function&quot;&gt;12) A short example with the Beta function&lt;/h2&gt;

&lt;p&gt;With \(a,b&amp;gt;0\):&lt;/p&gt;

\[B(a,b)=\int_0^1 t^{a-1}(1-t)^{b-1}\,dt
=\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}.\]

&lt;p&gt;Example:&lt;/p&gt;

\[B(2,3)=\frac{\Gamma(2)\Gamma(3)}{\Gamma(5)}=\frac{1!\,2!}{4!}=\frac{1}{12}.\]

&lt;p&gt;This part shows clearly the role of the Gamma as a tool for computing the normalizing constant of the Beta.&lt;/p&gt;

&lt;h2 id=&quot;13-a-numerical-example-for-the-beta-shape-710&quot;&gt;13) A numerical example for the Beta shape (7/10)&lt;/h2&gt;

&lt;p&gt;Suppose we consider the expression in \(\theta\) on the interval \([0,1]\):&lt;/p&gt;

\[g(\theta)=\theta^8(1-\theta)^4.\]

&lt;p&gt;This is only the unnormalized form. The normalized form is:&lt;/p&gt;

\[f(\theta)=\frac{1}{B(9,5)}\theta^8(1-\theta)^4.\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/beta_binomial_update_7of10.png&quot; alt=&quot;Beta-Binomial update 7 over 10&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: The curve shows that the unnormalized and normalized forms have the same relative shape; the factor \(1/B(9,5)\) only turns the curve into a valid density (area equal to 1).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;14-hints-for-numerically-stable-computation&quot;&gt;14) Hints for numerically stable computation&lt;/h2&gt;

&lt;p&gt;When the parameters are large, use log-functions instead of computing directly:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln(z)&lt;/code&gt; instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(gamma(z))&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;betaln(a,b)&lt;/code&gt; instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log(beta(a,b))&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In SciPy, these functions are in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.special&lt;/code&gt; and are more stable in computation.&lt;/p&gt;

&lt;p&gt;Python example:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scipy.special&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gammaln&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;betaln&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# 120.0
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# ~1.7724538509 = sqrt(pi)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gammaln&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# log(Gamma(100))
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# 1/12 = 0.08333...
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;betaln&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# log(Beta(2,3))
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;15-quick-summary&quot;&gt;15) Quick summary&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;The Beta is a flexible distribution for quantities in \([0,1]\).&lt;/li&gt;
  &lt;li&gt;The Gamma is a distribution for positive quantities.&lt;/li&gt;
  &lt;li&gt;The Gamma function extends the factorial: \(\Gamma(n+1)=n!\).&lt;/li&gt;
  &lt;li&gt;The Beta function is directly related to the Gamma via the ratio \(\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}\).&lt;/li&gt;
  &lt;li&gt;The normalizing constant turns an expression of the “right shape” into a valid density.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=juF3r12nM5A&quot;&gt;The Beta distribution in 12 minutes!&lt;/a&gt; — Luis Serrano Academy, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch to read α and β as the numbers of successes and failures known beforehand, exactly the Beta on the interval from 0 to 1 part.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=9IIcHAJlcWc&quot;&gt;The Gamma Distribution&lt;/a&gt; — Steve Brunton, English. Watch the Gamma shape for positive quantities, supporting the half of the lesson about rate parameters and waiting times.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How to Estimate Rates with a Gamma-Poisson Bayesian Model&lt;/td&gt;
          &lt;td&gt;Conjugate Priors](https://www.youtube.com/watch?v=m8roQUqmybg) — Drawing Distributions, English. Watch the Gamma–Poisson pair when estimating an event rate, linking the distributions in the lesson to Bayesian updating in the closing connection.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-hand-updating-both-a-betabinomial-and-a-gammapoisson-prior&quot;&gt;Worked Numerical Example: Hand-Updating Both a Beta–Binomial and a Gamma–Poisson Prior&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Part A — Beta–Binomial Update (Click Rate \(p\)):&lt;/strong&gt;
Start with a mildly informed prior \(\mathrm{Beta}(\alpha_0 = 2,\; \beta_0 = 8)\) (prior mean \(2/10 = 0.20\)). Now observe \(k = 6\) clicks in \(n = 10\) visits (4 non-clicks):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Posterior: \(\mathrm{Beta}(2 + 6,\; 8 + 4) = \mathbf{\mathrm{Beta}(8,\; 12)}\).&lt;/li&gt;
  &lt;li&gt;Posterior mean: \(\frac{8}{8+12} = \mathbf{0.40}\) (a weighted average of prior mean \(0.20\) and data rate \(0.60\)!).&lt;/li&gt;
  &lt;li&gt;Posterior variance: \(\frac{8\times 12}{20^2 \times 21} = \frac{96}{8400} \approx 0.01143 \implies \mathrm{SD} \approx 0.107\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Part B — Gamma–Poisson Update (Bug Rate \(\lambda\) per Day):&lt;/strong&gt;
Start with prior \(\mathrm{Gamma}(\alpha_0 = 4,\; \beta_0 = 2)\) (prior mean \(4/2 = 2.0\) bugs/day). Over \(T = 3\) days, you observe \(\sum k_i = 11\) bugs:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Posterior: \(\mathrm{Gamma}(4 + 11,\; 2 + 3) = \mathbf{\mathrm{Gamma}(15,\; 5)}\).&lt;/li&gt;
  &lt;li&gt;Posterior mean: \(\frac{15}{5} = \mathbf{3.0}\) bugs/day; posterior SD: \(\frac{\sqrt{15}}{5} \approx 0.775\) bugs/day!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;explanation-four-rules-for-choosing-beta-and-gamma-priors&quot;&gt;Explanation: Four Rules for Choosing Beta and Gamma Priors&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check shape–rate vs. shape–scale parameterization in software:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats.gamma&lt;/code&gt; uses &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale = 1/rate&lt;/code&gt;, whereas Bayesian textbooks and Stan often use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rate = \beta&lt;/code&gt;! Mixing them up inverts your mean!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use prior predictive checks to verify your pseudo-counts:&lt;/strong&gt; Ask &lt;em&gt;“does \(\mathrm{Beta}(2,8)\) put reasonable mass across the conversion rates I consider plausible before seeing data?”&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Watch how prior weight fades as data grows:&lt;/strong&gt; In Part A, the prior had weight 10 and the data had weight 10 (50–50 blend); with \(n = 1{,}000\) visits, data carries 99% of the weight.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mean vs. Mode (MAP):&lt;/strong&gt; For \(\mathrm{Beta}(\alpha,\beta)\) with \(\alpha,\beta &amp;gt; 1\), the mode is \(\frac{\alpha-1}{\alpha+\beta-2}\), which differs slightly from the mean \(\frac{\alpha}{\alpha+\beta}\) when the posterior is skewed.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In Part A above, if you observe &lt;em&gt;another&lt;/em&gt; batch of 10 visits with 6 clicks (updating sequentially from \(\mathrm{Beta}(8,12)\)), what is the new posterior Beta distribution—and does it match updating once on all 20 visits (12 clicks, 8 non-clicks)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1.&lt;/strong&gt; Use the recurrence formula to compute \(\Gamma(4)\) and \(\Gamma(5)\), then compare with \(3!\) and \(4!\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2.&lt;/strong&gt; From \(\Gamma\!\left(\tfrac{1}{2}\right)=\sqrt{\pi}\), deduce \(\Gamma\!\left(\tfrac{3}{2}\right)\) and \(\Gamma\!\left(\tfrac{5}{2}\right)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3.&lt;/strong&gt; Rewrite the normalizing constant of Beta(\(a,b\)) using the Gamma and explain why this constant is needed for the density to integrate to 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4.&lt;/strong&gt; In Python, compute &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gamma(10)&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln(10)&lt;/code&gt;. Check whether &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.log(gamma(10))&lt;/code&gt; is close to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln(10)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5.&lt;/strong&gt; Quickly prove \(B(a,1)=\frac{1}{a}\) from the integral definition, then compare with the Gamma ratio formula.&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Gelman, A., et al. (2013). &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd ed.). CRC Press.&lt;/li&gt;
  &lt;li&gt;Kruschke, J. (2015). &lt;em&gt;Doing Bayesian Data Analysis&lt;/em&gt; (2nd ed.). Academic Press.&lt;/li&gt;
  &lt;li&gt;SciPy Special Functions: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gamma&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gammaln&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Beta and Gamma are two foundational families of distributions in statistics: the Beta for variables in \([0,1]\) and the Gamma for positive variables. The most important point of the lesson is knowing how to choose the right domain and understanding the role of the normalizing constant in turning a “shape” into a valid distribution.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_03_descriptive_statistics/&quot;&gt;0.6 Descriptive Statistics&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.4: Normal and CLT Intuition - When Does Data Look Bell-Shaped?</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_02_03_normal_clt_intuition/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_02_03_normal_clt_intuition</id>
   <content type="html">&lt;p&gt;Why does the bell-shaped &lt;strong&gt;Normal (Gaussian) distribution&lt;/strong&gt; keep popping up everywhere—from human heights and measurement errors to the posterior distributions of Bayesian parameters with large datasets? Not because nature has a mystical fondness for bells, but because &lt;strong&gt;adding many small, independent disturbances washes out their individual shapes&lt;/strong&gt;—the miracle of the &lt;strong&gt;Central Limit Theorem (CLT)&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;This lesson builds geometric intuition for the Normal distribution’s 68–95–99.7 rule, explains &lt;em&gt;when&lt;/em&gt; the CLT works (and when heavy tails or multiplicative growth break it), and connects Gaussianity directly to the &lt;strong&gt;Laplace / Bernstein–von Mises approximation&lt;/strong&gt; in Bayesian inference.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-why-gaussians-dominate-both-data-and-posteriors&quot;&gt;Key ideas: Why Gaussians Dominate Both Data and Posteriors&lt;/h2&gt;

&lt;p&gt;Four deep properties explain the ubiquity of the Normal distribution in Bayesian statistics:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Standardization (Z-Score):&lt;/strong&gt; Every Normal \(\mathcal{N}(\mu, \sigma^2)\) reduces to \(\mathcal{N}(0,1)\) via \(Z = \frac{X-\mu}{\sigma}\), giving the universal 68% (\(\pm 1\sigma\)), 95% (\(\pm 1.96\sigma\)), and 99.7% (\(\pm 3\sigma\)) intervals.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Additive Closure &amp;amp; the CLT:&lt;/strong&gt; Sums of independent random variables with finite variance converge in distribution to a Normal—explaining why averages \(\bar{X}_n\) look bell-shaped even when raw data is skewed.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multiplicative Processes Produce Log-Normal, Not Normal:&lt;/strong&gt; When effects &lt;em&gt;multiply&lt;/em&gt; (compound returns, incomes, file sizes), \(\log Y\) is Normal—so \(Y\) itself is right-skewed Log-Normal!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Bernstein–von Mises Theorem:&lt;/strong&gt; As sample size \(n\) grows, smooth Bayesian posteriors concentrate around the MLE and look increasingly Gaussian—justifying fast Normal approximations while reminding us that at &lt;em&gt;small \(n\)&lt;/em&gt; or boundary constraints, exact posteriors can be strongly skewed.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will understand the role of the Normal distribution, interpret the parameters \(\mu,\sigma\) correctly, and know how to use the intuition of the central limit theorem (CLT) to explain why many aggregate quantities are approximately normal.&lt;/p&gt;

&lt;h2 id=&quot;1-what-is-the-normal-distribution&quot;&gt;1) What is the Normal distribution?&lt;/h2&gt;

&lt;p&gt;For a continuous variable \(X\):&lt;/p&gt;

\[X\sim\mathcal{N}(\mu,\sigma^2),\]

&lt;p&gt;the density function is:&lt;/p&gt;

\[f(x)=\frac{1}{\sigma\sqrt{2\pi}}\exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right).\]

&lt;p&gt;Here, \(\mu\) gives the central location of the distribution, while \(\sigma\) measures the spread around that center. A quick rule of thumb is that the interval \(\mu\pm\sigma\) contains approximately 68% of the probability mass, the interval \(\mu\pm 2\sigma\) contains about 95%, and the interval \(\mu\pm 3\sigma\) contains about 99.7%.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/normal_distribution_rule.png&quot; alt=&quot;The 68-95-99.7 rule of the Normal distribution&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates the 68-95-99.7 rule of the normal distribution. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-why-does-the-normal-appear-so-often&quot;&gt;2) Why does the Normal appear so often?&lt;/h2&gt;

&lt;p&gt;The CLT says: when adding up (or averaging) many independent noise components, the aggregate usually approaches a normal shape, even if each initial component is not normal.&lt;/p&gt;

&lt;p&gt;So quantities such as measurement error, average scores, and the total influence of many small factors are usually close to Normal.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/clt_sample_means_overlay.png&quot; alt=&quot;The CLT makes the distribution of the sample mean gradually rounder and narrower&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates that the CLT makes the distribution of the sample mean gradually rounder and narrower. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-where-does-the-normalizing-constant-of-the-normal-come-from&quot;&gt;3) Where does the normalizing constant of the Normal come from?&lt;/h2&gt;

&lt;p&gt;The Normal density has the form:&lt;/p&gt;

\[f(x)=\frac{1}{\sigma\sqrt{2\pi}}\exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right).\]

&lt;p&gt;The factor \(\frac{1}{\sigma\sqrt{2\pi}}\) is the normalizing constant that ensures:&lt;/p&gt;

\[\int_{-\infty}^{\infty} f(x)\,dx=1.\]

&lt;p&gt;Setting the standardized variable \(z=\frac{x-\mu}{\sigma}\), we get:&lt;/p&gt;

\[\int_{-\infty}^{\infty} f(x)\,dx
=\int_{-\infty}^{\infty}\frac{1}{\sqrt{2\pi}}e^{-z^2/2}\,dz
=1.\]

&lt;p&gt;That is, the whole “probability mass” of the bell curve equals exactly 1, which is why it is a valid density.&lt;/p&gt;

&lt;h2 id=&quot;4-an-intuitive-example&quot;&gt;4) An intuitive example&lt;/h2&gt;

&lt;p&gt;Suppose the final exam score is influenced by many small factors:&lt;/p&gt;

&lt;p&gt;For example sleep quality, level of revision, the difficulty of each question, and psychological state during the exam.&lt;/p&gt;

&lt;p&gt;Each factor varies a little, but their combination usually gives a score distribution close to a bell shape. This is why using a Normal model for errors or for total scores is reasonable in many contexts.&lt;/p&gt;

&lt;h3 id=&quot;41-a-quick-reading-using-the-standard-deviation&quot;&gt;4.1) A quick reading using the standard deviation&lt;/h3&gt;

&lt;p&gt;Suppose the heights of a group of people can be approximated by:&lt;/p&gt;

\[X \sim \mathcal{N}(170, 6^2).\]

&lt;p&gt;Then we can read very quickly:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The range \(164\) to \(176\) cm is \(\mu \pm 1\sigma\), usually containing approximately 68% of observations.&lt;/li&gt;
  &lt;li&gt;The range \(158\) to \(182\) cm is \(\mu \pm 2\sigma\), usually containing approximately 95% of observations.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So, a person who is \(182\) cm tall is not “so unusual as to be impossible”, but is just sitting near the upper edge of the roughly 95% region. This is an intuitive way to read the Normal without needing to look up a table or compute an integral.&lt;/p&gt;

&lt;h2 id=&quot;5-when-should-the-normal-not-be-used&quot;&gt;5) When should the Normal not be used?&lt;/h2&gt;

&lt;p&gt;The Normal is no longer a good choice when the data is bounded in its domain, such as a probability lying only in \([0,1]\) or a waiting time that is always positive, when the data is non-negative integer counts, or when the distribution is strongly skewed, heavy-tailed, or contains many outliers. In these cases, the Normal assumption can distort the uncertainty intervals considerably.&lt;/p&gt;

&lt;h2 id=&quot;6-the-bayesian-connection&quot;&gt;6) The Bayesian connection&lt;/h2&gt;

&lt;p&gt;In Bayesian modeling, the Normal distribution appears at many different levels: it can serve as the likelihood for continuous data, as the prior for regression coefficients, or appear as a convenient approximation of the posterior when the sample size is large enough. Still, the Bayesian workflow always requires careful model checking, instead of assuming by default that any continuous data can unconditionally be given a Normal.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-applying-the-z-score-and-clt-scaling-by-hand&quot;&gt;Worked Numerical Example: Applying the Z-Score and CLT Scaling by Hand&lt;/h3&gt;

&lt;p&gt;Suppose individual shipping weights follow a skewed distribution with mean \(\mu = 500\text{ g}\) and standard deviation \(\sigma = 40\text{ g}\). A pallet holds \(n = 16\) independent packages:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Distribution of the sample mean weight \(\bar{X}_{16}\) (by CLT):&lt;/strong&gt;
\(\mathbb{E}[\bar{X}_{16}] = 500\text{ g}, \qquad \mathrm{SE} = \frac{\sigma}{\sqrt{n}} = \frac{40}{\sqrt{16}} = 10\text{ g}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Probability that the pallet’s average package weight exceeds \(520\text{ g}\):&lt;/strong&gt;
Compute the \(Z\)-score:
\(z = \frac{520 - 500}{10} = +2.00.\)
Since roughly \(95.4\%\) of a standard Normal sits inside \([-2, +2]\), the upper tail \(P(Z &amp;gt; 2.0) \approx \frac{1 - 0.9545}{2} \approx \mathbf{2.28\%}\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Contrast with a single package:&lt;/strong&gt; For \(n=1\), \(520\text{ g}\) is only \(+0.5\sigma\) above the mean (very common, ~31%); averaging 16 packages concentrates the distribution 4× tighter!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-checks-before-assuming-normality&quot;&gt;Explanation: Four Checks Before Assuming Normality&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Check whether the mechanism is additive or multiplicative:&lt;/strong&gt; Additive noise \(\to\) Normal; multiplicative percentages \(\to\) model \(\log Y\) as Normal.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Watch for heavy tails and outliers:&lt;/strong&gt; Extreme outliers (Cauchy-like or financial crashes) break Gaussian assumptions—in Bayesian modeling, swap Normal likelihoods for a heavy-tailed &lt;strong&gt;Student-\(t\)&lt;/strong&gt; likelihood for instant robustness!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Remember the CLT applies to &lt;em&gt;sums and averages&lt;/em&gt;, not individual data points:&lt;/strong&gt; Increasing \(n\) makes \(\bar{X}_n\) more Normal, &lt;em&gt;never&lt;/em&gt; the raw skewed histogram of \(X_i\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never blindly use Normal intervals near boundaries:&lt;/strong&gt; A probability \(p = 0.02\) with \(\mathrm{SE} = 0.02\) gives a naive Normal CI \([-0.02, +0.06]\) (impossible negative probability!); exact Beta posteriors stay strictly inside \([0,1]\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; In the shipping example above (\(\mu = 500\text{ g}, \sigma = 40\text{ g}\)), if we put \(n = 64\) packages on a pallet instead of \(16\), what is the new standard error of \(\bar{X}_{64}\), and what is the new \(Z\)-score for an average weight of \(520\text{ g}\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=rzFX5NWojp0&quot;&gt;The Normal Distribution, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch to read μ and σ on the bell curve, exactly the part of the lesson that interprets the parameters of the Normal distribution.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zeJD6dqJ5lo&quot;&gt;But what is the Central Limit Theorem?&lt;/a&gt; — 3Blue1Brown, English. Watch the intuition for why the average of many independent variables is close to normal, supporting the central limit theorem part.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Sm2yBx3Jn6c&quot;&gt;Định lý giới hạn trung tâm (Central limit theorem)&lt;/a&gt; — Bài Học 10 Phút, Vietnamese. Watch a short Vietnamese version on the same theorem, to compare with the lesson’s argument about when aggregate data looks bell-shaped.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practice-questions&quot;&gt;Practice questions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Name a continuous quantity for which the Normal should be used and explain why.&lt;/li&gt;
  &lt;li&gt;Name a continuous quantity for which the Normal should not be used and propose a replacement distribution.&lt;/li&gt;
  &lt;li&gt;How does the CLT help the intuition about the distribution of the sample mean?&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_02_04_beta_gamma_bayesian/&quot;&gt;0.5 Beta and Gamma&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.3: Poisson and Exponential - Counting Events and Waiting Times</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_02_02_poisson_exponential/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_02_02_poisson_exponential</id>
   <content type="html">&lt;p&gt;Stand by a quiet highway and watch cars pass at an average rate of \(\lambda = 3\) cars per minute. Two twin questions immediately arise: &lt;em&gt;How many cars will pass in the next minute?&lt;/em&gt; (&lt;strong&gt;Poisson&lt;/strong&gt;), and &lt;em&gt;How long will I wait until the very next car arrives?&lt;/em&gt; (&lt;strong&gt;Exponential&lt;/strong&gt;). They are not two unrelated textbook formulas—they are two faces of the exact same continuous-time &lt;strong&gt;Poisson process&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;This lesson builds intuitive command over Poisson counts and Exponential waiting times, explains the startling &lt;strong&gt;memoryless property&lt;/strong&gt;, warns against real-world overdispersion, and sets up their natural Bayesian conjugate partner: the &lt;strong&gt;Gamma distribution&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-the-duality-of-counts-and-waiting-times&quot;&gt;Key ideas: The Duality of Counts and Waiting Times&lt;/h2&gt;

&lt;p&gt;Four structural facts link Poisson, Exponential, and Bayesian rate modeling:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Poisson Count Distribution:&lt;/strong&gt; Counts independent events occurring at constant rate \(\lambda\) per unit time: \(P(N=k\mid \lambda) = \frac{\lambda^k e^{-\lambda}}{k!}\) with exact &lt;strong&gt;equidispersion&lt;/strong&gt; \(\mathbb{E}[N] = \mathrm{Var}(N) = \lambda\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exponential Waiting Time:&lt;/strong&gt; The waiting time \(T\) until the next event has PDF \(f(t\mid \lambda) = \lambda e^{-\lambda t}\) (\(t \ge 0\)), mean \(1/\lambda\), and survival function \(P(T &amp;gt; t) = e^{-\lambda t}\). Notice that \(P(T &amp;gt; 1) = e^{-\lambda} = P(N = 0)\)—waiting more than 1 minute is literally identical to seeing 0 cars in 1 minute!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Memoryless Property:&lt;/strong&gt; \(P(T &amp;gt; s + t \mid T &amp;gt; s) = P(T &amp;gt; t)\). Having waited 5 minutes with no bus tells you nothing about the remaining wait if arrivals are truly Poisson (useful for radioactive decay, dangerous for aging machinery!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Gamma–Poisson Conjugacy:&lt;/strong&gt; Writing \(L(\lambda) \propto \lambda^{\sum k_i} e^{-n\lambda}\) has the exact algebraic kernel of a &lt;strong&gt;Gamma distribution&lt;/strong&gt;, letting us update our belief about an unknown rate \(\lambda\) by simple addition!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will be able to model count data with the Poisson, model waiting times with the Exponential, and understand why these two distributions are two faces of the same random event process over time.&lt;/p&gt;

&lt;h2 id=&quot;1-when-to-use-the-poisson&quot;&gt;1) When to use the Poisson?&lt;/h2&gt;

&lt;p&gt;The Poisson is suitable when we count the number of events in a fixed interval:&lt;/p&gt;

&lt;p&gt;Typical examples are the number of calls in 1 hour, the number of errors on 1 page of text, or the number of accidents at an intersection in 1 month.&lt;/p&gt;

&lt;p&gt;If \(Y\) is the number of events in the observation interval:&lt;/p&gt;

\[Y \sim \text{Poisson}(\lambda), \quad P(Y=k)=\frac{\lambda^k e^{-\lambda}}{k!},\; k=0,1,2,\dots\]

&lt;p&gt;Here \(\lambda\) is the average number of events per interval.&lt;/p&gt;

&lt;p&gt;Core properties:&lt;/p&gt;

\[\mathbb{E}[Y]=\lambda, \qquad \mathrm{Var}(Y)=\lambda.\]

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/poisson_counts_timeline.png&quot; alt=&quot;The Poisson describes the number of events counted in fixed time intervals&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates that the Poisson describes the number of events counted in fixed time intervals. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-when-to-use-the-exponential&quot;&gt;2) When to use the Exponential?&lt;/h2&gt;

&lt;p&gt;The Exponential is suitable when we care about the waiting time until the next event.&lt;/p&gt;

&lt;p&gt;If \(T\) is the waiting time:&lt;/p&gt;

\[T \sim \text{Exponential}(\lambda), \quad f(t)=\lambda e^{-\lambda t},\; t\ge 0.\]

&lt;p&gt;Expectation:&lt;/p&gt;

\[\mathbb{E}[T]=\frac{1}{\lambda}.\]

&lt;p&gt;That is, the higher the event rate, the lower the average waiting time.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/exponential_waiting_time_curve.png&quot; alt=&quot;The Exponential describes the waiting time until the next event&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates that the Exponential describes the waiting time until the next event. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;3-the-normalizing-constant-in-poissonexponential&quot;&gt;3) The normalizing constant in Poisson/Exponential&lt;/h2&gt;

&lt;p&gt;For the Poisson:&lt;/p&gt;

\[P(Y=k)=\frac{\lambda^k e^{-\lambda}}{k!},\quad k=0,1,2,\dots\]

&lt;p&gt;Where:&lt;/p&gt;

&lt;p&gt;Here, \(k!\) reflects the number of ways of arranging the events in the combinatorial counting argument, while \(e^{-\lambda}\) is the factor that makes the whole PMF sum to exactly 1.&lt;/p&gt;

&lt;p&gt;Indeed:&lt;/p&gt;

\[\sum_{k=0}^{\infty} \frac{\lambda^k e^{-\lambda}}{k!}
=e^{-\lambda}\sum_{k=0}^{\infty}\frac{\lambda^k}{k!}
=e^{-\lambda}e^{\lambda}=1.\]

&lt;p&gt;For the Exponential:&lt;/p&gt;

\[f(t)=\lambda e^{-\lambda t},\quad t\ge 0.\]

&lt;p&gt;The constant \(\lambda\) is the normalizing factor that makes the density integrate to 1:&lt;/p&gt;

\[\int_0^{\infty} \lambda e^{-\lambda t}\,dt=1.\]

&lt;p&gt;If \(\lambda\) is dropped, the function \(e^{-\lambda t}\) is only the exponentially decaying “shape”, not yet a valid density.&lt;/p&gt;

&lt;h2 id=&quot;4-the-direct-link-between-poisson-and-exponential&quot;&gt;4) The direct link between Poisson and Exponential&lt;/h2&gt;

&lt;p&gt;If the number of events over time follows a Poisson process with rate \(\lambda\), then:&lt;/p&gt;

&lt;p&gt;The number of events in a longer interval \(\Delta t\) will have a Poisson(\(\lambda\Delta t\)) distribution, while the time between two consecutive events will have an Exponential(\(\lambda\)) distribution.&lt;/p&gt;

&lt;p&gt;So, the questions “how many events are counted” and “how long to wait until the next event” are really the same model from two viewpoints.&lt;/p&gt;

&lt;h2 id=&quot;5-a-short-example&quot;&gt;5) A short example&lt;/h2&gt;

&lt;p&gt;A call center receives an average of 6 calls per hour.&lt;/p&gt;

&lt;p&gt;Then, the number of calls in 1 hour can be modeled by \(Y\sim\text{Poisson}(6)\), and the probability that there is no call in 10 minutes, i.e. 1/6 hour, is computed as follows:&lt;/p&gt;

\[P(Y=0)=e^{-6\times(1/6)}=e^{-1}\approx 0.368.\]

&lt;p&gt;Meanwhile, the average waiting time until the next call is:&lt;/p&gt;

\[\mathbb{E}[T]=\frac{1}{6}\text{ hours}=10\text{ minutes}.\]

&lt;h3 id=&quot;51-the-same-lambda-answering-two-different-questions&quot;&gt;5.1) The same \(\lambda\), answering two different questions&lt;/h3&gt;

&lt;p&gt;Still with \(\lambda = 6\) calls per hour:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;In 30 minutes, the expected number of calls is \(6 \times 0.5 = 3\), so we can ask “will there be overload?” using the Poisson.&lt;/li&gt;
  &lt;li&gt;In 5 minutes, the probability of at least one call is:&lt;/li&gt;
&lt;/ul&gt;

\[P(T \leq 5\text{ minutes}) = 1 - e^{-6\times(5/60)} = 1 - e^{-0.5} \approx 0.393.\]

&lt;p&gt;That is, in the first 5 minutes, the probability that the call center receives at least one call is only about 39.3%.&lt;/p&gt;

&lt;p&gt;The important point is: the Poisson helps answer the counting question over a time interval, while the Exponential helps answer the question of how long to wait until the next event. Both use exactly the same underlying rate \(\lambda\).&lt;/p&gt;

&lt;h2 id=&quot;6-modeling-warnings&quot;&gt;6) Modeling warnings&lt;/h2&gt;

&lt;p&gt;If count data has variance much larger than the mean (overdispersion), the Poisson is usually too “tight”. Then a Negative Binomial or a hierarchical model may be needed.&lt;/p&gt;

&lt;p&gt;If the event rate changes over time (peak/off-peak hours), the assumption of a constant \(\lambda\) is also no longer appropriate.&lt;/p&gt;

&lt;h2 id=&quot;7-the-bayesian-connection&quot;&gt;7) The Bayesian connection&lt;/h2&gt;

&lt;p&gt;In Bayes, a Gamma prior for \(\lambda\) combined with a Poisson likelihood gives a Gamma posterior. This is a very useful conjugate pair for event-count problems.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_02_03_normal_clt_intuition/&quot;&gt;0.4 Normal and CLT Intuition&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-server-errors-at-rate-lambda--2-per-hour&quot;&gt;Worked Numerical Example: Server Errors at Rate \(\lambda = 2\) per Hour&lt;/h3&gt;

&lt;p&gt;Suppose a microservice logs errors as a Poisson process with rate \(\lambda = 2\) errors/hour:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Probability of a completely clean hour (\(N = 0\)):&lt;/strong&gt;
\(P(N = 0) = \frac{2^0 e^{-2}}{0!} = e^{-2} \approx 0.1353 \quad (13.5\%).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Probability of at least 1 error in an hour (\(N \ge 1\)):&lt;/strong&gt;
\(P(N \ge 1) = 1 - P(N=0) = 1 - 0.1353 = 0.8647 \quad (86.5\%).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Probability of waiting more than 30 minutes (\(t = 0.5\) hr) for the next error:&lt;/strong&gt;
\(P(T &amp;gt; 0.5) = e^{-\lambda t} = e^{-2(0.5)} = e^{-1} \approx 0.3679 \quad (36.8\%).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check the duality:&lt;/strong&gt; Probability of 0 errors in 30 minutes (effective rate \(\lambda_{\text{half}} = 2 \times 0.5 = 1\)) is \(e^{-1} \approx 0.3679\)—identical to \(P(T &amp;gt; 0.5)\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-modeling-checks-before-choosing-poissonexponential&quot;&gt;Explanation: Four Modeling Checks Before Choosing Poisson/Exponential&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check \(\mathrm{Var}(N)\) vs. \(\mathbb{E}[N]\):&lt;/strong&gt; If your real-world click or error counts have sample variance \(3\times\) larger than the mean, Poisson will understate tail risk—upgrade to a &lt;strong&gt;Gamma–Poisson (Negative Binomial)&lt;/strong&gt; mixture.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scale \(\lambda\) proportionally to exposure time:&lt;/strong&gt; If rate is \(\lambda = 2\) per hour, over \(t = 3\) hours the count is \(\mathrm{Poisson}(6)\), never \(\mathrm{Poisson}(2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify whether memorylessness makes physical sense:&lt;/strong&gt; Lightbulbs and servers &lt;em&gt;age&lt;/em&gt; (hazard rate increases), so Weibull or Gamma waiting times beat Exponential for reliability modeling.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Spot the Bayesian kernel early:&lt;/strong&gt; Whenever you see \(\lambda^k e^{-t\lambda}\), think immediately of a Gamma posterior \(\mathrm{Gamma}(\alpha + k,\; \beta + t)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If errors arrive at \(\lambda = 2\) per hour and you have already waited 45 minutes with zero errors, what is the probability you will wait &lt;em&gt;at least another 30 minutes&lt;/em&gt; under the memoryless Exponential model?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jmqZG6roVqU&quot;&gt;An Introduction to the Poisson Distribution&lt;/a&gt; — jbstatistics, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch to grasp the Poisson as a model for counting events in a fixed interval, exactly the first half of the lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=n7K8s4vryCQ&quot;&gt;Understanding Exponential vs Poisson Distributions&lt;/a&gt; — Explained by Michael, English. Watch the comparison of waiting time versus counts, supporting the claim that the Exponential and Poisson are two faces of the same process.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=wtLQUjfomig&quot;&gt;The Exponential Distribution&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch the shape and parameter of the Exponential, used when the lesson moves from counting events to waiting times.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.2: Bernoulli and Binomial - From Binary Outcomes to the Number of Successes</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_02_01_bernoulli_binomial/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_02_01_bernoulli_binomial</id>
   <content type="html">&lt;p&gt;Every click-through rate, medical trial recovery, and A/B test conversion begins with the simplest possible random experiment: a single yes-or-no trial with success probability \(p\). Stack \(n\) independent copies of that trial together and count the successes, and you get the &lt;strong&gt;Binomial distribution&lt;/strong&gt;—the exact likelihood engine behind the most famous Bayesian update in history (the Beta–Binomial model!).&lt;/p&gt;

&lt;p&gt;This lesson builds fluent intuition for &lt;strong&gt;Bernoulli&lt;/strong&gt; and &lt;strong&gt;Binomial&lt;/strong&gt; models, distinguishes ordered sequences from unordered counts via \(\binom{n}{k}\), and previews how flipping the question from &lt;em&gt;“given \(p\), what is \(P(k)\)?”&lt;/em&gt; to &lt;em&gt;“given \(k\), what is plausible for \(p\)?”&lt;/em&gt; launches Bayesian inference.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-from-binary-trials-to-bayesian-likelihoods&quot;&gt;Key ideas: From Binary Trials to Bayesian Likelihoods&lt;/h2&gt;

&lt;p&gt;Four concepts turn coin-flip math into a real-world statistical workhorse:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bernoulli Trial (\(n=1\)):&lt;/strong&gt; Models a single binary outcome \(X \in \{0,1\}\) with mean \(p\) and variance \(p(1-p)\) (maximized at \(p=0.5\), where uncertainty is greatest).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Binomial Count (\(n\) i.i.d. trials):&lt;/strong&gt; Counts \(K = \sum_{i=1}^n X_i\) with PMF \(P(K=k\mid p) = \binom{n}{k} p^k (1-p)^{n-k}\), mean \(np\), and variance \(np(1-p)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Combinatorial Multiplicity \(\binom{n}{k}\):&lt;/strong&gt; Counts how many distinct sequences produce \(k\) successes. Crucially, \(\binom{n}{k}\) does &lt;strong&gt;not&lt;/strong&gt; depend on \(p\)—so in Bayesian updating it cancels out as a constant!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Likelihood View (Fixing \(k\), Varying \(p\)):&lt;/strong&gt; Holding observed data \((n, k)\) fixed and reading \(L(p) \propto p^k(1-p)^{n-k}\) as a function of \(p\) turns the Binomial PMF into a Bayesian likelihood ready to multiply by a Beta prior.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning objectives&lt;/h2&gt;

&lt;p&gt;After this lesson, you will clearly distinguish Bernoulli and Binomial problems, understand the data-generating relationship between them, and know how to read the parameters in practical language instead of just looking at formulas.&lt;/p&gt;

&lt;h2 id=&quot;1-the-story-of-binary-data-generation&quot;&gt;1) The story of binary data generation&lt;/h2&gt;

&lt;p&gt;Many data problems start from a binary question:&lt;/p&gt;

&lt;p&gt;For example, whether a user clicks or not, whether a patient responds to treatment or not, or whether a package is delivered on time or not.&lt;/p&gt;

&lt;p&gt;Each observation has only two states, so the basic random variable is Bernoulli.&lt;/p&gt;

\[X \sim \text{Bernoulli}(p), \quad P(X=1)=p,\; P(X=0)=1-p.\]

&lt;p&gt;Here \(p\) is the probability of success in a single trial.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/bernoulli_binary_outcomes.png&quot; alt=&quot;Bernoulli describes a single binary trial with two possible outcomes&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates that a Bernoulli describes a single binary trial with two possible outcomes. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-from-bernoulli-to-binomial&quot;&gt;2) From Bernoulli to Binomial&lt;/h2&gt;

&lt;p&gt;If we repeat the Bernoulli experiment \(n\) times independently with the same \(p\), the number of successes \(K\) follows a Binomial:&lt;/p&gt;

\[K \sim \text{Binomial}(n,p), \quad P(K=k)=\binom{n}{k}p^k(1-p)^{n-k}.\]

&lt;p&gt;This is an important step in modeling:&lt;/p&gt;

&lt;p&gt;A Bernoulli describes a single binary observation, while a Binomial describes the total number of successes after many trials of the same kind.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/chapter_img/chapter00/binomial_success_count_distribution.png&quot; alt=&quot;The Binomial counts the number of successes after many independent Bernoulli trials&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to read the figure: This figure illustrates that the Binomial counts the number of successes after many independent Bernoulli trials. Read the axis labels/legend first, then compare the main trend across the lines, bars or groups of points instead of looking only at individual points.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In this illustration, we are using the parameters \(n=12\) and \(p=0.35\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to read the chart &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;binomial_success_count_distribution.png&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The horizontal axis is the number of successes \(k\) (from \(0\) to \(n\)), the vertical axis is the probability \(P(K=k)\).&lt;/li&gt;
  &lt;li&gt;Each bar shows the chance of getting exactly \(k\) successes after \(n\) trials.&lt;/li&gt;
  &lt;li&gt;The peak of the distribution usually lies near \(k\approx np\), so as \(p\) increases the probability mass shifts to the right.&lt;/li&gt;
  &lt;li&gt;Intuitively, the chart immediately shows us “which number of successes is most likely” and “how spread out it is around the expected value”.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;3-the-normalizing-constant-in-bernoullibinomial&quot;&gt;3) The normalizing constant in Bernoulli/Binomial&lt;/h2&gt;

&lt;p&gt;For the Bernoulli, the PMF is usually written:&lt;/p&gt;

\[P(X=x)=p^x(1-p)^{1-x},
\quad x\in\{0,1\}.\]

&lt;p&gt;The validity condition of a discrete distribution is that the probabilities sum to 1:&lt;/p&gt;

\[\sum_{x\in\{0,1\}} p^x(1-p)^{1-x}
=(1-p)+p=1.\]

&lt;p&gt;For the Binomial:&lt;/p&gt;

\[P(K=k)=\binom{n}{k}p^k(1-p)^{n-k},\quad k=0,1,\dots,n.\]

&lt;p&gt;Here the binomial coefficient \(\binom{n}{k}\) is exactly the count of the ways to arrange \(k\) successes among \(n\) trials. Thanks to this coefficient, the total probability closes to exactly 1:&lt;/p&gt;

\[\sum_{k=0}^{n} \binom{n}{k}p^k(1-p)^{n-k}
=(p+1-p)^n=1.\]

&lt;p&gt;In short: for the Bernoulli/Binomial, the Binomial PMF is already “self-normalized”: no extra constant is needed outside the formula.&lt;/p&gt;

&lt;h2 id=&quot;4-the-meaning-of-the-parameters&quot;&gt;4) The meaning of the parameters&lt;/h2&gt;

&lt;p&gt;In this model, \(p\) expresses the “ease of success” of one trial, \(n\) gives the scale of the experiment, and \(k\) is the actual observed outcome after we have carried out those trials.&lt;/p&gt;

&lt;p&gt;Two useful quantities:&lt;/p&gt;

\[\mathbb{E}[K]=np, \qquad \mathrm{Var}(K)=np(1-p).\]

&lt;p&gt;So, the same mean \(np\) but a different \(p\) can give very different spread.&lt;/p&gt;

&lt;h2 id=&quot;5-a-short-practical-example&quot;&gt;5) A short practical example&lt;/h2&gt;

&lt;p&gt;Suppose an API has an error probability of \(p=0.05\) per request. In \(n=40\) independent requests, the number of failed requests \(K\) has a Binomial distribution.&lt;/p&gt;

&lt;p&gt;In this case, the expected number of errors is \(\mathbb{E}[K]=40\times 0.05=2\), and the probability that no error appears at all is computed as follows:&lt;/p&gt;

\[P(K=0)=(1-0.05)^{40}\approx 0.129.\]

&lt;p&gt;Interpretation: even though the error rate is only 5%, the chance that a batch of 40 requests has no errors at all is only about 12.9%.&lt;/p&gt;

&lt;h3 id=&quot;51-same-expectation-of-2-but-the-uncertainty-is-not-the-same&quot;&gt;5.1) Same expectation of 2, but the uncertainty is not the same&lt;/h3&gt;

&lt;p&gt;Suppose we compare the following two situations:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;A quiz with 4 questions, each correct with probability \(0.5\).&lt;/li&gt;
  &lt;li&gt;An email campaign with 20 customers, each responding with probability \(0.1\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both give an expected number of successes equal to 2:&lt;/p&gt;

\[4 \times 0.5 = 2, \qquad 20 \times 0.1 = 2.\]

&lt;p&gt;But the variance differs:&lt;/p&gt;

\[4 \times 0.5 \times 0.5 = 1, \qquad 20 \times 0.1 \times 0.9 = 1.8.\]

&lt;p&gt;Interpretation: even with the same “mean of 2 successes”, the email campaign fluctuates clearly more. So reading \(np\) alone is not enough; we also have to look at \(np(1-p)\) to understand whether the result is stable.&lt;/p&gt;

&lt;h2 id=&quot;6-common-modeling-mistakes&quot;&gt;6) Common modeling mistakes&lt;/h2&gt;

&lt;p&gt;The most common mistakes are using a Binomial when \(p\) actually changes over time but is still assumed fixed, assuming independence even though the data depends on groups or on visit sessions, and equating the “observed probability” with the “true probability” without considering uncertainty. In these situations, we need to extend the model to richer forms such as hierarchical models, mixture models, or logistic regression with covariates.&lt;/p&gt;

&lt;h2 id=&quot;7-the-bayesian-connection&quot;&gt;7) The Bayesian connection&lt;/h2&gt;

&lt;p&gt;In Bayes, we usually put a prior on \(p\) and then update with Binomial data. The most common conjugate pair is the Beta-Binomial (details in lesson 0.5).&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_02_02_poisson_exponential/&quot;&gt;0.3 Poisson and Exponential&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-comparing-two-hypotheses-for-7-conversions-in-10-visits&quot;&gt;Worked Numerical Example: Comparing Two Hypotheses for 7 Conversions in 10 Visits&lt;/h3&gt;

&lt;p&gt;Suppose a landing page gets \(k = 7\) signups out of \(n = 10\) independent visitors. First, compute the exact Binomial probability under two competing conversion rates—\(p = 0.5\) vs. \(p = 0.7\) (noting \(\binom{10}{7} = \frac{10\times 9\times 8}{3\times 2\times 1} = 120\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Candidate Rate \(p\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(p^7\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\((1-p)^3\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Exact PMF \(120\,p^7(1-p)^3\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Relative Likelihood&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(p = 0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.00781\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.1250\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.1172\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1.00\times\) (baseline)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(p = 0.7\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.08235\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.0270\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(0.2668\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(2.28\times\) more likely!&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Notice the Bayesian insight: the data (7 out of 10) is \(2.28\) times more probable under \(p=0.7\) than under \(p=0.5\), yet \(p=0.5\) still has a completely non-trivial likelihood (\(11.7\%\))—so with only 10 visits, we shouldn’t declare victory too soon!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-for-binomial-modeling-in-practice&quot;&gt;Explanation: Four Rules for Binomial Modeling in Practice&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Check all three Binomial assumptions:&lt;/strong&gt; Fixed \(n\), constant \(p\) across trials, and conditional independence. If one user clicks 10 times in a row, independence fails and variance explodes (&lt;em&gt;overdispersion&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Know why \(\binom{n}{k}\) vanishes in Bayes’ rule:&lt;/strong&gt; Because \(\binom{n}{k}\) is identical for every candidate \(p\), the likelihood ratio between \(p=0.7\) and \(p=0.5\) depends &lt;em&gt;only&lt;/em&gt; on \(p^k(1-p)^{n-k}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Standard error shrinks like \(1/\sqrt{n}\):&lt;/strong&gt; For the sample proportion \(\hat{p} = K/n\), \(\mathrm{SD}(\hat{p}) = \sqrt{p(1-p)/n}\)—bounded above by \(0.5/\sqrt{n}\) at \(p=0.5\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Watch the zero-success edge case:&lt;/strong&gt; Observing \(0\) conversions in \(5\) visits gives MLE \(\hat{p} = 0\) (claiming conversion is impossible!), whereas a Bayesian Beta prior smoothly keeps small positive rates plausible.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; For \(n = 10\) trials and \(p = 0.5\), what are the exact mean \(\mathbb{E}[K]\) and standard deviation \(\mathrm{SD}(K)\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Tc6g-Y-l0Rg&quot;&gt;Bernoulli and Binomial Random Variables&lt;/a&gt; — Steve Brunton, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch to separate a single binary trial from the number of successes over many trials, exactly the Bernoulli and Binomial focus of the lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=J8jNoF-K8E8&quot;&gt;The Binomial Distribution and Test, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch the example of counting successes and the combination formula, supporting the part that reads parameters in real-data language.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Binomial distributions&lt;/td&gt;
          &lt;td&gt;Probabilities of probabilities, part 1](https://www.youtube.com/watch?v=8idr1WZ1A7Q) — 3Blue1Brown, English. Watch to see the Binomial as the generative model of repeated binary data, a bridge to how Bayes uses this distribution in later lessons.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Lesson 0.1: Probability Foundations - The Language of Uncertainty</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_01_probability_basics/"/>
   <updated>2025-01-02T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_01_probability_basics</id>
   <content type="html">&lt;p&gt;Suppose a hospital screens 10,000 people for a rare condition that affects 1% of the population using a test with 99% sensitivity and 95% specificity. When a patient tests positive, most people—even experienced physicians—intuitively guess there is a 95% or 99% chance they have the disease. Yet the true probability is just &lt;strong&gt;16.7%&lt;/strong&gt;! That jarring gap between gut instinct and mathematical reality is why &lt;strong&gt;probability theory&lt;/strong&gt; is the indispensable foundation of Bayesian data analysis.&lt;/p&gt;

&lt;p&gt;This opening lesson builds the exact grammar of uncertainty—sample spaces, conditional probability, independence, and the law of total probability—so that when Bayes’ theorem arrives in Chapter 1, every piece feels like transparent arithmetic rather than magic.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-four-axiomatic-pillars-behind-bayesian-reasoning&quot;&gt;Key ideas: Four Axiomatic Pillars Behind Bayesian Reasoning&lt;/h2&gt;

&lt;p&gt;Every Bayesian calculation in this entire course is built from just four elementary probability rules:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kolmogorov Axioms &amp;amp; Normalization:&lt;/strong&gt; Probabilities lie in \([0,1]\), mutually exclusive events add, and the total probability of the entire sample space equals \(1\)—the exact constraint that defines the normalizing constant (evidence) in Bayes’ rule.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Conditional Probability &amp;amp; Product Rule:&lt;/strong&gt; Knowing event \(B\) occurred shrinks the universe from \(\Omega\) to \(B\), giving \(P(A\mid B) = \frac{P(A\cap B)}{P(B)}\) and the product rule \(P(A\cap B) = P(A\mid B)P(B)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Law of Total Probability (Marginalization):&lt;/strong&gt; Partitioning uncertainty across all mutually exclusive hypotheses \(H_1,\dots,H_k\) gives \(P(D) = \sum_i P(D\mid H_i)P(H_i)\)—the denominator of Bayes’ theorem!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Independence vs. Conditional Independence:&lt;/strong&gt; Two events are independent when \(P(A\mid B)=P(A)\). In Bayesian modeling, data points \(y_1,\dots,y_n\) are rarely marginally independent, yet they &lt;em&gt;are&lt;/em&gt; &lt;strong&gt;conditionally independent given the parameter \(\theta\)&lt;/strong&gt;, letting likelihoods factor cleanly into products.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;learning-objectives&quot;&gt;Learning Objectives&lt;/h2&gt;

&lt;p&gt;After completing this lesson, you will understand that probability is not just a collection of computational formulas, but a complete mathematical language for describing, quantifying, and reasoning about uncertainty. You will firmly grasp the basic concepts of sample spaces, events, and the rules of probability, and understand why these concepts are an indispensable foundation for Bayesian inference. More importantly, you will begin to see probability as a way of encoding beliefs and updating those beliefs when new information arrives.&lt;/p&gt;

&lt;h2 id=&quot;introduction-why-do-we-need-probability&quot;&gt;Introduction: Why Do We Need Probability?&lt;/h2&gt;

&lt;p&gt;In the real world, we rarely have perfect information. A doctor diagnoses a disease based on unclear symptoms. A scientist tries to infer natural laws from noisy data. An engineer designs a system that must work well even when environmental conditions change unpredictably. In all of these situations, uncertainty is not a nuisance to be eliminated, but a fundamental feature of the problem that needs to be modeled and managed in a principled way.&lt;/p&gt;

&lt;p&gt;Probability gives us the mathematical language to do this. It lets us &lt;strong&gt;quantify the degree of belief&lt;/strong&gt; in different propositions, combine information from many sources, and make rational decisions even when we cannot be certain about the outcome. &lt;strong&gt;In this course on Bayesian data analysis, probability is not only a computational tool but also the way we think about data, models, and inference.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before we can use probability for Bayesian inference, we need to understand its foundations well. This lesson will build the basic concepts carefully, not only so that you can compute probabilities, but also so that you understand the meaning of those numbers and how they connect to statistical inference.&lt;/p&gt;

&lt;h2 id=&quot;sample-spaces-and-events-describing-what-can-happen&quot;&gt;Sample Spaces and Events: Describing What Can Happen&lt;/h2&gt;

&lt;p&gt;Every probability analysis begins by clearly identifying what can happen. We call the set of all possible outcomes of an experiment or random process the &lt;strong&gt;sample space&lt;/strong&gt;, usually denoted \(\Omega\). Each element of the sample space represents a specific, complete, and distinguishable outcome.&lt;/p&gt;

&lt;p&gt;Consider a simple example: flipping a fair coin. The sample space here is \(\Omega = \{\text{Tails}, \text{Heads}\}\). Each time we flip, we observe one of these two outcomes, and no other outcome can occur. The simplicity of this example should not obscure its importance: identifying the sample space precisely is the first and most important step in every probability analysis.&lt;/p&gt;

&lt;p&gt;In many real situations, the sample space can be much more complicated. If we flip the coin twice, the sample space becomes \(\Omega = \{TT, TH, HT, HH\}\), where \(T\) is Tails and \(H\) is Heads. If we measure the height of a randomly chosen person, the sample space is the set of all possible positive values (in practice, limited by biological constraints), and this is a continuous space rather than a discrete one.&lt;/p&gt;

&lt;p&gt;Once we have identified the sample space, we can talk about &lt;strong&gt;events&lt;/strong&gt;. An event is a subset of the sample space, representing a set of outcomes that we care about. For example, in the experiment of flipping a coin twice, the event “at least one Tails” corresponds to the set \(\{TT, TH, HT\}\). The event “both flips are Tails” corresponds to the set \(\{TT\}\).&lt;/p&gt;

&lt;p&gt;Defining events as subsets of the sample space may seem abstract, but it allows us to use set theory to reason about probability. We can talk about the union of two events (at least one of the two occurs), the intersection of two events (both occur together), and the complement of an event (that event does not occur). These operations will correspond directly to the probability rules we will discuss next.&lt;/p&gt;

&lt;h2 id=&quot;defining-probability-from-frequency-to-belief&quot;&gt;Defining Probability: From Frequency to Belief&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;There are many ways to understand what probability is&lt;/strong&gt;, and how we understand it deeply affects how we use it. In this course, we will mainly work with the &lt;strong&gt;Bayesian view of probability&lt;/strong&gt;, but first let us look at the traditional &lt;strong&gt;frequentist view&lt;/strong&gt; to understand the difference.&lt;/p&gt;

&lt;p&gt;According to the frequentist view, the probability of an event is defined as the relative frequency with which that event occurs when we repeat the experiment infinitely many times. If we flip a fair coin many times, the proportion of Tails will approach \(0.5\) as the number of flips increases. &lt;strong&gt;This is an objective and easy-to-understand definition, but it has an important limitation: it only makes sense for events that can be repeated many times. We cannot talk about “the probability of rain tomorrow” or “the probability that a scientific hypothesis is true” in the frequentist sense, because these events cannot be repeated under identical conditions.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Bayesian view of probability&lt;/strong&gt; is broader and more flexible. In this view, probability is a measure of the &lt;strong&gt;degree of belief&lt;/strong&gt; or the &lt;strong&gt;plausibility&lt;/strong&gt; of a proposition, based on available information. A probability of \(0\) means we are completely certain that the proposition is false, a probability of \(1\) means we are completely certain that it is true, and values in between express different degrees of uncertainty. Importantly, &lt;strong&gt;Bayesian probability can change as we gather more information, and this is exactly the basis of Bayesian inference.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;However we understand probability, it must follow some basic mathematical rules to ensure consistency. These rules, called the probability axioms, are the foundation of all of probability theory.&lt;/p&gt;

&lt;h2 id=&quot;the-probability-axioms-the-rules-of-the-game&quot;&gt;The Probability Axioms: The Rules of the Game&lt;/h2&gt;

&lt;p&gt;For probability to be a useful mathematical tool, it must obey some basic rules. These rules, formalized by the Russian mathematician Andrey Kolmogorov in 1933, define what we can and cannot do with probability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Axiom 1: Non-negativity.&lt;/strong&gt; The probability of any event is non-negative. For every event \(A\), we have \(P(A) \geq 0\). This is intuitive: we cannot have a “negative probability” for an event. A probability of zero means the event definitely does not occur.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Axiom 2: Normalization.&lt;/strong&gt; The probability of the whole sample space is \(1\). In other words, \(P(\Omega) = 1\). This reflects the fact that one of the possible outcomes must occur. We are completely certain that &lt;em&gt;something&lt;/em&gt; will happen, even when we are not sure &lt;em&gt;what&lt;/em&gt; will happen.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Axiom 3: Additivity.&lt;/strong&gt; If two events \(A\) and \(B\) are &lt;strong&gt;mutually exclusive&lt;/strong&gt;, meaning they cannot occur together (\(A \cap B = \emptyset\)), then the probability of their union equals the sum of the individual probabilities: \(P(A \cup B) = P(A) + P(B)\). This extends to any finite or countable collection of mutually exclusive events.&lt;/p&gt;

&lt;p&gt;These three axioms may seem simple, but they have profound consequences. From them, we can derive all the other probability rules we will need. For example, we can prove that the probability of the complement event \(A^c\) (the event that \(A\) does not occur) is \(P(A^c) = 1 - P(A)\). To see this, note that \(A\) and \(A^c\) are mutually exclusive and their union is the whole sample space, so \(P(A) + P(A^c) = P(\Omega) = 1\).&lt;/p&gt;

&lt;p&gt;Another important consequence is the &lt;strong&gt;general addition rule&lt;/strong&gt; for any two events (not necessarily mutually exclusive):&lt;/p&gt;

\[P(A \cup B) = P(A) + P(B) - P(A \cap B)\]

&lt;p&gt;We must subtract \(P(A \cap B)\) because otherwise we would count the outcomes in both \(A\) and \(B\) twice. This formula is analogous to the inclusion-exclusion principle in set theory, and it illustrates the deep connection between probability and set theory.&lt;/p&gt;

&lt;h2 id=&quot;conditional-probability-updating-beliefs-with-new-information&quot;&gt;Conditional Probability: Updating Beliefs with New Information&lt;/h2&gt;

&lt;p&gt;One of the most important concepts in probability theory, and especially important for Bayesian inference, is &lt;strong&gt;conditional probability&lt;/strong&gt;. This is the probability of an event, given that we know another event has occurred.&lt;/p&gt;

&lt;p&gt;Suppose we are interested in the probability of event \(A\), but we know that event \(B\) has occurred. How does this information change our assessment of how likely \(A\) is? The conditional probability of \(A\) given \(B\), denoted \(P(A \mid B)\), is defined as:&lt;/p&gt;

\[P(A \mid B) = \frac{P(A \cap B)}{P(B)}\]

&lt;p&gt;provided \(P(B) &amp;gt; 0\).&lt;/p&gt;

&lt;p&gt;This definition has a clear intuition. When we know that \(B\) has occurred, the space of possible outcomes shrinks to only the outcomes in \(B\). In this shrunken space, the probability of \(A\) is proportional to the probability that both \(A\) and \(B\) occur, normalized by the probability of \(B\) to ensure that the total probability in the new space is still \(1\).&lt;/p&gt;

&lt;p&gt;Consider a concrete example. Suppose we flip a fair coin twice. The sample space is \(\{TT, TH, HT, HH\}\), and each outcome has probability \(1/4\). The probability of the event “both flips are Tails” (\(A = \{TT\}\)) is \(P(A) = 1/4\). But suppose we are told that “at least one Tails” (\(B = \{TT, TH, HT\}\)). With this information, the conditional probability of \(A\) given \(B\) is:&lt;/p&gt;

\[P(A \mid B) = \frac{P(A \cap B)}{P(B)} = \frac{P(\{TT\})}{P(\{TT, TH, HT\})} = \frac{1/4}{3/4} = \frac{1}{3}\]

&lt;p&gt;Notice that the probability increases from \(1/4\) to \(1/3\) when we learn additional information. This is a simple example of updating beliefs based on new evidence, a central idea in Bayesian inference.&lt;/p&gt;

&lt;h3 id=&quot;a-variant-that-is-easy-to-confuse&quot;&gt;A Variant That Is Easy to Confuse&lt;/h3&gt;

&lt;p&gt;Still with two coin flips, let us compare two different conditions:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;If we know &lt;strong&gt;at least one flip is Tails&lt;/strong&gt;, the probability that both flips are Tails is \(1/3\).&lt;/li&gt;
  &lt;li&gt;But if we know &lt;strong&gt;the first flip is Tails&lt;/strong&gt;, the probability that both flips are Tails is \(1/2\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The two problems sound quite similar, but the conditioning information is not the same, so the conditional probability also differs. This is a very important lesson: in probability, the meaning of “knowing additional information” depends entirely on which possibilities the conditioning event has removed from the sample space.&lt;/p&gt;

&lt;p&gt;From the definition of conditional probability, we can derive the &lt;strong&gt;multiplication rule&lt;/strong&gt;:&lt;/p&gt;

\[P(A \cap B) = P(A \mid B) \cdot P(B) = P(B \mid A) \cdot P(A)\]

&lt;p&gt;This rule gives us two different ways to compute the probability of the intersection of two events, and their equivalence will lead to one of the most important formulas in statistics: Bayes’ theorem.&lt;/p&gt;

&lt;h2 id=&quot;independence-when-information-does-not-change-beliefs&quot;&gt;Independence: When Information Does Not Change Beliefs&lt;/h2&gt;

&lt;p&gt;Two events \(A\) and \(B\) are called &lt;strong&gt;independent&lt;/strong&gt; if knowing that one occurs does not change the probability of the other. Formally, \(A\) and \(B\) are independent if and only if:&lt;/p&gt;

\[P(A \mid B) = P(A)\]

&lt;p&gt;or equivalently:&lt;/p&gt;

\[P(A \cap B) = P(A) \cdot P(B)\]

&lt;p&gt;Independence is a strong assumption and is often untrue in practice, but it significantly simplifies probability computations and is the foundation of many statistical models. For example, when we flip a coin many times, we usually assume the flips are independent of each other, meaning the outcome of one flip does not affect the probabilities of subsequent flips.&lt;/p&gt;

&lt;p&gt;However, in many real situations, events are not independent. If we draw two cards from a deck without replacement, the outcome of the second draw depends on the first. If we observe the temperature on two consecutive days, they tend to be correlated with each other. Recognizing and modeling these dependencies is an important part of Bayesian data analysis.&lt;/p&gt;

&lt;h2 id=&quot;conditional-independence-when-dependence-vanishes-once-the-latent-variable-is-known&quot;&gt;Conditional Independence: When Dependence Vanishes Once the Latent Variable Is Known&lt;/h2&gt;

&lt;p&gt;There is a more subtle situation than ordinary independence: two events may &lt;strong&gt;not be independent when viewed globally&lt;/strong&gt;, but become independent once we know an additional latent variable \(C\).&lt;/p&gt;

&lt;p&gt;We say \(A\) and \(B\) are &lt;strong&gt;conditionally independent given \(C\)&lt;/strong&gt; if:&lt;/p&gt;

\[P(A \cap B \mid C) = P(A \mid C)P(B \mid C).\]

&lt;p&gt;The intuition is this:&lt;/p&gt;

&lt;p&gt;When we do not know \(C\), we are mixing several different data-generating mechanisms into a single picture; once we know \(C\), we know exactly which mechanism we are in; and within each individual mechanism, \(A\) and \(B\) may no longer influence each other.&lt;/p&gt;

&lt;p&gt;For example, suppose we randomly choose one of two coins:&lt;/p&gt;

&lt;p&gt;The first coin is fair, while the second coin always lands heads.&lt;/p&gt;

&lt;p&gt;Then we flip the chosen coin twice. Let:&lt;/p&gt;

&lt;p&gt;Let \(C\) be the event “coin 1 was chosen”, \(A\) the event “the first flip lands heads”, and \(B\) the event “the second flip lands heads”.&lt;/p&gt;

&lt;p&gt;If we &lt;strong&gt;know in advance which coin was chosen&lt;/strong&gt;, the two flips are conditionally independent:&lt;/p&gt;

&lt;p&gt;Under the fair coin, each flip is independent with probability of heads equal to \(1/2\); under the always-heads coin, the two flips are still independent in the sense that both are certain to land heads.&lt;/p&gt;

&lt;p&gt;But if we &lt;strong&gt;do not know&lt;/strong&gt; which coin was chosen, then \(A\) and \(B\) are no longer independent in the ordinary sense. The reason is that the outcome of the first flip reveals information about which kind of coin we are holding, and that information changes our belief about the second flip.&lt;/p&gt;

&lt;p&gt;This is a very important idea in Bayes:&lt;/p&gt;

&lt;p&gt;Dependence does not always come from variables “directly affecting” each other; sometimes it appears simply because we do not yet know a latent variable that governs both at once.&lt;/p&gt;

&lt;p&gt;When you move on to mixture models, hierarchical models or causal graphs, you will meet this idea again many times.&lt;/p&gt;

&lt;h2 id=&quot;the-law-of-total-probability-divide-and-compute&quot;&gt;The Law of Total Probability: Divide and Compute&lt;/h2&gt;

&lt;p&gt;Sometimes, the easiest way to compute the probability of an event is to split it into simpler cases. The &lt;strong&gt;law of total probability&lt;/strong&gt; lets us do this systematically.&lt;/p&gt;

&lt;p&gt;Suppose we have a partition of the sample space into mutually exclusive events \(B_1, B_2, \ldots, B_n\) such that \(\bigcup_{i=1}^n B_i = \Omega\). This means every outcome belongs to exactly one of the \(B_i\). Then the probability of any event \(A\) can be computed by:&lt;/p&gt;

\[P(A) = \sum_{i=1}^n P(A \mid B_i) \cdot P(B_i)\]

&lt;p&gt;This formula says that to compute \(P(A)\), we can consider each case \(B_i\), compute the probability of \(A\) in that case (\(P(A \mid B_i)\)), multiply by the probability of that case (\(P(B_i)\)), and add everything up.&lt;/p&gt;

&lt;p&gt;This rule is especially useful in hierarchical models, where we have &lt;strong&gt;latent variables that are not directly observed&lt;/strong&gt;. In Bayesian inference, we often use this rule to “marginalize out” nuisance parameters, focusing on what we really want to infer.&lt;/p&gt;

&lt;h2 id=&quot;implications-for-bayesian-inference&quot;&gt;Implications for Bayesian Inference&lt;/h2&gt;

&lt;p&gt;All the concepts we have discussed in this lesson are not merely abstract theory. They are the foundation on which all of Bayesian data analysis is built.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Bayesian inference, we will use conditional probability to update beliefs about model parameters as we observe data. We will use the law of total probability to marginalize out nuisance parameters. We will use the probability axioms to ensure that our inferences are consistent and sensible.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;More importantly, we will apply the Bayesian view of probability as &lt;strong&gt;degree of belief&lt;/strong&gt;. This lets us talk about “the probability of a hypothesis” or “the probability of a parameter value”, concepts that have no meaning in frequentist statistics but are very natural and useful in Bayesian statistics.&lt;/p&gt;

&lt;p&gt;As you progress through this course, you will see that every Bayesian tool, from the simple Bayes’ theorem to complex hierarchical models, is built from the basic probability principles we have discussed here. Understanding these foundations deeply will help you not only apply Bayesian methods correctly, but also understand why they work and when they may fail.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-solving-the-rare-disease-screening-paradox-by-hand&quot;&gt;Worked Numerical Example: Solving the Rare-Disease Screening Paradox by Hand&lt;/h3&gt;

&lt;p&gt;Consider a population of \(10{,}000\) people with disease prevalence \(P(D) = 0.01\) (\(100\) sick, \(9{,}900\) healthy), test sensitivity \(P(+\mid D) = 0.99\), and false-positive rate \(P(+\mid 
eg D) = 0.05\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Group&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Population Count&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Positive Test (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+&lt;/code&gt;)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Negative Test (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-&lt;/code&gt;)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Has Disease (\(D\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(100\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(100 \times 0.99 = \mathbf{99}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;**Healthy ($$&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt; &lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt; &lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt; &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;eg D$$)**&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(9{,}900\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(9{,}900 \times 0.05 = \mathbf{495}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(9{,}405\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Total&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(10{,}000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;\(594\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(9{,}406\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Read the exact conditional probability straight off the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+&lt;/code&gt; column:&lt;/p&gt;

\[P(D \mid +) = \frac{99}{99 + 495} = \frac{99}{594} = \frac{1}{6} \approx \mathbf{16.67\%}!\]

&lt;p&gt;Even with a 99%-accurate test, five out of six positive results are false alarms because healthy people outnumber sick people 99-to-1!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-rules-to-never-misfire-on-conditional-probability&quot;&gt;Explanation: Four Rules to Never Misfire on Conditional Probability&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Never confuse \(P(A\mid B)\) with \(P(B\mid A)\):&lt;/strong&gt; Confusing \(P(+\mid D) = 99\%\) with \(P(D\mid +) = 16.7\%\) is the &lt;em&gt;base-rate fallacy&lt;/em&gt;—the #1 statistical error in medicine, law, and machine learning.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Always check the denominator (marginal evidence):&lt;/strong&gt; Conditioning replaces the whole sample space with the slice where the observed evidence holds (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;594&lt;/code&gt; positive tests, not &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10,000&lt;/code&gt; people).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Distinguish mutually exclusive from independent:&lt;/strong&gt; If \(A\) and \(B\) are mutually exclusive (and have positive probability), knowing \(A\) happened guarantees \(B\) did &lt;em&gt;not&lt;/em&gt;—making them maximally &lt;em&gt;dependent&lt;/em&gt;, not independent!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convert probabilities into natural counts of 10,000 when stuck:&lt;/strong&gt; A 2×2 frequency table turns abstract conditional formulas into effortless mental arithmetic.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; If the same patient takes a &lt;em&gt;second&lt;/em&gt;, conditionally independent test (same 99% sensitivity, 5% false-positive rate) and tests positive &lt;em&gt;again&lt;/em&gt;, does \(P(D \mid +, +)\) jump above 75%? &lt;em&gt;(Hint: update the prior from \(1\%\) to \(16.67\%\)!)&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=oI3hZJqXJuc&quot;&gt;The Main Ideas behind Probability Distributions&lt;/a&gt; — StatQuest with Josh Starmer, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch to read a distribution as a story about degrees of certainty, exactly the opening part where the lesson treats probability as the language of uncertainty.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=_IgyaD7vOOA&quot;&gt;Conditional Probabilities, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Watch the part on conditional probability, since that is the computation the lesson uses to go from the sample space to inference once new information is available.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Random variables&lt;/td&gt;
          &lt;td&gt;Probability and Statistics&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=3v9w79NhsfI) — Khan Academy, English. Watch how random variables are defined, supporting the part that distinguishes observed outcomes from still-unknown quantities.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;exercises&quot;&gt;Exercises&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Exercise 1: Basic Probability.&lt;/strong&gt; A box contains 5 red marbles, 3 blue marbles, and 2 yellow marbles. We draw one marble at random. (a) Determine the sample space. (b) Compute the probability of drawing a red marble. (c) Compute the probability of drawing a marble that is not yellow. Explain your reasoning in words, not just formulas.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 2: Conditional Probability.&lt;/strong&gt; In a class, 60% of students study Python, 40% study R, and 25% study both. (a) If a student is chosen at random and we know the student studies Python, what is the probability that the student also studies R? (b) Are the events “studies Python” and “studies R” independent? Explain using both computation and intuition.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 3: The Law of Total Probability.&lt;/strong&gt; A company manufactures products at three factories A, B, and C with production shares of 50%, 30%, and 20% respectively. The defect rates from each factory are 2%, 3%, and 5% respectively. (a) Compute the probability that a randomly chosen product is defective. (b) If a product is found to be defective, what is the probability it came from factory C? (Hint: Part (b) requires Bayes’ theorem, which we will study in the next lesson, but try to reason intuitively.)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 4: Simpson’s Paradox.&lt;/strong&gt; Consider two treatments A and B tested on two groups of patients: a mild-illness group and a severe-illness group. In the mild group, A succeeds 90/100 times and B succeeds 85/90 times. In the severe group, A succeeds 20/100 times and B succeeds 15/110 times. (a) In each group, which treatment has the higher success rate? (b) Compute the overall success rate of each treatment. (c) Explain why the result seems paradoxical. What does this teach us about the importance of considering latent variables?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercise 5: Reflections on Probability.&lt;/strong&gt; Write a short paragraph (200-300 words) explaining the difference between the frequentist view and the Bayesian view of probability. Give an example of a situation where the Bayesian view seems more natural, and explain why. Reflect on how the way we understand probability can affect how we design experiments and interpret results.&lt;/p&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;h3 id=&quot;primary-references&quot;&gt;Primary References:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., &amp;amp; Rubin, D. B. (2013).&lt;/strong&gt; &lt;em&gt;Bayesian Data Analysis&lt;/em&gt; (3rd Edition). CRC Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 1: Probability and inference&lt;/li&gt;
  &lt;li&gt;Appendix A: Standard probability distributions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kruschke, J. K. (2015).&lt;/strong&gt; &lt;em&gt;Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan&lt;/em&gt; (2nd Edition). Academic Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapter 4: What is This Stuff Called Probability?&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;supplementary-reading&quot;&gt;Supplementary Reading:&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jaynes, E. T. (2003).&lt;/strong&gt; &lt;em&gt;Probability Theory: The Logic of Science&lt;/em&gt;. Cambridge University Press.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chapters 1-2: Plausible reasoning and quantitative rules&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;Next lesson: &lt;a href=&quot;/contents/en/chapter00/00_02_01_bernoulli_binomial/&quot;&gt;0.2 Bernoulli and Binomial&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>author details</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/home/author-details/"/>
   <updated>2021-05-20T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/home/author-details</id>
   <content type="html">&lt;h1 id=&quot;about-the-authors&quot;&gt;About the Authors&lt;/h1&gt;

&lt;h2 id=&quot;lead-instructor&quot;&gt;Lead Instructor&lt;/h2&gt;

&lt;h3 id=&quot;your-name&quot;&gt;[Your Name]&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Position&lt;/strong&gt;: [Your Title]&lt;br /&gt;
&lt;strong&gt;Institution&lt;/strong&gt;: [Your Institution]&lt;br /&gt;
&lt;strong&gt;Email&lt;/strong&gt;: your.email@example.com&lt;br /&gt;
&lt;strong&gt;Website&lt;/strong&gt;: &lt;a href=&quot;https://your-website.com&quot;&gt;https://your-website.com&lt;/a&gt;&lt;br /&gt;
&lt;strong&gt;LinkedIn&lt;/strong&gt;: &lt;a href=&quot;https://linkedin.com/in/yourprofile&quot;&gt;Your LinkedIn Profile&lt;/a&gt;&lt;/p&gt;

&lt;h4 id=&quot;background&quot;&gt;Background&lt;/h4&gt;

&lt;p&gt;[Write a detailed bio about yourself, including:]&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Your educational background&lt;/li&gt;
  &lt;li&gt;Your professional experience&lt;/li&gt;
  &lt;li&gt;Your research interests&lt;/li&gt;
  &lt;li&gt;Your teaching philosophy&lt;/li&gt;
  &lt;li&gt;Publications or notable achievements&lt;/li&gt;
  &lt;li&gt;Why you created this course&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;research-interests&quot;&gt;Research Interests&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;[Research area 1]&lt;/li&gt;
  &lt;li&gt;[Research area 2]&lt;/li&gt;
  &lt;li&gt;[Research area 3]&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;co-authors--teaching-team&quot;&gt;Co-Authors / Teaching Team&lt;/h2&gt;

&lt;h3 id=&quot;co-author-name-1&quot;&gt;[Co-Author Name 1]&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Role&lt;/strong&gt;: [Teaching Assistant / Co-Instructor]&lt;br /&gt;
&lt;strong&gt;Email&lt;/strong&gt;: coauthor1@example.com&lt;/p&gt;

&lt;p&gt;Brief bio and contributions to the course.&lt;/p&gt;

&lt;h3 id=&quot;co-author-name-2&quot;&gt;[Co-Author Name 2]&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Role&lt;/strong&gt;: [Teaching Assistant / Co-Instructor]&lt;br /&gt;
&lt;strong&gt;Email&lt;/strong&gt;: coauthor2@example.com&lt;/p&gt;

&lt;p&gt;Brief bio and contributions to the course.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;course-development&quot;&gt;Course Development&lt;/h2&gt;

&lt;p&gt;This course was developed over [time period] with the goal of [course goals]. The materials have been refined through [number] iterations based on student feedback and evolving best practices in [field].&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;contact&quot;&gt;Contact&lt;/h2&gt;

&lt;p&gt;For questions about the course content, please contact:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;General inquiries&lt;/strong&gt;: your.email@example.com&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Technical issues&lt;/strong&gt;: Open an issue on &lt;a href=&quot;https://github.com/your-username/bayesian-statistics-self-learning&quot;&gt;GitHub&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Collaboration opportunities&lt;/strong&gt;: [Contact form or email]&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>reference</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/reference/26_reference/"/>
   <updated>2021-03-28T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/reference/26_reference</id>
   <content type="html">&lt;h1 id=&quot;references-and-resources&quot;&gt;References and Resources&lt;/h1&gt;

&lt;p&gt;This page contains references and resources for the course. Add your own references as needed.&lt;/p&gt;

&lt;h2 id=&quot;textbooks&quot;&gt;Textbooks&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Author, A. (Year). &lt;em&gt;&lt;a href=&quot;https://example.com&quot;&gt;Book Title&lt;/a&gt;&lt;/em&gt;. Publisher.&lt;/li&gt;
  &lt;li&gt;Author, B. (Year). &lt;em&gt;&lt;a href=&quot;https://example.com&quot;&gt;Another Book Title&lt;/a&gt;&lt;/em&gt;. Publisher.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;online-courses-and-lectures&quot;&gt;Online Courses and Lectures&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Instructor, C. (Year). &lt;em&gt;&lt;a href=&quot;https://example.com&quot;&gt;Course Title&lt;/a&gt;&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;University. &lt;em&gt;&lt;a href=&quot;https://example.com&quot;&gt;Lecture Series&lt;/a&gt;&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;papers-and-articles&quot;&gt;Papers and Articles&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Author, D. et al. (Year). &lt;em&gt;&lt;a href=&quot;https://example.com&quot;&gt;Paper Title&lt;/a&gt;&lt;/em&gt;. Journal Name, Vol. X, pp. XXX-XXX.&lt;/li&gt;
  &lt;li&gt;Author, E. (Year). &lt;em&gt;&lt;a href=&quot;https://example.com&quot;&gt;Article Title&lt;/a&gt;&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;online-resources&quot;&gt;Online Resources&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Wikipedia. &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Topic&quot;&gt;Topic Name&lt;/a&gt;&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Documentation. &lt;em&gt;&lt;a href=&quot;https://example.com&quot;&gt;Tool/Library Name&lt;/a&gt;&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;additional-materials&quot;&gt;Additional Materials&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Author, F. (Year). &lt;em&gt;&lt;a href=&quot;https://example.com&quot;&gt;Tutorial/Guide Title&lt;/a&gt;&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Organization. &lt;em&gt;&lt;a href=&quot;https://example.com&quot;&gt;Resource Name&lt;/a&gt;&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: Replace these placeholder references with actual references relevant to your course content.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>makers</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/home/makers/"/>
   <updated>2021-02-03T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/home/makers</id>
   <content type="html">&lt;h1 id=&quot;course-creators&quot;&gt;Course Creators&lt;/h1&gt;

&lt;h2 id=&quot;lead-instructor&quot;&gt;Lead Instructor&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;[Your Name]&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Position: [Your Title/Position]&lt;/li&gt;
  &lt;li&gt;Institution: [Your Institution]&lt;/li&gt;
  &lt;li&gt;Email: your.email@example.com&lt;/li&gt;
  &lt;li&gt;Website: &lt;a href=&quot;https://your-website.com&quot;&gt;Your Website&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;about-the-instructor&quot;&gt;About the Instructor&lt;/h3&gt;

&lt;p&gt;[Write a brief bio about yourself, including your background, expertise, teaching philosophy, and what motivated you to create this course. This helps students connect with you and understand your perspective.]&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;I am a [your title] with [X years] of experience in [your field]. My research interests include [topics], and I have published [number] papers in [areas]. I created this course to help students understand [subject] in a practical and accessible way.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;teaching-assistants&quot;&gt;Teaching Assistants&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;[TA Name 1]&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Role: [Specific responsibilities]&lt;/li&gt;
  &lt;li&gt;Email: ta1@example.com&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;[TA Name 2]&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Role: [Specific responsibilities]&lt;/li&gt;
  &lt;li&gt;Email: ta2@example.com&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;contributors&quot;&gt;Contributors&lt;/h2&gt;

&lt;p&gt;We welcome contributions from the community! See our &lt;a href=&quot;/AUTHORS.html&quot;&gt;Contributors page&lt;/a&gt; for a full list of people who have helped improve this course.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;acknowledgments&quot;&gt;Acknowledgments&lt;/h2&gt;

&lt;p&gt;This course was made possible with support from:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;[Institution/Organization Name]&lt;/li&gt;
  &lt;li&gt;[Funding Source, if applicable]&lt;/li&gt;
  &lt;li&gt;[Any other acknowledgments]&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Special thanks to all students who provided feedback and helped improve the course materials.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Conventions</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contribution/conventions/"/>
   <updated>2021-02-03T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contribution/conventions</id>
   <content type="html">&lt;h2 id=&quot;1-directory-convention&quot;&gt;1. Directory Convention&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;주요 컨텐츠는 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;contents/chapter&lt;/code&gt;로 시작하는 디렉토리에 포함되어 있습니다. 또한 컨텐츠에 필요한 이미지는 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;image&lt;/code&gt; 디렉토리에 들어 있습니다.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;contents/chapter&lt;/code&gt;의 내부 디렉토리는 다음과 같습니다.&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;contents
├── chapter01
│   ├── _posts
│   │   ├── 21-01-07-01_00_Introduction.md
│   │   ├── 21-01-07-01_01_optimization_problems.md
│   │   ├── 21-01-28-01_02_convex_optimization_problem.md
│   │   ├── 21-01-28-01_03_goals_and_topics.md
│   │   └── 21-01-28-01_04_brief_history_of_convex_optimization.md
│   ├── index.html
...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;Jekyll에서는 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;_posts&lt;/code&gt; 디렉토리 내에 있는 Markdown 또는 html 파일을 블로그의 Posting으로 인식합니다. 따라서 새로운 포스팅을 작성하고자 한다면 각 디렉토리의 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;_posts&lt;/code&gt;에 새로 파일을 추가하시면 됩니다.&lt;/li&gt;
  &lt;li&gt;Jekyll의 Posting 파일들은 모두 아래와 같은 Naming Convention을 따라야 합니다.
    &lt;ul&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;yy-mm-dd-new_posting_name.md&lt;/code&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chapter&lt;/code&gt;와 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;image&lt;/code&gt; 디렉토리 외의 내용들은 모두 Blog의 설정과 관련된 것들입니다. 안정적인 운영을 위해 설정과 관련된 부분들에 대해서는 직접 편집보다는 이슈로 작성해주시면 처리하겠습니다(관련 내용 수정 시 PR Merge가 어려울 수 있습니다).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;2-posting-convention&quot;&gt;2. Posting Convention&lt;/h2&gt;

&lt;h3 id=&quot;21-header-field&quot;&gt;2.1. Header Field&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;모든 Posting 파일들은 다음 예시와 같은 Header를 가지고 있어야 합니다.&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;---
layout: post
title: Quasi-Newton Methods
chapter: &quot;18&quot;
order: 1
owner: &quot;Kyeongmin Woo&quot;
---
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;layout&lt;/strong&gt;은 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;post&lt;/code&gt;여야 합니다.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;title&lt;/strong&gt;은 내용에 맞게 임의의 String으로 설정할 수 있습니다.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;chapter&lt;/strong&gt;는 상위 카테고리의 마지막 두 숫자를 String으로 표기합니다. 다만 한 자리수인 경우 “01”과 같이 0을 붙여줘야 합니다.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;order&lt;/strong&gt;는 해당 chapter 내에서의 정렬 순서를 의미합니다.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;owner&lt;/strong&gt;는 해당 post의 관리자를 의미합니다.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;22-latex&quot;&gt;2.2. Latex&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;수식은 Latex 문법에 따라 표기합니다.&lt;/li&gt;
  &lt;li&gt;$$ 와 같이 double dollar sign을 사용하여 수식임을 나타냅니다.&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$$\theta x_1 + (1-\theta)x_2 \in C$$
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;위 수식은 다음과 같이 표기됩니다.&lt;/p&gt;

\[\theta x_1 + (1-\theta)x_2 \in C\]

&lt;h3 id=&quot;23-image-convention&quot;&gt;2.3. Image Convention&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Posting 파일에서 이미지를 삽일할 때 아래의 Convention을 따라야합니다.&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;figure class=&quot;image&quot; style=&quot;align: center;&quot;&amp;gt;
&amp;lt;p align=&quot;center&quot;&amp;gt;
  &amp;lt;img src=&quot;{image_path}&quot; alt=&quot;{description of image}&quot; width=&quot;{scale_ratio}%&quot; height=&quot;{scale_ratio}%&quot;&amp;gt;
  &amp;lt;figcaption style=&quot;text-align: center;&quot;&amp;gt;{figcaption}&amp;lt;/figcaption&amp;gt;
&amp;lt;/p&amp;gt;
&amp;lt;/figure&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;figure class는 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;image&lt;/code&gt;여야합니다.&lt;/li&gt;
  &lt;li&gt;{}에 들어갈 내용을 적절히 넣어야합니다.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;24-hyperlink-convention&quot;&gt;2.4 Hyperlink Convention&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Blog 내의 Post에 대한 hyperlink는 jekyll multilang_post_url 사용합니다. 예시:&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[Your Post Title](#post-not-found)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;기타 외부 Url로의 hyperlink는 다음과 같이 작성할 수 있습니다.&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[External Link](&amp;lt;https://example.com&amp;gt;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;3-github-convnention&quot;&gt;3. GitHub Convnention&lt;/h2&gt;

&lt;p&gt;작성 내용에 질문이 있거나 수정 사항을 발견하신 경우 다음 두 방법 중 하나로 남겨주시면 됩니다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;댓글 작성하기&lt;/li&gt;
  &lt;li&gt;Repogitory에 이슈 생성하기&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;새로운 내용을 추가하거나 직접 편집하시고 싶으신 경우에는 새로운 Branch를 생성하여 먼저 수정하신 후 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Pull Request&lt;/code&gt;를 생성해주시면 됩니다. 신규 작성 및 기존 내용 수정은 누구나 가능합니다.&lt;/p&gt;

&lt;h3 id=&quot;31-repository-policy&quot;&gt;3.1. Repository Policy&lt;/h3&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;main&lt;/code&gt; 브랜치로 Merge 되기 위해서는 1명 이상의 Reviewer가 Approve 해야 합니다. CODEOWNERS 시스템이 도입되어 있어 각 Chapter 별 Reviewer가 자동으로 할당됩니다.&lt;/p&gt;

&lt;h3 id=&quot;32-branch-naming-convention&quot;&gt;3.2. Branch Naming Convention&lt;/h3&gt;

&lt;p&gt;브랜치 이름은 다음 컨벤션에 맞춰 생성해주시면 됩니다.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[feature|bugfix]/[chapter**|settings]-변경-사항
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Prefix는 feature와 bugfix 두 가지를 사용합니다. 각각의 사용 예시는 다음과 같습니다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;feature
    &lt;ul&gt;
      &lt;li&gt;Migration 작업&lt;/li&gt;
      &lt;li&gt;문장/수식/이미지 등이 달라지는 경우&lt;/li&gt;
      &lt;li&gt;새로운 내용이 추가되는 경우&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;bugfix
    &lt;ul&gt;
      &lt;li&gt;오타를 수정하는 경우&lt;/li&gt;
      &lt;li&gt;latex view가 깨져 수정하는 경우&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;구체적인 예시는 아래와 같습니다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;feature/chapter01-migration&lt;/code&gt;: chapter01 Migration&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;feature/chapter01-fix-formula&lt;/code&gt;: chapter01에서 수식 업데이트&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;feature/settings-update-branch-convention&lt;/code&gt;: Convention 업데이트&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bugfix/chapter01-fix-typo&lt;/code&gt;: chapter01에서 오타 수정&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>how to contribute</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/home/link_to_how_to_contribute/"/>
   <updated>2021-01-27T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/home/link_to_how_to_contribute</id>
   <content type="html">&lt;h1 id=&quot;how-to-contribute&quot;&gt;How to Contribute&lt;/h1&gt;

&lt;p&gt;We welcome contributions from the community! Whether you want to fix a typo, add an example, or contribute a whole new chapter, your help is appreciated.&lt;/p&gt;

&lt;h2 id=&quot;ways-to-contribute&quot;&gt;Ways to Contribute&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Fix errors&lt;/strong&gt;: Found a typo or mistake? Submit a fix!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Add examples&lt;/strong&gt;: Share practical examples or exercises&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Improve explanations&lt;/strong&gt;: Make concepts clearer&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Translate content&lt;/strong&gt;: Help make the course available in more languages&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Add resources&lt;/strong&gt;: Suggest additional reading materials or tools&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;getting-started&quot;&gt;Getting Started&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Fork the repository&lt;/strong&gt; on GitHub&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Clone your fork&lt;/strong&gt; to your local machine&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Create a new branch&lt;/strong&gt; for your changes&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Make your changes&lt;/strong&gt; following our style guide&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Test your changes&lt;/strong&gt; locally&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Submit a pull request&lt;/strong&gt; with a clear description&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;style-guidelines&quot;&gt;Style Guidelines&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Use clear, concise language&lt;/li&gt;
  &lt;li&gt;Follow the existing formatting conventions&lt;/li&gt;
  &lt;li&gt;Include examples where appropriate&lt;/li&gt;
  &lt;li&gt;Test all code snippets&lt;/li&gt;
  &lt;li&gt;Use proper LaTeX formatting for mathematical expressions&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;questions&quot;&gt;Questions?&lt;/h2&gt;

&lt;p&gt;If you have questions about contributing, please:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Check our &lt;a href=&quot;/contribution/how_to_contribute/&quot;&gt;Contributing Guide&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Open an issue on GitHub&lt;/li&gt;
  &lt;li&gt;Contact the course maintainers&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Thank you for helping improve this course!&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Initial Settings</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contribution/initial_settings/"/>
   <updated>2021-01-27T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contribution/initial_settings</id>
   <content type="html">&lt;p&gt;The contents of this repository are hosted as a &lt;a href=&quot;https://convex-optimization-for-all.github.io/&quot;&gt;Github Blog&lt;/a&gt; using Jekyll.
Therefore, to edit existing content or create new content, you must follow Jekyll’s directory structure and content writing conventions.
Additionally, you need to verify that changes are properly reflected in your local environment (your current computer) through a web browser.&lt;/p&gt;

&lt;p&gt;We have compiled environment setup instructions for those who are not familiar with GitHub or Jekyll.
If you have difficulties following the guide, please leave an &lt;a href=&quot;https://github.com/convex-optimization-for-all/convex-optimization-for-all.github.io/issues&quot;&gt;issue&lt;/a&gt; in the repository or contact us via the email below for assistance.&lt;/p&gt;

&lt;p&gt;(Kyeongmin Woo, wgm0601@gmail.com)&lt;/p&gt;

&lt;h2 id=&quot;1-git-installation&quot;&gt;1. Git Installation&lt;/h2&gt;

&lt;p&gt;All work management for this blog is performed through Git and GitHub. Please visit the website below to install Git.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://git-scm.com/downloads&quot;&gt;https://git-scm.com/downloads&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-downloading-the-repository&quot;&gt;2. Downloading the Repository&lt;/h2&gt;

&lt;p&gt;To modify the blog, enter the following command in the terminal to download the blog’s source code.&lt;/p&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;git clone https://github.com/convex-optimization-for-all/convex-optimization-for-all.github.io.git
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;3-local-hosting&quot;&gt;3. Local Hosting&lt;/h2&gt;

&lt;p&gt;Before applying changed or modified content to the blog, you must verify that the work has been performed as intended through local hosting.
If you merge work content that does not follow Jekyll’s required conventions into the repository, the blog hosted on the actual web may not function properly.
For local hosting setup, you can choose between two methods: using a virtual environment (Docker) (Option 1) or directly installing the Jekyll environment locally (Option 2).
After completing the local hosting setup and running the local server, you can check your blog content through the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;127.0.0.1:4000&lt;/code&gt; address in your web browser.&lt;/p&gt;

&lt;h3 id=&quot;3-1-option-1-docker-installation&quot;&gt;3-1. (Option 1) Docker Installation&lt;/h3&gt;

&lt;h3 id=&quot;a-docker-installation&quot;&gt;A. Docker Installation&lt;/h3&gt;

&lt;p&gt;Using Docker enables local hosting without direct environment installation on your local machine.
Please visit the website below to install Docker.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://docs.docker.com/get-docker/&quot;&gt;https://docs.docker.com/get-docker/&lt;/a&gt;&lt;/p&gt;

&lt;h3 id=&quot;b-local-hosting&quot;&gt;B. Local Hosting&lt;/h3&gt;

&lt;p&gt;Enter the following command in the terminal.&lt;/p&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nv&quot;&gt;$ &lt;/span&gt;docker-compose up
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;3-2-option-2-jekyll-environment-installation&quot;&gt;3-2. (Option 2) Jekyll Environment Installation&lt;/h3&gt;

&lt;h3 id=&quot;a-jekyll-and-ruby-package-installation&quot;&gt;A. Jekyll and Ruby Package Installation&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://jekyllrb.com/docs/installation/&quot;&gt;Installing Ruby&lt;/a&gt;: Jekyll is built with Ruby. Therefore, you need to install Ruby to use Jekyll.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://jekyllrb.com/docs/&quot;&gt;Installing Jekyll&lt;/a&gt;: Once Ruby is installed, enter the cloned repository and install Jekyll.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://jekyllrb.com/docs/&quot;&gt;Installing Bundle Gem&lt;/a&gt;: You need to additionally install Ruby packages required for hosting. Run the following command in the repository’s project directory.&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nv&quot;&gt;$ &lt;/span&gt;bundle &lt;span class=&quot;nb&quot;&gt;install&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;b-local-hosting-1&quot;&gt;B. Local Hosting&lt;/h3&gt;

&lt;p&gt;Enter the following command in the terminal.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ jekyll serve
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If hosting doesn’t work, you can also try the following command.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ bundle exec jekyll serve
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If both commands don’t work, the Jekyll environment has not been properly installed.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>How to Contribute</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contribution/how_to_contribute/"/>
   <updated>2021-01-27T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contribution/how_to_contribute</id>
   <content type="html">&lt;hr /&gt;

&lt;h2 id=&quot;1-컨텐츠를-직접-수정하는-방법&quot;&gt;1. 컨텐츠를 직접 수정하는 방법&lt;/h2&gt;

&lt;h3 id=&quot;1-우선-local의-repository-directory로-들어갑니다-local-repository가-없다면-initial-settings를-참고하시기-바랍니다&quot;&gt;(1) 우선 Local의 Repository Directory로 들어갑니다. Local Repository가 없다면 &lt;a href=&quot;https://convex-optimization-for-all.github.io/contribution/2021/01/27/initial_settings/&quot;&gt;Initial Settings&lt;/a&gt;를 참고하시기 바랍니다.&lt;/h3&gt;

&lt;h3 id=&quot;2--remote-저장소와의-정보를-동기화합니다&quot;&gt;(2)  Remote 저장소와의 정보를 동기화합니다.&lt;/h3&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nv&quot;&gt;$ &lt;/span&gt;git checkout main
&lt;span class=&quot;nv&quot;&gt;$ &lt;/span&gt;git pull &lt;span class=&quot;nt&quot;&gt;--all&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;3-수정-내용을-담는-새로운-브랜치를-생성합니다-브랜치-명은-prefix챕터명수정하는_이유로-하시면-됩니다branch-naming-convetion-예시는-아래와-같습니다&quot;&gt;(3) 수정 내용을 담는 새로운 브랜치를 생성합니다. 브랜치 명은 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[Prefix]/[챕터명]/[수정하는_이유]&lt;/code&gt;로 하시면 됩니다(&lt;a href=&quot;https://convex-optimization-for-all.github.io/contribution/2021/02/03/conventions/&quot;&gt;Branch Naming Convetion&lt;/a&gt;). 예시는 아래와 같습니다.&lt;/h3&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nv&quot;&gt;$ &lt;/span&gt;git checkout &lt;span class=&quot;nt&quot;&gt;-b&lt;/span&gt; bugfix/chapter01-fix-typo
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;4-파일을-편집합니다-생성-또는-수정하고자-하는-컨텐츠는-convention을-지켜-작성해야-합니다&quot;&gt;(4) 파일을 편집합니다. 생성 또는 수정하고자 하는 컨텐츠는 &lt;a href=&quot;https://convex-optimization-for-all.github.io/contribution/2021/02/03/conventions/&quot;&gt;Convention&lt;/a&gt;을 지켜 작성해야 합니다.&lt;/h3&gt;

&lt;h3 id=&quot;5-remote로-push합니다-예시는-아래와-같습니다&quot;&gt;(5) Remote로 Push합니다. 예시는 아래와 같습니다.&lt;/h3&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nv&quot;&gt;$ &lt;/span&gt;git push origin bugfix/chapter01-fix-typo
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;6-github에서-main-branch로의-pull-request를-생성합니다-pull-request-생성-방법은-아래-github-docs를-참고하시기-바랍니다&quot;&gt;(6) &lt;a href=&quot;https://github.com/convex-optimization-for-all/convex-optimization-for-all.github.io/pulls&quot;&gt;Github&lt;/a&gt;에서 main branch로의 Pull Request를 생성합니다. Pull Request 생성 방법은 아래 GitHub Docs를 참고하시기 바랍니다.&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request&quot;&gt;Creating a pull request&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-컨텐츠-수정을-요청하는-방법&quot;&gt;2. 컨텐츠 수정을 요청하는 방법&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Github Repository에 &lt;a href=&quot;https://github.com/convex-optimization-for-all/convex-optimization-for-all.github.io/issues&quot;&gt;Issue&lt;/a&gt;를 생성하실 수 있습니다.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;
</content>
 </entry>
 
 <entry>
   <title>introduction</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/home/introduction/"/>
   <updated>2021-01-20T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/home/introduction</id>
   <content type="html">&lt;h1 id=&quot;welcome-to-your-course-name&quot;&gt;Welcome to [Your Course Name]&lt;/h1&gt;

&lt;p&gt;This course provides comprehensive coverage of [your subject area]. Whether you’re a beginner or looking to deepen your knowledge, this course will guide you through the essential concepts and practical applications.&lt;/p&gt;

&lt;h2 id=&quot;what-youll-learn&quot;&gt;What You’ll Learn&lt;/h2&gt;

&lt;p&gt;Throughout this course, you will:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Gain a solid understanding of fundamental concepts in [your subject]&lt;/li&gt;
  &lt;li&gt;Learn practical techniques and methodologies&lt;/li&gt;
  &lt;li&gt;Apply theoretical knowledge to real-world problems&lt;/li&gt;
  &lt;li&gt;Develop critical thinking and problem-solving skills&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;course-structure&quot;&gt;Course Structure&lt;/h2&gt;

&lt;p&gt;The course is organized into chapters, each focusing on a specific topic. You can navigate through the content using the sidebar menu. Each chapter includes:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Theoretical explanations&lt;/strong&gt; with clear examples&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mathematical formulations&lt;/strong&gt; (where applicable)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Practical exercises&lt;/strong&gt; to reinforce learning&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Real-world applications&lt;/strong&gt; and case studies&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;To get the most out of this course, you should have:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Basic knowledge of [prerequisite 1]&lt;/li&gt;
  &lt;li&gt;Familiarity with [prerequisite 2]&lt;/li&gt;
  &lt;li&gt;[Any other prerequisites]&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;how-to-use-this-course&quot;&gt;How to Use This Course&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Start with Chapter 0 for an overview&lt;/li&gt;
  &lt;li&gt;Progress through chapters sequentially or jump to topics of interest&lt;/li&gt;
  &lt;li&gt;Complete exercises to test your understanding&lt;/li&gt;
  &lt;li&gt;Refer to the reference materials for deeper exploration&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;support-and-feedback&quot;&gt;Support and Feedback&lt;/h2&gt;

&lt;p&gt;If you have questions or feedback, please:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Open an issue on our &lt;a href=&quot;https://github.com/your-username/bayesian-statistics-self-learning&quot;&gt;GitHub repository&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Contact the instructor (see Authors page)&lt;/li&gt;
  &lt;li&gt;Join our community discussions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s begin your learning journey!&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>contents</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/home/contents/"/>
   <updated>2021-01-20T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/home/contents</id>
   <content type="html">&lt;p&gt;A comprehensive introduction to [your course subject], covering fundamental concepts, practical applications, and advanced topics.&lt;/p&gt;

&lt;h1 id=&quot;course-objectives&quot;&gt;Course Objectives&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Provide students with a solid foundation in [subject area] to support their learning and professional development.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Enable students to understand key concepts and apply them to solve real-world problems.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Develop analytical and critical thinking skills through hands-on exercises and projects.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Prepare students for advanced study or professional work in [related field].&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;course-outline&quot;&gt;Course Outline&lt;/h2&gt;

&lt;p&gt;The course is divided into the following chapters:&lt;/p&gt;

&lt;h3 id=&quot;chapter-0-introduction&quot;&gt;Chapter 0: Introduction&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Overview of the course&lt;/li&gt;
  &lt;li&gt;Fundamental concepts&lt;/li&gt;
  &lt;li&gt;Course structure and expectations&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;chapter-1-topic-1&quot;&gt;Chapter 1: [Topic 1]&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Subtopic 1.1&lt;/li&gt;
  &lt;li&gt;Subtopic 1.2&lt;/li&gt;
  &lt;li&gt;Practical applications&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;chapter-2-topic-2&quot;&gt;Chapter 2: [Topic 2]&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Subtopic 2.1&lt;/li&gt;
  &lt;li&gt;Subtopic 2.2&lt;/li&gt;
  &lt;li&gt;Case studies&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;chapter-3-topic-3&quot;&gt;Chapter 3: [Topic 3]&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Advanced concepts&lt;/li&gt;
  &lt;li&gt;Integration with previous topics&lt;/li&gt;
  &lt;li&gt;Real-world examples&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Add more chapters as needed for your course&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;main-textbooks&quot;&gt;Main Textbooks&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;[Author Name], [Book Title], [Publisher], [Year].&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;[Author Name], [Book Title], [Publisher], [Year].&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;[Author Name], [Book Title], [Publisher], [Year].&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;[Author Name], [Book Title], [Publisher], [Year].&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;[Author Name], [Book Title], [Publisher], [Year].&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;additional-resources&quot;&gt;Additional Resources&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Online tutorials and documentation&lt;/li&gt;
  &lt;li&gt;Video lectures (if available)&lt;/li&gt;
  &lt;li&gt;Practice problems and solutions&lt;/li&gt;
  &lt;li&gt;Community forums and discussion groups&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01-02 Derivatives and Multivariable Calculus</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_01_02_Derivatives_and_Multivariable_Calculus/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_01_02_Derivatives_and_Multivariable_Calculus</id>
   <content type="html">&lt;p&gt;This lesson covers derivatives and essential multivariable calculus concepts that form the foundation for optimization theory and algorithms.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;When Hamiltonian Monte Carlo (HMC / NUTS) explores a 50-dimensional Bayesian posterior in Stan or PyMC, how does it know which direction leads uphill toward higher probability without blindly stumbling in 50 dimensions? It follows the &lt;strong&gt;gradient vector \(\nabla_\theta \log p(\theta\mid y)\)&lt;/strong&gt;—and uses the &lt;strong&gt;multivariable chain rule&lt;/strong&gt; (reverse-mode automatic differentiation) to compute all 50 partial derivatives in a single backward pass!&lt;/p&gt;

&lt;p&gt;This mathematical reference sharpens the exact multivariable calculus tools that power modern Bayesian optimization and sampling: partial derivatives, gradients, Hessians, and the multivariable chain rule.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-multivariable-calculus-inside-modern-bayesian-engines&quot;&gt;Key ideas: Multivariable Calculus Inside Modern Bayesian Engines&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Vector (\(\nabla f\)):&lt;/strong&gt; Points in the direction of steepest ascent of the log-posterior; setting \(\nabla_\theta \log p(\theta\mid y) = \mathbf{0}\) locates the MAP mode.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hessian Matrix (\(\mathbf{H}\)):&lt;/strong&gt; The matrix of second partial derivatives measures local curvature—its negative inverse \((-\mathbf{H})^{-1}\) at the mode gives the &lt;strong&gt;Laplace covariance matrix&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multivariable Chain Rule &amp;amp; Reverse-Mode Autodiff:&lt;/strong&gt; Composing priors, link functions (logit/exp), and likelihoods creates a computational graph; the chain rule propagates sensitivities backward in \(O(1)\) passes regardless of parameter count.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Jacobian Determinants for Constrained Parameters:&lt;/strong&gt; Transforming \(\sigma &amp;gt; 0\) via \(\sigma = e^\phi\) changes volume elements by \(\lvert \frac{d\sigma}{d\phi}\rvert = e^\phi\)—required so HMC samples the true target posterior!&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;derivatives-and-rate-of-change&quot;&gt;Derivatives and Rate of Change&lt;/h2&gt;

&lt;p&gt;The derivative of a single variable function represents its instantaneous rate of change, which is fundamental to understanding how functions behave locally.&lt;/p&gt;

&lt;h3 id=&quot;basic-derivative-concepts&quot;&gt;Basic Derivative Concepts&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Slope between two points:&lt;/strong&gt;&lt;/p&gt;

\[\text{Slope} = \frac{y_2 - y_1}{x_2 - x_1}\]

&lt;p&gt;&lt;strong&gt;Derivative (instantaneous rate of change):&lt;/strong&gt;&lt;/p&gt;

\[f&apos;(x_0) = \lim_{x_1 \to x_0} \frac{f(x_1) - f(x_0)}{x_1 - x_0} = \lim_{\Delta x \to 0} \frac{f(x_0 + \Delta x) - f(x_0)}{\Delta x}\]

&lt;p&gt;The derivative tells us how quickly the function is changing at any given point, which is essential for finding optimal points where the rate of change is zero.&lt;/p&gt;

&lt;h3 id=&quot;level-curves-of-functions&quot;&gt;Level Curves of Functions&lt;/h3&gt;

&lt;p&gt;Level curves are a fundamental concept in multivariable calculus used to visualize functions of two variables, typically denoted as \(f(x, y)\). They provide a way to represent a 3D surface in a 2D plane.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;level curve&lt;/strong&gt; of a function \(f(x, y)\) is the set of all points \((x, y)\) in the domain of \(f\) where the function takes a constant value:&lt;/p&gt;

\[f(x, y) = c\]

&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;For \(f(x, y) = x^2 + y^2\), the level curves are circles: \(x^2 + y^2 = c\)&lt;/li&gt;
  &lt;li&gt;For \(f(x, y) = x + y\), the level curves are parallel lines: \(x + y = c\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Level curves help us understand:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;The topography of the function&lt;/li&gt;
  &lt;li&gt;Directions of steepest ascent and descent&lt;/li&gt;
  &lt;li&gt;Locations of potential optima&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;multivariable-calculus-key-concepts&quot;&gt;Multivariable Calculus Key Concepts&lt;/h2&gt;

&lt;h3 id=&quot;partial-derivatives&quot;&gt;Partial Derivatives&lt;/h3&gt;

&lt;p&gt;For a function \(f(x_1, x_2, \ldots, x_n)\), the &lt;strong&gt;partial derivative&lt;/strong&gt; with respect to \(x_i\) is:&lt;/p&gt;

\[\frac{\partial f}{\partial x_i} = \lim_{h \to 0} \frac{f(x_1, \ldots, x_i + h, \ldots, x_n) - f(x_1, \ldots, x_i, \ldots, x_n)}{h}\]

&lt;p&gt;This measures how \(f\) changes when only \(x_i\) varies while all other variables remain fixed.&lt;/p&gt;

&lt;h3 id=&quot;gradient-vector&quot;&gt;Gradient Vector&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;gradient&lt;/strong&gt; is a vector composed of all partial derivatives:&lt;/p&gt;

\[\nabla f(\mathbf{x}) = \begin{pmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_n} \end{pmatrix}\]

&lt;p&gt;The gradient points in the direction of steepest increase of the function and is perpendicular to level curves.&lt;/p&gt;

&lt;h3 id=&quot;hessian-matrix&quot;&gt;Hessian Matrix&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;Hessian matrix&lt;/strong&gt; contains all second-order partial derivatives:&lt;/p&gt;

\[\nabla^2 f(\mathbf{x}) = \mathbf{H} = \begin{pmatrix} 
\frac{\partial^2 f}{\partial x_1^2} &amp;amp; \frac{\partial^2 f}{\partial x_1 \partial x_2} &amp;amp; \cdots &amp;amp; \frac{\partial^2 f}{\partial x_1 \partial x_n} \\
\frac{\partial^2 f}{\partial x_2 \partial x_1} &amp;amp; \frac{\partial^2 f}{\partial x_2^2} &amp;amp; \cdots &amp;amp; \frac{\partial^2 f}{\partial x_2 \partial x_n} \\
\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\
\frac{\partial^2 f}{\partial x_n \partial x_1} &amp;amp; \frac{\partial^2 f}{\partial x_n \partial x_2} &amp;amp; \cdots &amp;amp; \frac{\partial^2 f}{\partial x_n^2}
\end{pmatrix}\]

&lt;p&gt;The Hessian provides information about the curvature of the function and is crucial for:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Determining the nature of critical points (minimum, maximum, or saddle point)&lt;/li&gt;
  &lt;li&gt;Second-order optimization methods like Newton’s method&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;chain-rule-for-multivariable-functions&quot;&gt;Chain Rule for Multivariable Functions&lt;/h2&gt;

&lt;p&gt;The chain rule is fundamental for computing derivatives of composite functions, which frequently appear in optimization problems.&lt;/p&gt;

&lt;h3 id=&quot;basic-chain-rule&quot;&gt;Basic Chain Rule&lt;/h3&gt;

&lt;p&gt;For a function \(z = f(x, y)\) where \(x = g(t)\) and \(y = h(t)\):&lt;/p&gt;

\[\frac{dz}{dt} = \frac{\partial f}{\partial x} \frac{dx}{dt} + \frac{\partial f}{\partial y} \frac{dy}{dt}\]

&lt;h3 id=&quot;general-chain-rule&quot;&gt;General Chain Rule&lt;/h3&gt;

&lt;p&gt;For \(z = f(x_1, x_2, \ldots, x_n)\) where each \(x_i = x_i(t_1, t_2, \ldots, t_m)\):&lt;/p&gt;

\[\frac{\partial z}{\partial t_j} = \sum_{i=1}^{n} \frac{\partial f}{\partial x_i} \frac{\partial x_i}{\partial t_j}\]

&lt;h3 id=&quot;applications-in-optimization&quot;&gt;Applications in Optimization&lt;/h3&gt;

&lt;p&gt;The chain rule is essential for:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Computation&lt;/strong&gt;: Computing gradients of composite objective functions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Constraint Handling&lt;/strong&gt;: Dealing with constraints that are functions of other variables&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Algorithm Implementation&lt;/strong&gt;: Backpropagation in neural networks and automatic differentiation&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sensitivity Analysis&lt;/strong&gt;: Understanding how changes in parameters affect optimal solutions&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;example-optimization-with-constraints&quot;&gt;Example: Optimization with Constraints&lt;/h3&gt;

&lt;p&gt;Consider minimizing \(f(x, y) = x^2 + y^2\) subject to \(g(x, y) = x + y - 1 = 0\).&lt;/p&gt;

&lt;p&gt;Using the constraint to eliminate one variable: \(y = 1 - x\), so we minimize:
\(h(x) = f(x, 1-x) = x^2 + (1-x)^2\)&lt;/p&gt;

&lt;p&gt;Using the chain rule:
\(h&apos;(x) = \frac{\partial f}{\partial x} \cdot 1 + \frac{\partial f}{\partial y} \cdot \frac{d(1-x)}{dx} = 2x + 2(1-x)(-1) = 4x - 2\)&lt;/p&gt;

&lt;p&gt;Setting \(h&apos;(x) = 0\) gives \(x = 1/2\), so the optimal point is \((1/2, 1/2)\).&lt;/p&gt;

&lt;p&gt;This demonstrates how multivariable calculus concepts work together to solve optimization problems systematically.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-computing-gradient-and-hessian-of-a-2d-log-posterior-by-hand&quot;&gt;Worked Numerical Example: Computing Gradient and Hessian of a 2D Log-Posterior by Hand&lt;/h3&gt;

&lt;p&gt;Consider a 2-parameter Gaussian log-posterior \(g(\mu, \beta) = -\frac{1}{2}\!\left(2(\mu - 1)^2 + 4(\beta - 3)^2 + 2(\mu - 1)(\beta - 3)\right)\):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Partial derivatives (Gradient):&lt;/strong&gt;
\(\frac{\partial g}{\partial \mu} = -2(\mu - 1) - (\beta - 3), \qquad \frac{\partial g}{\partial \beta} = -4(\beta - 3) - (\mu - 1).\)
At \((\mu, \beta) = (0, 3)\), \(\nabla g = (+2, +1)^T\)—pointing straight uphill toward the mode \((1, 3)\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Negative Hessian (Posterior Precision Matrix):&lt;/strong&gt;
\(-\mathbf{H} = \begin{pmatrix} 2 &amp;amp; 1 \\ 1 &amp;amp; 4 \end{pmatrix} \implies \Sigma = (-\mathbf{H})^{-1} = \frac{1}{7}\begin{pmatrix} 4 &amp;amp; -1 \\ -1 &amp;amp; 2 \end{pmatrix}.\)
The off-diagonal \(+1\) in \(-\mathbf{H}\) immediately tells you \(\mu\) and \(\beta\) are negatively correlated (\(\mathrm{Cov} = -1/7\))!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;explanation-four-rules-for-multivariable-calculus-in-bayes&quot;&gt;Explanation: Four Rules for Multivariable Calculus in Bayes&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Always check the sign of the Hessian at a mode:&lt;/strong&gt; A maximum of \(\log p\) must have a &lt;em&gt;negative-definite&lt;/em&gt; Hessian (so \(-\mathbf{H}\) is positive-definite).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify your analytical gradient with finite differences:&lt;/strong&gt; Checking \(\frac{g(\theta+\epsilon)-g(\theta-\epsilon)}{2\epsilon}\) against your coded gradient catches 99% of chain-rule bugs in 5 seconds.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Never forget the Jacobian when reparameterizing:&lt;/strong&gt; Sampling \(\log \sigma\) without adding &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+\log\sigma&lt;/code&gt; to the log-posterior silently changes your prior!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Centering predictors makes the Hessian nearly diagonal:&lt;/strong&gt; Smaller off-diagonal Hessian entries mean faster optimization and faster HMC mixing.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; For \(g(\mu, \beta)\) above, verify that \(\nabla g = (0, 0)^T\) at \((\mu, \beta) = (1, 3)\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[The paradox of the derivative&lt;/td&gt;
          &lt;td&gt;Chapter 2, Essence of calculus](https://www.youtube.com/watch?v=9vKqVkMQHKk) — 3Blue1Brown, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch the derivative as a local linear approximation, the rate-of-change idea in the first section of the lesson.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=AXqhWeUEtQU&quot;&gt;Partial derivatives, introduction&lt;/a&gt; — Khan Academy, English. Watch a partial derivative hold every variable but one fixed, supporting the multivariable section.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NO3AqAaAE6o&quot;&gt;Multivariable chain rule&lt;/a&gt; — Khan Academy, English. Watch the multivariable chain rule, the last section of the lesson on composed functions of several inputs.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01-01 Continuity and Uniform Continuity</title>
   <link href="https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_01_01_Continuity_and_Uniform_Continuity/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://bayesian-statistics-self-learning.pages.dev/contents/en/chapter00/00_01_01_Continuity_and_Uniform_Continuity</id>
   <content type="html">&lt;p&gt;This lesson introduces the fundamental concepts of continuity and uniform continuity, which are essential for understanding the behavior of functions in optimization.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;When you approximate a continuous Bayesian posterior integral \(\int_0^1 p(\theta\mid y)\,d\theta\) on a finite grid of step size \(\Delta\theta = 0.01\), what mathematical guarantee ensures that making the grid finer actually converges to the exact integral everywhere at once? The answer is &lt;strong&gt;uniform continuity&lt;/strong&gt;—the stronger cousin of ordinary continuity where a single step size \(\delta\) controls the function’s wobble simultaneously across the &lt;em&gt;entire&lt;/em&gt; domain!&lt;/p&gt;

&lt;p&gt;This mathematical reference sharpens the distinction between &lt;strong&gt;pointwise continuity&lt;/strong&gt; and &lt;strong&gt;uniform continuity&lt;/strong&gt;, highlights the &lt;strong&gt;Heine–Cantor theorem&lt;/strong&gt; (every continuous function on a closed bounded interval \([a,b]\) is automatically uniformly continuous!), and shows why steep singularities on unbounded domains break naive grid approximations.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-ideas-continuity-compactness-and-numerical-integration&quot;&gt;Key ideas: Continuity, Compactness, and Numerical Integration&lt;/h2&gt;

&lt;p&gt;Four analysis concepts connect real analysis directly to Bayesian grid approximation and density theory:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Pointwise Continuity:&lt;/strong&gt; At a &lt;em&gt;fixed&lt;/em&gt; point \(x_0\), you can keep \(\lvert f(x)-f(x_0)
vert &amp;lt; \varepsilon\) by choosing \(\delta(\varepsilon, x_0)\)—allowing \(\delta\) to shrink arbitrarily tiny in steeper regions of the graph.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Uniform Continuity:&lt;/strong&gt; One single \(\delta(\varepsilon)\) works for &lt;strong&gt;every&lt;/strong&gt; pair \(x, y\) across the entire domain simultaneously—guaranteeing controlled variation everywhere.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Heine–Cantor Theorem:&lt;/strong&gt; Any continuous function on a compact (closed and bounded) interval \([a,b]\) is automatically uniformly continuous—explaining why smooth posteriors on \([0,1]\) (like \(\mathrm{Beta}(\alpha,\beta)\) with \(\alpha,\beta \ge 1\)) integrate cleanly on uniform grids!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Failure Modes on Open/Unbounded Domains:&lt;/strong&gt; Functions like \(1/x\) on \((0,1]\) (blowing up near 0, like \(\mathrm{Beta}(0.5, 0.5)\)!) or \(x^2\) on \((0,\infty)\) are continuous everywhere yet &lt;strong&gt;not&lt;/strong&gt; uniformly continuous—requiring adaptive quadrature or log-transformations.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;continuity-and-uniform-continuity&quot;&gt;Continuity and Uniform Continuity&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Continuity&lt;/strong&gt; and &lt;strong&gt;Uniform Continuity&lt;/strong&gt; are fundamental concepts that describe the behavior of functions, particularly concerning their “smoothness” or “predictability.” While closely related, they capture distinct properties, with uniform continuity being a stronger condition than mere continuity.&lt;/p&gt;

&lt;h3 id=&quot;definition-of-continuity&quot;&gt;Definition of Continuity&lt;/h3&gt;

&lt;p&gt;A function \(f: A \to \mathbb{R}\) is said to be &lt;strong&gt;continuous at a point&lt;/strong&gt; \(c \in A\) if, for every positive real number \(\varepsilon &amp;gt; 0\), there exists a positive real number \(\delta &amp;gt; 0\) such that for all \(x \in A\), if&lt;/p&gt;

\[\lvert x - c \rvert &amp;lt; \delta\]

&lt;p&gt;then&lt;/p&gt;

\[\lvert f(x) - f(c) \rvert &amp;lt; \varepsilon\]

&lt;p&gt;Intuitively, it means that for any desired level of precision \(\varepsilon\) in the output \(f(x)\), we can find a sufficiently small interval around \(c\) (of width \(2\delta\)) such that all \(x\) values within this interval map to \(f(x)\) values within an \(\varepsilon\)-interval around \(f(c)\). The crucial aspect here is that the choice of \(\delta\) generally depends not only on \(\varepsilon\) but also on the specific point \(c\).&lt;/p&gt;

&lt;p&gt;A function is &lt;strong&gt;continuous on a set&lt;/strong&gt; \(A\) if it is continuous at every point \(c \in A\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Examples of continuous functions&lt;/strong&gt; include all polynomials (e.g., \(f(x) = x^2 + 3x - 1\)), trigonometric functions like \(\sin(x)\) and \(\cos(x)\), and exponential functions \(e^x\) on their respective domains.&lt;/p&gt;

&lt;h3 id=&quot;definition-of-uniform-continuity&quot;&gt;Definition of Uniform Continuity&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Uniform Continuity&lt;/strong&gt;, on the other hand, imposes a more stringent condition. A function \(f: A \to \mathbb{R}\) is said to be &lt;strong&gt;uniformly continuous on a set&lt;/strong&gt; \(A\) if, for every positive real number \(\varepsilon &amp;gt; 0\), there exists a positive real number \(\delta &amp;gt; 0\) such that for all \(x, y \in A\), if&lt;/p&gt;

\[\lvert x - y \rvert &amp;lt; \delta\]

&lt;p&gt;then&lt;/p&gt;

\[\lvert f(x) - f(y) \rvert &amp;lt; \varepsilon\]

&lt;p&gt;The &lt;strong&gt;key distinction&lt;/strong&gt; from point-wise continuity lies in the order of quantifiers: for &lt;strong&gt;uniform&lt;/strong&gt; continuity, the \(\delta\) depends &lt;em&gt;only&lt;/em&gt; on \(\varepsilon\) and is independent of the specific points \(x\) and \(y\) in the domain.&lt;/p&gt;

&lt;h3 id=&quot;definition-of-lipschitz-continuity&quot;&gt;Definition of Lipschitz Continuity&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Lipschitz Continuity&lt;/strong&gt; provides an even more specific and quantitative notion of continuity. A function \(f: A \to \mathbb{R}\) is said to be &lt;strong&gt;Lipschitz continuous&lt;/strong&gt; (or &lt;strong&gt;L-Lipschitz&lt;/strong&gt;) on a set \(A\) if there exists a constant \(L \geq 0\) such that for all \(x, y \in A\):&lt;/p&gt;

\[\lvert f(x) - f(y) \rvert \leq L \lvert x - y \rvert\]

&lt;p&gt;The smallest such constant \(L\) is called the &lt;strong&gt;Lipschitz constant&lt;/strong&gt; or &lt;strong&gt;Lipschitz modulus&lt;/strong&gt; of \(f\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Properties of Lipschitz Continuity:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Bounded Rate of Change&lt;/strong&gt;: The Lipschitz condition ensures that the function cannot change faster than a linear rate determined by \(L\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Uniform Continuity&lt;/strong&gt;: Every Lipschitz continuous function is uniformly continuous (choose \(\delta = \varepsilon/L\) for \(L &amp;gt; 0\)).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Almost Everywhere Differentiability&lt;/strong&gt;: Lipschitz continuous functions are differentiable almost everywhere, and where the derivative exists, \(\lvert f&apos;(x) \rvert \leq L\).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(f(x) = \lvert x \rvert\) is 1-Lipschitz on \(\mathbb{R}\)&lt;/li&gt;
  &lt;li&gt;\(f(x) = \sin(x)\) is 1-Lipschitz on \(\mathbb{R}\) (since \(\lvert \cos(x) \rvert \leq 1\))&lt;/li&gt;
  &lt;li&gt;\(f(x) = x^2\) is not Lipschitz on \(\mathbb{R}\) but is Lipschitz on any bounded interval&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;key-differences-and-hierarchy&quot;&gt;Key Differences and Hierarchy&lt;/h3&gt;

&lt;p&gt;The three types of continuity form a hierarchy of increasingly strong conditions:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Continuity ⊆ Uniform Continuity ⊆ Lipschitz Continuity&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Point-wise vs Global&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Continuity&lt;/strong&gt;: Local property (checked at each point)&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Uniform Continuity&lt;/strong&gt;: Global property of the entire function&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Lipschitz Continuity&lt;/strong&gt;: Global property with quantitative bounds&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Choice of \(\delta\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Continuity&lt;/strong&gt;: \(\delta\) can depend on both \(\varepsilon\) and the specific point \(c\)&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Uniform Continuity&lt;/strong&gt;: \(\delta\) depends only on \(\varepsilon\), working for all points simultaneously&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Lipschitz Continuity&lt;/strong&gt;: \(\delta = \varepsilon/L\) provides explicit relationship&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Rate of Change Control&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Continuity&lt;/strong&gt;: No control over rate of change&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Uniform Continuity&lt;/strong&gt;: Ensures bounded variation over small intervals&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Lipschitz Continuity&lt;/strong&gt;: Provides explicit linear bound on rate of change&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Strength Relationships&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Every Lipschitz continuous function is uniformly continuous&lt;/li&gt;
      &lt;li&gt;Every uniformly continuous function is continuous&lt;/li&gt;
      &lt;li&gt;The converses are not generally true&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;detailed-examples-and-comparisons&quot;&gt;Detailed Examples and Comparisons&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Example 1: \(f(x) = x^2\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;On \(\mathbb{R}\)&lt;/strong&gt;: Continuous but not uniformly continuous (rate of change \(\lvert f&apos;(x) \rvert = 2\lvert x \rvert\) is unbounded)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;On \([0,1]\)&lt;/strong&gt;: Continuous, uniformly continuous, and Lipschitz with \(L = 2\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example 2: \(f(x) = \sin(x)\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;On \(\mathbb{R}\)&lt;/strong&gt;: Continuous, uniformly continuous, and 1-Lipschitz (since \(\lvert \cos(x) \rvert \leq 1\))&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example 3: \(f(x) = \lvert x \rvert\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;On \(\mathbb{R}\)&lt;/strong&gt;: Continuous, uniformly continuous, and 1-Lipschitz&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Note&lt;/strong&gt;: Not differentiable at \(x = 0\), but still Lipschitz&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example 4: \(f(x) = \sqrt{x}\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;On \([0,1]\)&lt;/strong&gt;: Continuous and uniformly continuous, but not Lipschitz (derivative unbounded near \(x = 0\))&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;On \([a,1]\) for \(a &amp;gt; 0\)&lt;/strong&gt;: Lipschitz with \(L = 1/(2\sqrt{a})\)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;worked-numerical-example-proving-fx--x2-is-continuous-yet-not-uniformly-continuous-on-0-infty&quot;&gt;Worked Numerical Example: Proving \(f(x) = x^2\) Is Continuous Yet NOT Uniformly Continuous on \([0, \infty)\)&lt;/h3&gt;

&lt;p&gt;Test whether a single step size \(\delta\) can keep \(\lvert f(y) - f(x)
vert &amp;lt; 1\) everywhere on \([0, \infty)\):
Pick the sequence of pairs \(x_n = n\) and \(y_n = n + \frac{1}{n}\) for \(n = 1, 10, 100, \dots\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(n\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(x_n\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;\(y_n = n + 1/n\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Input Gap $$\lvert y_n - x_n&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt; &lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;vert$$&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Output Jump $$\lvert y_n^2 - x_n^2&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt; &lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt; &lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt; &lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;vert = 2 + 1/n^2$$&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt; &lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt; &lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt; &lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt; &lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2.00\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1.00\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(3.00\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(10\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(10\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(10.10\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.10\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2.01\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(100\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(100\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(100.01\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0.01\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2.0001\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Even as the input gap \(1/n \to 0\) becomes smaller than &lt;em&gt;any&lt;/em&gt; proposed \(\delta &amp;gt; 0\), the output jump stays strictly above &lt;strong&gt;\(2\)&lt;/strong&gt;! Yet restrict \(f(x) = x^2\) to the compact interval \([0, 10]\), and \(\lvert y^2 - x^2
vert = \lvert y+x
vert\lvert y-x
vert \le 20\lvert y-x
vert\)—so \(\delta = \varepsilon / 20\) works uniformly everywhere!&lt;/p&gt;

&lt;h3 id=&quot;explanation-four-takeaways-connecting-continuity-to-bayesian-computing&quot;&gt;Explanation: Four Takeaways Connecting Continuity to Bayesian Computing&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bounded slope implies Lipschitz \(\implies\) uniform continuity:&lt;/strong&gt; Whenever \(\lvert f&apos;(x)
vert \le M\) on an interval, \(\lvert f(y)-f(x)
vert \le M\lvert y-x
vert\) gives an instant, explicit uniform step size \(\delta = \varepsilon/M\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Watch boundary singularities in Beta/Gamma densities:&lt;/strong&gt; \(\mathrm{Beta}(0.5, 0.5)\) shoots to \(\infty\) at \(p = 0\) and \(p = 1\)—evaluating it on a naive grid starting at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p = 0.0&lt;/code&gt; produces &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Log-posterior smoothness matters for HMC/NUTS:&lt;/strong&gt; Hamiltonian Monte Carlo uses fixed leapfrog step sizes \(\epsilon\); when log-posterior curvature varies wildly (failing uniform Lipschitz gradients, like Neal’s Funnel!), HMC produces &lt;strong&gt;divergences&lt;/strong&gt; until you reparameterize.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compact domains are friendly; infinite tails need care:&lt;/strong&gt; Always verify tail decay before truncating a numerical grid on \((-\infty, \infty)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Quick check.&lt;/strong&gt; Is \(f(x) = \frac{1}{x}\) uniformly continuous on the closed interval \([1, 10]\)? What about on the open interval \((0, 1]\)?&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;reference-videos&quot;&gt;Reference videos&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Continuity at a point&lt;/td&gt;
          &lt;td&gt;Limits and continuity&lt;/td&gt;
          &lt;td&gt;AP Calculus AB&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=3KMqU5j7irw) — Khan Academy, English. &lt;strong&gt;watch first&lt;/strong&gt;. Watch continuity at a point through nearby inputs giving nearby outputs, the local idea this lesson starts from.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Uniform Continuity Explained&lt;/td&gt;
          &lt;td&gt;Real Analysis](https://www.youtube.com/watch?v=MmxtJwr3Kws) — Wrath of Math, English. Watch uniform continuity as a single modulus of continuity for the whole domain, the distinction the lesson exists to draw.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 

</feed>
