<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://xiaomingtseng.github.io/blog/feed.xml" rel="self" type="application/atom+xml" /><link href="https://xiaomingtseng.github.io/blog/" rel="alternate" type="text/html" /><updated>2026-03-29T15:26:17+00:00</updated><id>https://xiaomingtseng.github.io/blog/feed.xml</id><title type="html">竹節蟲的blog</title><subtitle>歡迎來到我的部落格</subtitle><author><name>Chien-Chih Tseng</name></author><entry><title type="html">隨機演算法導論</title><link href="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/randomized-algorithms-intro.html" rel="alternate" type="text/html" title="隨機演算法導論" /><published>2026-03-16T07:00:00+00:00</published><updated>2026-03-16T07:00:00+00:00</updated><id>https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/randomized-algorithms-intro</id><content type="html" xml:base="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/randomized-algorithms-intro.html"><![CDATA[<style>
:root {
  --accent: #667eea;
  --accent-light: #eef3fb;
  --border: #e5e5e0;
  --text-muted: #6b6b65;
}

.oneliner {
  background: var(--accent-light);
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 32px 0;
  font-size: 1.05rem;
  font-style: italic;
  color: #1a3a6b;
}

.section {
  margin: 40px 0;
}

.section-label {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-family: monospace;
  font-size: 11px;
  font-weight: bold;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 14px;
}

.section-label::before {
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  background: #d4a847;
}

.section-label.blue::before { background: #4a90d9; }
.section-label.green::before { background: #5aaa72; }
.section-label.purple::before { background: #9b72c8; }
.section-label.red::before { background: #d96b5a; }

.math-block {
  background: #fafaf8;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 16px 20px;
  margin: 16px 0;
  overflow-x: auto;
}

.comparison-table {
  width: 100%;
  border-collapse: collapse;
  margin: 16px 0;
}

.comparison-table th,
.comparison-table td {
  padding: 12px;
  border: 1px solid var(--border);
  text-align: left;
}

.comparison-table th {
  background: #f5f5f3;
  font-weight: bold;
  color: #2a2a28;
}

.comparison-table tr:hover {
  background: var(--accent-light);
}

.highlight-box {
  background: #fff8e6;
  border-left: 4px solid #d4a847;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.example-box {
  background: #f0f9ff;
  border-left: 4px solid #4a90d9;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}
</style>

<!-- MathJax 配置 -->
<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$']],
    displayMath: [['$$', '$$']],
    tags: 'ams'
  }
};
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async=""></script>

<hr />

<h2 id="一句話解釋">一句話解釋</h2>

<div class="oneliner">
  <p>在演算法執行過程中使用隨機選擇，換取更簡單的實作、更好的平均效能，或解決確定性演算法難以處理的問題。</p>
</div>

<hr />

<h2 id="什麼是隨機演算法">什麼是隨機演算法？</h2>

<div class="section">
  <div class="section-label blue">核心概念</div>

  <p><strong>隨機演算法（Randomized Algorithm）<strong> 是在執行過程中會做</strong>隨機選擇</strong>的演算法。</p>

  <h3 id="section">定義</h3>

  <ul>
    <li>演算法可以「擲硬幣」或「擲骰子」來決定下一步</li>
    <li>給定相同的輸入，每次執行可能產生不同的結果或運行時間</li>
    <li>隨機性來源：
      <ul>
        <li>偽隨機數生成器（Pseudo-random number generator）</li>
        <li>真隨機源（硬體、量子現象等）</li>
      </ul>
    </li>
  </ul>

  <h3 id="section-1">與確定性演算法的差異</h3>

  <table class="comparison-table">
  <thead>
    <tr>
      <th>特性</th>
      <th>確定性演算法</th>
      <th>隨機演算法</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>**執行過程**</td>
      <td>完全可預測</td>
      <td>含隨機選擇</td>
    </tr>
    <tr>
      <td>**相同輸入**</td>
      <td>總是產生相同結果</td>
      <td>可能產生不同結果/時間</td>
    </tr>
    <tr>
      <td>**分析方式**</td>
      <td>Worst-case / Best-case</td>
      <td>期望值 / 機率界</td>
    </tr>
    <tr>
      <td>**正確性**</td>
      <td>絕對保證</td>
      <td>可能是機率性保證</td>
    </tr>
  </tbody>
</table>

</div>

<hr />

<h2 id="為什麼使用隨機演算法">為什麼使用隨機演算法？</h2>

<div class="section">
  <div class="section-label green">動機</div>

  <h3 id="section-2">1. 簡化演算法設計</h3>

  <p>隨機性可以避免複雜的決策邏輯。</p>

  <div class="example-box">
    <p><strong>範例：Quicksort</strong><br />
確定性 Quicksort 需要精心選擇 pivot（如 median-of-medians）才能保證 O(n log n)。<br />
隨機 Quicksort 只需<strong>隨機選 pivot</strong>，期望時間就是 O(n log n)，實作簡單得多。</p>
  </div>

  <h3 id="section-3">2. 打破對手策略</h3>

  <p>在競爭或對抗性環境中，隨機性讓對手無法預測你的行為。</p>

  <div class="example-box">
    <p><strong>範例：線上演算法</strong><br />
如果演算法的行為可預測，adversary 可以構造最壞輸入。<br />
隨機化讓 adversary 無法針對性地攻擊。</p>
  </div>

  <h3 id="section-4">3. 更好的平均效能</h3>

  <p>某些問題的確定性演算法 worst-case 很差，但隨機版本期望效能很好。</p>

  <h3 id="section-5">4. 唯一已知的有效方法</h3>

  <p>某些問題（如質數測試）的確定性多項式演算法直到很晚才被發現，隨機演算法長期是唯一實用解。</p>

  <div class="highlight-box">
    <p><strong>💡 核心思想：</strong><br />
隨機性不是「運氣」，而是一種<strong>設計工具</strong>。我們用機率分析來證明演算法在<strong>期望意義下</strong>或<strong>高機率下</strong>表現良好。</p>
  </div>

</div>

<hr />

<h2 id="las-vegas-vs-monte-carlo">Las Vegas vs. Monte Carlo</h2>

<div class="section">
  <div class="section-label purple">兩大類別</div>

  <p>隨機演算法主要分為兩類：</p>

  <h3 id="las-vegas-algorithms">Las Vegas Algorithms</h3>

  <ul>
    <li><strong>總是給出正確答案</strong></li>
    <li><strong>運行時間是隨機的</strong></li>
    <li>我們分析<strong>期望運行時間</strong></li>
  </ul>

  <div class="math-block">

<strong>定義：</strong>
- 輸出總是正確：$\Pr[\text{Output is correct}] = 1$
- 運行時間 $T$ 是隨機變數：$\mathbb{E}[T] = $ 期望時間

</div>

  <div class="example-box">
    <p><strong>範例：</strong></p>
    <ul>
  <li><strong>Randomized Quicksort：</strong> 總是正確排序，但時間隨 pivot 選擇而變</li>
  <li><strong>Randomized Min-Cut（重複到成功）：</strong> 重複運行直到找到正確答案</li>
</ul>
  </div>

  <h3 id="monte-carlo-algorithms">Monte Carlo Algorithms</h3>

  <ul>
    <li><strong>運行時間是確定的</strong>（或有界）</li>
    <li><strong>答案可能是錯的</strong>（但機率很小）</li>
    <li>我們分析<strong>錯誤機率</strong></li>
  </ul>

  <div class="math-block">

<strong>定義：</strong>
- 運行時間固定或有界：$T \leq T_{\max}$
- 可能出錯：$\Pr[\text{Output is wrong}] \leq \epsilon$ （通常 $\epsilon$ 很小）

</div>

  <div class="example-box">
    <p><strong>範例：</strong></p>
    <ul>
  <li><strong>Miller-Rabin 質數測試：</strong> 固定時間，但可能誤判合數為質數</li>
  <li><strong>Karger's Min-Cut（單次執行）：</strong> 多項式時間，但可能找到非最小割</li>
</ul>
  </div>

  <h3 id="section-6">比較表</h3>

  <table class="comparison-table">
  <thead>
    <tr>
      <th></th>
      <th>Las Vegas</th>
      <th>Monte Carlo</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>**正確性**</td>
      <td>✓ 總是正確</td>
      <td>✗ 可能出錯（機率小）</td>
    </tr>
    <tr>
      <td>**運行時間**</td>
      <td>✗ 隨機（期望有界）</td>
      <td>✓ 確定或有界</td>
    </tr>
    <tr>
      <td>**分析重點**</td>
      <td>期望時間 $\mathbb{E}[T]$</td>
      <td>錯誤率 $\Pr[\text{error}] \leq \epsilon$</td>
    </tr>
    <tr>
      <td>**改進方式**</td>
      <td>無法改進正確性（已是 100%）</td>
      <td>重複執行降低錯誤率</td>
    </tr>
    <tr>
      <td>**命名來源**</td>
      <td>Las Vegas 賭場：不會輸，但不知何時贏</td>
      <td>Monte Carlo 賭場：快速結束，但可能輸</td>
    </tr>
  </tbody>
</table>

  <h3 id="section-7">兩者的轉換</h3>

  <p><strong>Monte Carlo → Las Vegas：</strong></p>
  <ul>
    <li>如果 Monte Carlo 演算法能<strong>驗證答案</strong>是否正確</li>
    <li>可以重複運行直到得到正確答案</li>
    <li>變成 Las Vegas（正確但時間隨機）</li>
  </ul>

  <p><strong>Las Vegas → Monte Carlo：</strong></p>
  <ul>
    <li>給 Las Vegas 演算法設定<strong>時間上限</strong></li>
    <li>超時就輸出「不知道」或隨機答案</li>
    <li>變成 Monte Carlo（快但可能錯）</li>
  </ul>

  <div class="highlight-box">
    <p><strong>🎲 記憶技巧：</strong></p>
    <ul>
  <li><strong>Las Vegas = Lucky but Slow（可能）：</strong> 一定贏，但可能等很久</li>
  <li><strong>Monte Carlo = Fast but Risky：</strong> 很快結束，但可能輸</li>
</ul>
  </div>

</div>

<hr />

<h2 id="經典範例">經典範例</h2>

<div class="section">

  <h3 id="quicksortlas-vegas">1. 隨機 Quicksort（Las Vegas）</h3>

  <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">randomized_quicksort</span><span class="p">(</span><span class="n">A</span><span class="p">):</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">A</span><span class="p">)</span> <span class="o">&lt;=</span> <span class="mi">1</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">A</span>
    <span class="n">pivot</span> <span class="o">=</span> <span class="n">random</span><span class="p">.</span><span class="n">choice</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>  <span class="c1"># 隨機選 pivot
</span>    <span class="n">left</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">A</span> <span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="n">pivot</span><span class="p">]</span>
    <span class="n">middle</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">A</span> <span class="k">if</span> <span class="n">x</span> <span class="o">==</span> <span class="n">pivot</span><span class="p">]</span>
    <span class="n">right</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">A</span> <span class="k">if</span> <span class="n">x</span> <span class="o">&gt;</span> <span class="n">pivot</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">randomized_quicksort</span><span class="p">(</span><span class="n">left</span><span class="p">)</span> <span class="o">+</span> <span class="n">middle</span> <span class="o">+</span> <span class="n">randomized_quicksort</span><span class="p">(</span><span class="n">right</span><span class="p">)</span>
</code></pre></div>  </div>

  <ul>
    <li><strong>類型：</strong> Las Vegas</li>
    <li><strong>正確性：</strong> 總是正確排序</li>
    <li><strong>時間：</strong> 期望 $O(n \log n)$，worst-case $O(n^2)$（機率極小）</li>
  </ul>

  <h3 id="monte-carlo">2. 質數測試（Monte Carlo）</h3>

  <p>Miller-Rabin 演算法：</p>
  <ul>
    <li>輸入：$n$（待測試的數）</li>
    <li>輸出：「質數」或「合數」</li>
    <li><strong>保證：</strong> 如果輸出「合數」，則 $n$ 一定是合數</li>
    <li><strong>錯誤：</strong> 如果輸出「質數」，$n$ 可能是合數（機率 $\leq 1/4^k$，$k$ 是測試次數）</li>
  </ul>

  <h3 id="kargers-min-cut">3. Karger’s Min-Cut</h3>

  <p>找圖的最小割：</p>
  <ul>
    <li><strong>單次執行（Monte Carlo）：</strong> 多項式時間，成功率 $\geq \frac{2}{n^2}$</li>
    <li><strong>重複執行（Las Vegas）：</strong> 運行 $O(n^2 \log n)$ 次，高機率找到最小割</li>
  </ul>

</div>

<hr />

<h2 id="總結">總結</h2>

<div class="section">

  <p><strong>隨機演算法</strong>是現代演算法設計的重要工具：</p>

  <ol>
    <li><strong>簡化設計：</strong> 避免複雜的確定性邏輯</li>
    <li><strong>打破對抗：</strong> 讓 adversary 無法預測</li>
    <li><strong>良好效能：</strong> 期望或高機率下表現優異</li>
    <li><strong>兩大類別：</strong>
      <ul>
        <li><strong>Las Vegas：</strong> 正確但時間隨機</li>
        <li><strong>Monte Carlo：</strong> 快速但可能出錯</li>
      </ul>
    </li>
  </ol>

  <p>後續課程將深入探討機率工具、複雜度理論、以及各種隨機演算法的設計與分析。</p>

</div>

<hr />

<h2 id="參考資料">參考資料</h2>

<ul>
  <li>Motwani &amp; Raghavan, <em>Randomized Algorithms</em></li>
  <li>Mitzenmacher &amp; Upfal, <em>Probability and Computing</em></li>
  <li>CLRS, <em>Introduction to Algorithms</em>, Chapter 5</li>
</ul>]]></content><author><name>Chien-Chih Tseng</name></author><category term="隨機演算法" /><category term="導論" /><category term="Las Vegas" /><category term="Monte Carlo" /><summary type="html"><![CDATA[什麼是隨機演算法？為什麼要使用隨機性？Las Vegas 與 Monte Carlo 的差異]]></summary></entry><entry><title type="html">Parametric Methods</title><link href="https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/parametric-methods.html" rel="alternate" type="text/html" title="Parametric Methods" /><published>2026-03-16T06:00:00+00:00</published><updated>2026-03-16T06:00:00+00:00</updated><id>https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/parametric-methods</id><content type="html" xml:base="https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/parametric-methods.html"><![CDATA[<style>
:root {
  --accent: #f093fb;
  --accent-light: #fef0f5;
  --border: #e5e5e0;
  --text-muted: #6b6b65;
}

.oneliner {
  background: var(--accent-light);
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 32px 0;
  font-size: 1.05rem;
  font-style: italic;
  color: #8b1538;
}

.section {
  margin: 40px 0;
}

.section-label {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-family: monospace;
  font-size: 11px;
  font-weight: bold;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 14px;
}

.section-label::before {
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  background: #d4a847;
}

.section-label.blue::before { background: #4a90d9; }
.section-label.green::before { background: #5aaa72; }
.section-label.purple::before { background: #9b72c8; }
.section-label.red::before { background: #d96b5a; }

.math-block {
  background: #fafaf8;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 16px 20px;
  margin: 16px 0;
  overflow-x: auto;
}

.comparison-table {
  width: 100%;
  border-collapse: collapse;
  margin: 16px 0;
}

.comparison-table th,
.comparison-table td {
  padding: 12px;
  border: 1px solid var(--border);
  text-align: left;
}

.comparison-table th {
  background: #f5f5f3;
  font-weight: bold;
  color: #2a2a28;
}

.comparison-table tr:hover {
  background: var(--accent-light);
}

.highlight-box {
  background: #fff8e6;
  border-left: 4px solid #d4a847;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.steps-list {
  counter-reset: step-counter;
  list-style: none;
  padding: 0;
}

.steps-list li {
  counter-increment: step-counter;
  padding: 12px 0 12px 40px;
  position: relative;
  border-left: 2px solid var(--border);
  margin-left: 20px;
}

.steps-list li::before {
  content: counter(step-counter);
  position: absolute;
  left: -20px;
  top: 8px;
  background: var(--accent);
  color: white;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
}

.steps-list li:last-child {
  border-left-color: transparent;
}
</style>

<!-- MathJax 配置 -->
<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$']],
    displayMath: [['$$', '$$']],
    tags: 'ams'
  }
};
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async=""></script>

<hr />

<h2 id="一句話解釋">一句話解釋</h2>

<div class="oneliner">
  <p>用固定數量的參數來描述機率分佈，透過 MLE 或 MAP 從資料中學習參數值。</p>
</div>

<hr />

<h2 id="核心假設什麼是-parametric-method">核心假設：什麼是 Parametric Method</h2>

<div class="section">
  <div class="section-label blue">核心概念</div>

  <p><strong>Parametric Method（參數方法）** 的核心假設是：資料的分佈可以用一個**有限維度的參數向量</strong> $\theta$ 完全描述。</p>

  <h3 id="section">基本假設</h3>

  <p>給定資料集 $\mathcal{D} = {x_1, x_2, \dots, x_n}$，我們假設：</p>

\[p(x \mid \theta) \quad \text{的形式已知，只需要估計 } \theta\]

  <h3 id="section-1">常見的參數化分佈</h3>

  <div class="math-block">

<strong>高斯分佈（Gaussian）：</strong>

$$p(x \mid \mu, \sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)$$
參數：$\theta = (\mu, \sigma^2)$

<strong>伯努利分佈（Bernoulli）：</strong>

$$p(x \mid p) = p^x (1-p)^{1-x}, \quad x \in \{0, 1\}$$
參數：$\theta = p$

<strong>多項式分佈（Multinomial）：</strong>

$$p(x \mid \boldsymbol{\pi}) = \prod_{k=1}^K \pi_k^{x_k}$$
參數：$\theta = (\pi_1, \dots, \pi_K)$

</div>

  <h3 id="parametric-vs-non-parametric">Parametric vs. Non-parametric</h3>

  <table class="comparison-table">
  <thead>
    <tr>
      <th>特性</th>
      <th>Parametric</th>
      <th>Non-parametric</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>**參數數量**</td>
      <td>固定（與資料量無關）</td>
      <td>隨資料量增長</td>
    </tr>
    <tr>
      <td>**假設**</td>
      <td>強假設（分佈形式已知）</td>
      <td>弱假設</td>
    </tr>
    <tr>
      <td>**樣本需求**</td>
      <td>較少</td>
      <td>較多</td>
    </tr>
    <tr>
      <td>**計算複雜度**</td>
      <td>較低</td>
      <td>較高</td>
    </tr>
    <tr>
      <td>**彈性**</td>
      <td>低（受限於假設）</td>
      <td>高</td>
    </tr>
    <tr>
      <td>**範例**</td>
      <td>Linear Regression, Logistic Regression, Naive Bayes</td>
      <td>KNN, Decision Trees, Kernel Methods</td>
    </tr>
  </tbody>
</table>

</div>

<hr />

<h2 id="mle最大似然估計">MLE：最大似然估計</h2>

<div class="section">
  <div class="section-label">Maximum Likelihood Estimation</div>

  <h3 id="section-2">核心概念</h3>

  <p><strong>最大似然估計（MLE）</strong> 的想法是：找到參數 $\theta$，使得觀測到的資料 $\mathcal{D}$ 出現的機率最大。</p>

  <div class="math-block">

<strong>似然函數（Likelihood）：</strong>

$$L(\theta \mid \mathcal{D}) = p(\mathcal{D} \mid \theta) = \prod_{i=1}^n p(x_i \mid \theta)$$

<strong>對數似然（Log-likelihood）：</strong>

$$\ell(\theta) = \log L(\theta) = \sum_{i=1}^n \log p(x_i \mid \theta)$$

<strong>MLE 估計：</strong>

$$\hat{\theta}_{\text{MLE}} = \arg\max_\theta \ell(\theta)$$

</div>

  <h3 id="section-3">求解方法</h3>

  <p>通常透過對 $\ell(\theta)$ 微分並令其為零：</p>

\[\frac{\partial \ell(\theta)}{\partial \theta} = 0\]

  <h3 id="gaussian-distribution--mle">範例：Gaussian Distribution 的 MLE</h3>

  <p>假設資料 $x_1, \dots, x_n$ 來自 $\mathcal{N}(\mu, \sigma^2)$：</p>

  <div class="math-block">

<strong>對數似然：</strong>

$$

\ell(\mu, \sigma^2) = -\frac{n}{2}\log(2\pi) - \frac{n}{2}\log(\sigma^2) - \frac{1}{2\sigma^2}\sum_{i=1}^n (x_i - \mu)^2

$$

<strong>對 $\mu$ 求導並令為零：</strong>

$$

\frac{\partial \ell}{\partial \mu} = \frac{1}{\sigma^2}\sum_{i=1}^n (x_i - \mu) = 0

$$

<strong>得到：</strong>

$$

\hat{\mu}_{\text{MLE}} = \frac{1}{n}\sum_{i=1}^n x_i \quad \text{（樣本平均）}

$$

<strong>對 $\sigma^2$ 求導並令為零：</strong>

$$

\frac{\partial \ell}{\partial \sigma^2} = -\frac{n}{2\sigma^2} + \frac{1}{2\sigma^4}\sum_{i=1}^n (x_i - \mu)^2 = 0

$$

<strong>得到：</strong>

$$

\hat{\sigma}^2_{\text{MLE}} = \frac{1}{n}\sum_{i=1}^n (x_i - \hat{\mu})^2 \quad \text{（樣本變異數）}

$$

</div>

  <div class="highlight-box">
    <p><strong>💡 重要性質：</strong></p>
    <ul>
  <li><strong>Consistency（一致性）：</strong> 當 $n \to \infty$，$\hat{\theta}_{\text{MLE}} \to \theta_{\text{true}}$</li>
  <li><strong>Asymptotic Normality：</strong> 大樣本下近似常態分佈</li>
  <li><strong>Asymptotic Efficiency：</strong> 漸近最小變異數</li>
</ul>
  </div>

</div>

<hr />

<h2 id="map-與-bayesian-estimation-的差異">MAP 與 Bayesian Estimation 的差異</h2>

<div class="section">
  <div class="section-label purple">貝葉斯觀點</div>

  <h3 id="section-4">三種估計方法的比較</h3>

  <table class="comparison-table">
  <thead>
    <tr>
      <th>方法</th>
      <th>目標</th>
      <th>公式</th>
      <th>輸出</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>**MLE**</td>
      <td>最大化似然</td>
      <td>$\arg\max_\theta p(\mathcal{D} \mid \theta)$</td>
      <td>點估計（單一值）</td>
    </tr>
    <tr>
      <td>**MAP**</td>
      <td>最大化後驗</td>
      <td>$\arg\max_\theta p(\theta \mid \mathcal{D})$</td>
      <td>點估計（單一值）</td>
    </tr>
    <tr>
      <td>**Bayesian**</td>
      <td>計算後驗分佈</td>
      <td>$p(\theta \mid \mathcal{D})$</td>
      <td>完整分佈</td>
    </tr>
  </tbody>
</table>

  <h3 id="maximum-a-posteriori-map">Maximum A Posteriori (MAP)</h3>

  <p>MAP 考慮參數的<strong>事前分佈（prior）</strong> $p(\theta)$：</p>

  <div class="math-block">

<strong>後驗分佈（Posterior）：</strong>

$$

p(\theta \mid \mathcal{D}) = \frac{p(\mathcal{D} \mid \theta) p(\theta)}{p(\mathcal{D})} \propto p(\mathcal{D} \mid \theta) p(\theta)

$$

<strong>MAP 估計：</strong>

$$

\hat{\theta}_{\text{MAP}} = \arg\max_\theta p(\theta \mid \mathcal{D}) = \arg\max_\theta \left[ \log p(\mathcal{D} \mid \theta) + \log p(\theta) \right]

$$

</div>

  <h3 id="mle-">與 MLE 的關係</h3>

  <ul>
    <li>
      <p>當 prior $p(\theta)$ 是 <strong>uniform（均勻分佈）</strong> 時：
\(\hat{\theta}_{\text{MAP}} = \hat{\theta}_{\text{MLE}}\)</p>
    </li>
    <li>
      <p>當 prior 是 <strong>Gaussian</strong> $\mathcal{N}(0, \lambda^{-1})$ 時，MAP 等價於 <strong>L2 regularization（Ridge Regression）</strong></p>
    </li>
  </ul>

  <h3 id="bayesian-estimation">Bayesian Estimation</h3>

  <p>Bayesian 方法不做點估計，而是保留<strong>整個後驗分佈</strong> $p(\theta \mid \mathcal{D})$。</p>

  <p><strong>預測新資料點時：</strong></p>

  <div class="math-block">

$$

p(x_{\text{new}} \mid \mathcal{D}) = \int p(x_{\text{new}} \mid \theta) p(\theta \mid \mathcal{D}) \, d\theta

$$

這稱為 **posterior predictive distribution（後驗預測分佈）**，對所有可能的 $\theta$ 做加權平均。

</div>

  <div class="highlight-box">
    <p><strong>🔑 關鍵差異：</strong></p>
    <ul>
  <li><strong>MAP：</strong> 用「最可能的」參數值來預測（點估計）</li>
  <li><strong>Bayesian：</strong> 考慮參數的「不確定性」，對所有可能參數做積分</li>
  <li>**Bayesian 更穩健，** 特別在資料不足時</li>
  <li>**MAP 計算更簡單，** 不需要處理積分</li>
</ul>
  </div>

</div>

<hr />

<h2 id="bias-variance-tradeoff">Bias-Variance Tradeoff</h2>

<div class="section">
  <div class="section-label red">估計誤差分析</div>

  <h3 id="section-5">基本概念</h3>

  <p>任何估計器 $\hat{\theta}$ 的<strong>均方誤差（Mean Squared Error, MSE）</strong> 可以分解為：</p>

  <div class="math-block">

$$

\text{MSE}(\hat{\theta}) = \mathbb{E}\left[(\hat{\theta} - \theta_{\text{true}})^2\right] = \text{Bias}^2(\hat{\theta}) + \text{Var}(\hat{\theta})

$$

<strong>其中：</strong>

<strong>Bias（偏差）：</strong>

$$\text{Bias}(\hat{\theta}) = \mathbb{E}[\hat{\theta}] - \theta_{\text{true}}$$

<strong>Variance（變異數）：</strong>

$$\text{Var}(\hat{\theta}) = \mathbb{E}\left[(\hat{\theta} - \mathbb{E}[\hat{\theta}])^2\right]$$

</div>

  <h3 id="unbiased-vs-biased-estimator">Unbiased vs. Biased Estimator</h3>

  <p><strong>Unbiased Estimator（不偏估計器）：</strong></p>
  <ul>
    <li>滿足 $\mathbb{E}[\hat{\theta}] = \theta_{\text{true}}$</li>
    <li>範例：樣本平均 $\hat{\mu} = \frac{1}{n}\sum x_i$ 是 $\mu$ 的不偏估計</li>
  </ul>

  <p><strong>Biased Estimator（有偏估計器）：</strong></p>
  <ul>
    <li>$\mathbb{E}[\hat{\theta}] \neq \theta_{\text{true}}$</li>
    <li>範例：MLE 的 $\hat{\sigma}^2 = \frac{1}{n}\sum(x_i - \bar{x})^2$ 是 <strong>有偏的</strong></li>
  </ul>

  <h3 id="mle--1">為什麼 MLE 的變異數估計是有偏的？</h3>

  <div class="math-block">

MLE 估計的變異數：

$$\hat{\sigma}^2_{\text{MLE}} = \frac{1}{n}\sum_{i=1}^n (x_i - \bar{x})^2$$

<strong>期望值：</strong>

$$

\mathbb{E}[\hat{\sigma}^2_{\text{MLE}}] = \frac{n-1}{n}\sigma^2 \neq \sigma^2

$$

因此它是 **低估（underestimate）** 的有偏估計器。

<strong>不偏估計器（Unbiased estimator）：</strong>

$$\hat{\sigma}^2_{\text{unbiased}} = \frac{1}{n-1}\sum_{i=1}^n (x_i - \bar{x})^2$$

這就是為什麼統計軟體通常使用 $n-1$ 而非 $n$（稱為 **Bessel's correction**）。

</div>

  <h3 id="biased-estimator">為什麼接受 Biased Estimator？</h3>

  <p>雖然 biased，但 MLE 的變異數估計器有<strong>更低的變異數（lower variance）</strong>：</p>

  <ul>
    <li>$\text{Var}(\hat{\sigma}^2<em>{\text{MLE}})$ &lt; $\text{Var}(\hat{\sigma}^2</em>{\text{unbiased}})$</li>
    <li>在某些情況下，<strong>MSE</strong> 反而更小！</li>
  </ul>

  <div class="highlight-box">
    <p><strong>💡 核心洞察：</strong><br />
我們關心的是 <strong>MSE = Bias² + Variance</strong>，而非單純的 unbiasedness。<br />
有時候接受一點 bias，可以換來更低的 variance，總體誤差反而更小。<br />
這就是 <strong>Bias-Variance Tradeoff</strong> 的精神！</p>
  </div>

  <h3 id="tradeoff-">Tradeoff 的直覺</h3>

  <ul>
    <li><strong>High Bias, Low Variance：</strong> 模型太簡單（underfitting）
      <ul>
        <li>例如用線性模型擬合非線性資料</li>
      </ul>
    </li>
    <li><strong>Low Bias, High Variance：</strong> 模型太複雜（overfitting）
      <ul>
        <li>例如高次多項式完美擬合訓練資料</li>
      </ul>
    </li>
    <li><strong>理想狀態：</strong> 在兩者之間找到平衡點</li>
  </ul>

</div>

<hr />

<h2 id="generative-approach-用於分類">Generative Approach 用於分類</h2>

<div class="section">
  <div class="section-label green">生成式分類</div>

  <h3 id="section-6">核心思想</h3>

  <p><strong>Generative Approach** 為每個類別 $C_k$ 建模**聯合機率分佈</strong> $p(x, C_k)$，然後用貝葉斯定理來分類。</p>

  <h3 id="section-7">完整流程</h3>

  <ul class="steps-list">
  <li>
    <strong>建模類別先驗（Class Prior）：</strong>
    $$p(C_k) = \frac{N_k}{N}$$
    其中 $N_k$ 是類別 $k$ 的樣本數，$N$ 是總樣本數。
  </li>
  
  <li>
    <strong>建模條件機率（Class-conditional Density）：</strong>
    $$p(x \mid C_k) \sim \mathcal{N}(\mu_k, \Sigma_k)$$
    使用 MLE 或 MAP 估計每個類別的參數 $\mu_k, \Sigma_k$。
  </li>
  
  <li>
    <strong>計算聯合機率：</strong>
    $$p(x, C_k) = p(x \mid C_k) p(C_k)$$
  </li>
  
  <li>
    <strong>用貝葉斯定理計算後驗：</strong>
    $$p(C_k \mid x) = \frac{p(x \mid C_k) p(C_k)}{p(x)} = \frac{p(x \mid C_k) p(C_k)}{\sum_{j} p(x \mid C_j) p(C_j)}$$
  </li>
  
  <li>
    <strong>分類決策：</strong>
    $$\hat{C} = \arg\max_k p(C_k \mid x)$$
  </li>
</ul>

  <h3 id="generative-models">常見的 Generative Models</h3>

  <p><strong>1. Gaussian Discriminant Analysis (GDA)</strong></p>
  <ul>
    <li>假設每個類別的 $p(x \mid C_k)$ 是高斯分佈</li>
    <li>變體：
      <ul>
        <li><strong>Linear Discriminant Analysis (LDA)：</strong> 所有類別共享相同的 $\Sigma$</li>
        <li><strong>Quadratic Discriminant Analysis (QDA)：</strong> 每個類別有不同的 $\Sigma_k$</li>
      </ul>
    </li>
  </ul>

  <p><strong>2. Naive Bayes</strong></p>
  <ul>
    <li>假設特徵條件獨立：
\(p(x \mid C_k) = \prod_{j=1}^d p(x_j \mid C_k)\)</li>
    <li>簡化計算，適合高維資料</li>
  </ul>

  <h3 id="generative-vs-discriminative">Generative vs. Discriminative</h3>

  <table class="comparison-table">
  <thead>
    <tr>
      <th>特性</th>
      <th>Generative</th>
      <th>Discriminative</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>**建模對象**</td>
      <td>$p(x, y)$ 或 $p(x \mid y)$</td>
      <td>$p(y \mid x)$ 直接建模</td>
    </tr>
    <tr>
      <td>**範例**</td>
      <td>Naive Bayes, GDA, HMM</td>
      <td>Logistic Regression, SVM</td>
    </tr>
    <tr>
      <td>**優點**</td>
      <td>可生成新資料、處理缺失值</td>
      <td>通常更高的分類準確率</td>
    </tr>
    <tr>
      <td>**資料需求**</td>
      <td>需要更多資料（建模完整分佈）</td>
      <td>較少（只需學習決策邊界）</td>
    </tr>
  </tbody>
</table>

  <div class="highlight-box">
    <p><strong>🎯 何時使用 Generative Approach？</strong></p>
    <ul>
  <li>資料量充足</li>
  <li>需要生成新樣本（例如 GAN）</li>
  <li>需要處理缺失特徵</li>
  <li>類別先驗 $p(C_k)$ 對決策很重要</li>
  <li>想要解釋「為什麼」而非只是「分類結果」</li>
</ul>
  </div>

</div>

<hr />

<h2 id="總結">總結</h2>

<div class="section">

  <p><strong>Parametric Methods</strong> 是機器學習的基石，透過有限參數來描述資料分佈：</p>

  <ol>
    <li><strong>MLE</strong> 找最大似然的參數（不考慮 prior）</li>
    <li><strong>MAP</strong> 加入 prior，等價於 regularization</li>
    <li><strong>Bayesian</strong> 保留完整的後驗分佈，更穩健但計算複雜</li>
    <li><strong>Bias-Variance Tradeoff</strong> 提醒我們：不偏不等於最好</li>
    <li><strong>Generative Approach</strong> 建模聯合分佈，可用於分類與生成</li>
  </ol>

  <p>這些概念串連起整個機器學習的理論基礎，從估計、推論到分類決策。</p>

</div>

<hr />

<h2 id="參考資料">參考資料</h2>

<ul>
  <li>Bishop, <em>Pattern Recognition and Machine Learning</em>, Chapter 2 &amp; 4</li>
  <li>Murphy, <em>Machine Learning: A Probabilistic Perspective</em>, Chapter 5</li>
  <li>Hastie, Tibshirani, Friedman, <em>The Elements of Statistical Learning</em>, Chapter 2</li>
</ul>]]></content><author><name>Chien-Chih Tseng</name></author><category term="機器學習" /><category term="參數估計" /><category term="MLE" /><category term="MAP" /><category term="Bias-Variance" /><summary type="html"><![CDATA[用固定數量的參數來描述機率分佈，透過 MLE 或 MAP 從資料中學習參數值]]></summary></entry><entry><title type="html">Ch03: Bayesian Decision Theory</title><link href="https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/bayesian-decision.html" rel="alternate" type="text/html" title="Ch03: Bayesian Decision Theory" /><published>2026-03-16T04:00:00+00:00</published><updated>2026-03-16T04:00:00+00:00</updated><id>https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/bayesian-decision</id><content type="html" xml:base="https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/bayesian-decision.html"><![CDATA[<style>
:root {
  --accent: #f093fb;
  --accent-light: #fef5ff;
  --border: #f5e5f0;
  --text-muted: #6b6b65;
}

.oneliner {
  background: var(--accent-light);
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 32px 0;
  font-size: 1.05rem;
  font-style: italic;
  color: #8b2c7a;
}

.section {
  margin: 40px 0;
}

.section-label {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-family: monospace;
  font-size: 11px;
  font-weight: bold;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 14px;
}

.section-label::before {
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  background: #d4a847;
}

.section-label.blue::before { background: #4a90d9; }
.section-label.green::before { background: #5aaa72; }
.section-label.purple::before { background: #d96bc8; }
.section-label.red::before { background: #d96b5a; }

.math-block {
  background: #fafaf8;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 16px 20px;
  margin: 16px 0;
  overflow-x: auto;
}

.theorem-box {
  background: #fef5ff;
  border: 2px solid #d96bc8;
  border-radius: 8px;
  padding: 16px 20px;
  margin: 20px 0;
}

.theorem-box .theorem-title {
  font-weight: bold;
  color: #d96bc8;
  margin-bottom: 8px;
  font-size: 1.2rem;
}

.highlight-box {
  background: #fff8f8;
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.example-box {
  background: #f0f9ff;
  border-left: 4px solid #4a90d9;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.loss-matrix {
  margin: 20px auto;
  border-collapse: collapse;
  font-family: monospace;
  max-width: 600px;
}

.loss-matrix th,
.loss-matrix td {
  padding: 12px 16px;
  border: 2px solid #f093fb;
  text-align: center;
  min-width: 80px;
}

.loss-matrix th {
  background: #fef5ff;
  font-weight: bold;
  color: #d96bc8;
}

.loss-matrix .row-label {
  background: #f8f9fa;
  font-weight: bold;
}
</style>

<!-- MathJax 配置 -->
<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$']],
    displayMath: [['$$', '$$']],
    tags: 'ams'
  }
};
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async=""></script>

<hr />

<h2 id="一句話解釋">一句話解釋</h2>

<div class="oneliner">
  <p>用 Bayes’ Rule 計算 posterior，再依據 loss function 做出期望風險最小的決策。</p>
</div>

<hr />

<h2 id="隨機變數與機率分佈">隨機變數與機率分佈</h2>

<div class="section">
  <div class="section-label blue">機率建模</div>

  <h3 id="section">基本假設</h3>

  <div class="math-block">

資料 $x$ 視為從某個機率分佈 $p(x)$ 抽出的隨機變數。

<strong>目標：</strong>
- 從樣本推論出 $p(x)$ 的性質
- 對新觀察做預測或決策

</div>

  <h3 id="section-1">為什麼要用機率？</h3>

  <ol>
    <li><strong>不確定性建模：</strong> 現實世界充滿雜訊和未知因素</li>
    <li><strong>有限資料：</strong> 無法觀察所有可能的情況</li>
    <li><strong>模型不完美：</strong> 真實關係可能太複雜，只能用機率近似</li>
  </ol>

  <div class="highlight-box">
    <p><strong>機率觀點：</strong><br />
分類不是找「絕對正確」的答案，而是找「最可能」的答案。</p>
  </div>

</div>

<hr />

<h2 id="bayesian-classification">Bayesian Classification</h2>

<div class="section">
  <div class="section-label green">後驗機率</div>

  <h3 id="bayes-rule-">Bayes’ Rule 回顧</h3>

  <div class="math-block">

$$

p(C_k \mid x) = \frac{p(x \mid C_k)\, p(C_k)}{p(x)}

$$

<strong>各項意義：</strong>
- $p(C_k)$：**Prior（先驗機率）** — class $C_k$ 出現的機率
- $p(x \mid C_k)$：**Class-conditional density（likelihood）** — 給定 $C_k$ 時觀察到 $x$ 的機率
- $p(C_k \mid x)$：**Posterior（後驗機率）** — 觀察到 $x$ 後，$C_k$ 的機率
- $p(x)$：**Evidence** — $p(x) = \sum_k p(x \mid C_k) p(C_k)$

</div>

  <h3 id="section-2">決策規則</h3>

  <div class="theorem-box">
<div class="theorem-title">Bayesian Decision Rule</div>

選擇 posterior 最大的 class：

$$

\hat{C} = \arg\max_{k} p(C_k \mid x)

$$

等價於（分母 $p(x)$ 相同，可忽略）：

$$

\hat{C} = \arg\max_{k} p(x \mid C_k)\, p(C_k)

$$

</div>

  <h3 id="spam-detection">實例：Spam Detection</h3>

  <div class="example-box">
    <p><strong>問題：</strong>郵件包含「free」這個字，是垃圾郵件嗎？<br /><br /></p>

    <p><strong>已知：</strong></p>
    <ul>
      <li>$p(\text{spam}) = 0.3$（prior：30% 郵件是垃圾）</li>
      <li>$p(\text{free} \mid \text{spam}) = 0.8$（垃圾郵件 80% 含「free」）</li>
      <li>$p(\text{free} \mid \text{ham}) = 0.1$（正常郵件 10% 含「free」）</li>
    </ul>

    <p><strong>計算 posterior：</strong></p>

\[\begin{align}
p(\text{spam} \mid \text{free}) &amp;= \frac{p(\text{free} \mid \text{spam}) \, p(\text{spam})}{p(\text{free})} \\
&amp;= \frac{0.8 \times 0.3}{0.8 \times 0.3 + 0.1 \times 0.7} \\
&amp;= \frac{0.24}{0.24 + 0.07} = \frac{0.24}{0.31} \approx 0.774
\end{align}\]

    <p><strong>結論：</strong>77.4% 機率是垃圾郵件，應標記為 spam。</p>
  </div>

</div>

<hr />

<h2 id="losses-and-risks">Losses and Risks</h2>

<div class="section">
  <div class="section-label purple">決策代價</div>

  <h3 id="loss">為什麼需要 Loss？</h3>

  <div class="highlight-box">
    <p>現實中，不同類型的錯誤<strong>代價不同</strong>。<br /><br />
例：醫療診斷</p>
    <ul>
  <li>漏診（false negative）→ 病人錯過治療，代價極高</li>
  <li>誤診（false positive）→ 多做檢查，代價較低</li>
</ul>
  </div>

  <h3 id="loss-matrix">Loss Matrix</h3>

  <div class="math-block">

$\lambda_{ij}$：真實 class 為 $C_j$，但採取 action $\alpha_i$ 所造成的 loss。

<table class="loss-matrix">
  <tr>
    <th></th>
    <th>真實 $C_1$</th>
    <th>真實 $C_2$</th>
  </tr>
  <tr>
    <th class="row-label">預測 $C_1$</th>
    <td>$\lambda_{11}$</td>
    <td>$\lambda_{12}$</td>
  </tr>
  <tr>
    <th class="row-label">預測 $C_2$</th>
    <td>$\lambda_{21}$</td>
    <td>$\lambda_{22}$</td>
  </tr>
</table>

通常對角線（正確分類）loss 為 0：$\lambda_{11} = \lambda_{22} = 0$

</div>

  <h3 id="expected-risk">Expected Risk</h3>

  <div class="theorem-box">
<div class="theorem-title">Definition: Expected Risk</div>

採取 action $\alpha_i$ 的期望風險：

$$

R(\alpha_i \mid x) = \sum_{k=1}^K \lambda_{ik}\, p(C_k \mid x)

$$

<strong>最優決策：</strong>選擇期望風險最小的 action

$$

\hat{\alpha} = \arg\min_{\alpha_i} R(\alpha_i \mid x)

$$

</div>

  <h3 id="loss-1">特例：0/1 Loss</h3>

  <div class="math-block">

<strong>0/1 loss：</strong>

$$

\lambda_{ik} = \begin{cases}
0 &amp; \text{if } i = k \\
1 &amp; \text{if } i \neq k
\end{cases}
$$

<strong>Expected risk：</strong>

$$

R(\alpha_i \mid x) = \sum_{k \neq i} p(C_k \mid x) = 1 - p(C_i \mid x)

$$

**最小化 risk 等價於最大化 posterior！**

$$

\arg\min_i R(\alpha_i \mid x) = \arg\max_i p(C_i \mid x)

$$

</div>

  <div class="highlight-box">
    <p><strong>結論：</strong><br />
0/1 loss 下，Bayesian decision rule 就是選 posterior 最大的 class。</p>
  </div>

  <h3 id="loss-2">例：醫療診斷的 Loss</h3>

  <div class="example-box">
    <p><strong>設定：</strong></p>
    <ul>
      <li>$C_1$：有病，$C_2$：無病</li>
      <li>$\alpha_1$：診斷為有病（治療），$\alpha_2$：診斷為無病（不治療）</li>
    </ul>

    <p><strong>Loss matrix：</strong></p>

    <table class="loss-matrix">
  <tr>
    <th></th>
    <th>真實有病</th>
    <th>真實無病</th>
  </tr>
  <tr>
    <th class="row-label">診斷有病</th>
    <td>0</td>
    <td>1</td>
  </tr>
  <tr>
    <th class="row-label">診斷無病</th>
    <td>10</td>
    <td>0</td>
  </tr>
</table>

    <ul>
      <li>正確診斷：loss = 0</li>
      <li>誤診（false positive）：loss = 1（多做治療）</li>
      <li>漏診（false negative）：loss = 10（錯過治療，嚴重！）</li>
    </ul>

    <p><strong>Expected risks：</strong></p>

\[\begin{align}
R(\alpha_1 \mid x) &amp;= 0 \cdot p(C_1 \mid x) + 1 \cdot p(C_2 \mid x) = p(C_2 \mid x) \\
R(\alpha_2 \mid x) &amp;= 10 \cdot p(C_1 \mid x) + 0 \cdot p(C_2 \mid x) = 10\, p(C_1 \mid x)
\end{align}\]

    <p><strong>決策：</strong>選 $\alpha_1$（診斷有病）當</p>

    <p>$$</p>

    <p>p(C_2 \mid x) &lt; 10\, p(C_1 \mid x)</p>

    <p>\(\)
\Rightarrow p(C_1 \mid x) &gt; \frac{1}{11} \approx 0.09</p>

\[只要有病機率 &gt; 9%，就該治療！（比 0/1 loss 的 50% 低很多）
&lt;/div&gt;

### Reject Option

&lt;div class="highlight-box" markdown="1"&gt;
&lt;strong&gt;Reject Option（拒絕分類）：&lt;/strong&gt;&lt;br&gt;
當所有 class 的 posterior 都低於閾值 $\theta$ 時，選擇**拒答**。&lt;br&gt;&lt;br&gt;
&lt;strong&gt;應用場景：&lt;/strong&gt;
&lt;ul&gt;
  &lt;li&gt;人工審核系統：不確定時交給專家&lt;/li&gt;
  &lt;li&gt;金融風控：拒絕高風險交易&lt;/li&gt;
  &lt;li&gt;醫療診斷：建議進一步檢查&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;div class="math-block"&gt;

&lt;strong&gt;決策規則（with reject）：&lt;/strong&gt;\]

    <p>\hat{C} = \begin{cases}
\arg\max_k p(C_k \mid x) &amp; \text{if } \max_k p(C_k \mid x) \geq \theta <br />
\text{reject} &amp; \text{otherwise}
\end{cases}
$$</p>

  </div>

</div>

<hr />

<h2 id="discriminant-functions">Discriminant Functions</h2>

<div class="section">
  <div class="section-label red">實作方式</div>

  <h3 id="section-3">定義</h3>

  <div class="math-block">

將分類實作為 **discriminant function** $g_k(x)$：

$$

\hat{C} = \arg\max_k g_k(x)

$$

<strong>常見選擇：</strong>

**選項 1：直接用 posterior**

$$

g_k(x) = p(C_k \mid x)

$$

**選項 2：用 log-posterior（避免數值下溢）**

$$

g_k(x) = \log p(C_k \mid x) = \log p(x \mid C_k) + \log p(C_k) - \log p(x)

$$

由於 $\log p(x)$ 對所有 $k$ 相同，可簡化為：

$$

g_k(x) = \log p(x \mid C_k) + \log p(C_k)

$$

</div>

  <h3 id="discriminant-function">為什麼用 Discriminant Function？</h3>

  <ol>
    <li><strong>計算效率：</strong> 不需要計算 $p(x)$（所有 class 共用）</li>
    <li><strong>數值穩定：</strong> log 避免機率乘積的下溢問題</li>
    <li><strong>簡化模型：</strong> 很多模型直接學習 $g_k(x)$，不經過 posterior</li>
  </ol>

</div>

<hr />

<h2 id="decision-regions--boundaries">Decision Regions &amp; Boundaries</h2>

<div class="section">
  <div class="section-label blue">幾何觀點</div>

  <h3 id="section-4">定義</h3>

  <div class="math-block">

<strong>Decision Region $\mathcal{R}_k$：</strong>被分到 class $C_k$ 的輸入空間區域

$$

\mathcal{R}_k = \{x : g_k(x) &gt; g_j(x), \forall j \neq k\}

$$

<strong>Decision Boundary：</strong>不同 decision region 的交界

$$

\{x : g_i(x) = g_j(x)\}

$$

</div>

  <h3 id="section-5">幾何直觀</h3>

  <div class="highlight-box">
    <ul>
      <li><strong>Decision region：</strong>輸入空間被分割成多個區域</li>
      <li><strong>Decision boundary：</strong>多個 $g_k(x)$ 值相等的地方</li>
      <li>Boundary 上的點是「最難分類」的點，多個 class 的機率相近</li>
    </ul>
  </div>

  <h3 id="gaussian-class">例：兩個 Gaussian Class</h3>

  <div class="example-box">
    <p><strong>設定：</strong></p>
    <ul>
      <li>$p(x \mid C_1) = \mathcal{N}(\mu_1, \Sigma)$</li>
      <li>$p(x \mid C_2) = \mathcal{N}(\mu_2, \Sigma)$（相同 covariance）</li>
      <li>$p(C_1) = p(C_2) = 0.5$</li>
    </ul>

    <p><strong>Discriminant function：</strong></p>

\[\begin{align}
g_k(x) &amp;= \log p(x \mid C_k) + \log p(C_k) \\
&amp;= -\frac{1}{2}(x - \mu_k)^T \Sigma^{-1} (x - \mu_k) + \text{const}
\end{align}\]

    <p><strong>Decision boundary：</strong>$g_1(x) = g_2(x)$</p>

    <p>經過化簡，這是一條<strong>直線</strong>（linear boundary）！</p>

\[w^T x + w_0 = 0\]

    <p>其中 $w = \Sigma^{-1}(\mu_1 - \mu_2)$</p>

    <p><strong>結論：</strong>相同 covariance 的 Gaussian → linear decision boundary</p>
  </div>

  <h3 id="covariance">不同 Covariance</h3>

  <div class="math-block">

若 $C_1$ 和 $C_2$ 有不同的 $\Sigma_1, \Sigma_2$，decision boundary 是<strong>二次曲線</strong>（quadratic）。

這導致：
- Linear Discriminant Analysis (LDA)：假設相同 covariance
- Quadratic Discriminant Analysis (QDA)：允許不同 covariance

</div>

</div>

<hr />

<h2 id="總結">總結</h2>

<div class="section">

  <p><strong>Bayesian Decision Theory 的核心：</strong></p>
  <ol>
    <li>用 Bayes’ Rule 計算 posterior $p(C_k \mid x)$</li>
    <li>定義 loss function $\lambda_{ik}$ 反映錯誤代價</li>
    <li>計算 expected risk $R(\alpha_i \mid x)$</li>
    <li>選擇 risk 最小的 action</li>
  </ol>

  <p><strong>實作方式：</strong></p>
  <ul>
    <li>Discriminant function $g_k(x)$</li>
    <li>Decision regions 與 boundaries</li>
    <li>Reject option 處理不確定性</li>
  </ul>

  <p><strong>下一步：</strong></p>
  <ul>
    <li>Parametric Methods：如何估計 $p(x \mid C_k)$（Gaussian, MLE, MAP）</li>
    <li>Non-parametric Methods：KNN, Kernel Density Estimation</li>
    <li>Discriminative Models：直接學習 $p(C_k \mid x)$（Logistic Regression, SVM）</li>
  </ul>

</div>

<hr />

<h2 id="參考資料">參考資料</h2>

<ul>
  <li>Bishop, <em>Pattern Recognition and Machine Learning</em>, Chapter 1.5</li>
  <li>Duda, Hart &amp; Stork, <em>Pattern Classification</em>, Chapter 2</li>
  <li>Murphy, <em>Machine Learning: A Probabilistic Perspective</em>, Chapter 5</li>
</ul>]]></content><author><name>Chien-Chih Tseng</name></author><category term="機器學習" /><category term="Bayesian" /><category term="Decision-Theory" /><category term="Discriminant-Function" /><category term="Risk" /><summary type="html"><![CDATA[Bayesian 分類、Loss 與 Risk、Discriminant Functions、Decision Boundaries]]></summary></entry><entry><title type="html">Ch02: Supervised Learning</title><link href="https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/supervised-learning.html" rel="alternate" type="text/html" title="Ch02: Supervised Learning" /><published>2026-03-16T03:00:00+00:00</published><updated>2026-03-16T03:00:00+00:00</updated><id>https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/supervised-learning</id><content type="html" xml:base="https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/supervised-learning.html"><![CDATA[<style>
:root {
  --accent: #f093fb;
  --accent-light: #fef5ff;
  --border: #f5e5f0;
  --text-muted: #6b6b65;
}

.oneliner {
  background: var(--accent-light);
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 32px 0;
  font-size: 1.05rem;
  font-style: italic;
  color: #8b2c7a;
}

.section {
  margin: 40px 0;
}

.section-label {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-family: monospace;
  font-size: 11px;
  font-weight: bold;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 14px;
}

.section-label::before {
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  background: #d4a847;
}

.section-label.blue::before { background: #4a90d9; }
.section-label.green::before { background: #5aaa72; }
.section-label.purple::before { background: #d96bc8; }
.section-label.red::before { background: #d96b5a; }

.math-block {
  background: #fafaf8;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 16px 20px;
  margin: 16px 0;
  overflow-x: auto;
}

.theorem-box {
  background: #fef5ff;
  border: 2px solid #d96bc8;
  border-radius: 8px;
  padding: 16px 20px;
  margin: 20px 0;
}

.theorem-box .theorem-title {
  font-weight: bold;
  color: #d96bc8;
  margin-bottom: 8px;
  font-size: 1.2rem;
}

.highlight-box {
  background: #fff8f8;
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.warning-box {
  background: #fff8e6;
  border-left: 4px solid #d4a847;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.example-box {
  background: #f0f9ff;
  border-left: 4px solid #4a90d9;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}
</style>

<!-- MathJax 配置 -->
<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$']],
    displayMath: [['$$', '$$']],
    tags: 'ams'
  }
};
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async=""></script>

<hr />

<h2 id="一句話解釋">一句話解釋</h2>

<div class="oneliner">
  <p>從有標註的資料中學習 input → output 的映射，並期望在未見資料上表現良好。</p>
</div>

<hr />

<h2 id="基本框架">基本框架</h2>

<div class="section">
  <div class="section-label blue">核心概念</div>

  <h3 id="section">監督式學習的組成</h3>

  <div class="math-block">

<strong>給定：</strong>
- 訓練資料 $D = \{(x_1, y_1), (x_2, y_2), \ldots, (x_N, y_N)\}$
- $x_i \in \mathcal{X}$：輸入空間（input space）
- $y_i \in \mathcal{Y}$：輸出空間（output space）

<strong>目標：</strong>
找一個 hypothesis $h: \mathcal{X} \to \mathcal{Y}$，使得：
- $h(x) \approx y$ 對訓練資料成立
- $h(x)$ 在**未見資料**上也表現良好（generalization）

</div>

  <h3 id="section-1">三個關鍵決策</h3>

  <table style="width: 100%; border-collapse: collapse; margin: 16px 0;">
  <thead>
    <tr style="background: #f5f5f3;">
      <th style="padding: 12px; border: 1px solid #e5e5e0; width: 30%;">決策</th>
      <th style="padding: 12px; border: 1px solid #e5e5e0;">說明</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">**1. Model（Hypothesis Space H）**</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">定義候選模型的範圍<br />例：線性模型、決策樹、神經網路</td>
    </tr>
    <tr>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">**2. Loss Function**</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">如何衡量預測錯誤<br />例：0/1 loss、squared loss、cross-entropy</td>
    </tr>
    <tr>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">**3. Optimization Algorithm**</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">如何找到最佳 h<br />例：梯度下降、EM algorithm</td>
    </tr>
  </tbody>
</table>

  <h3 id="hypothesis-space">Hypothesis Space</h3>

  <div class="highlight-box">
    <p><strong>Hypothesis h：</strong>候選的「機器」（模型），從 hypothesis space $\mathcal{H}$ 中挑選。<br /><br />
$\mathcal{H}$ 的選擇決定了模型的<strong>表達能力</strong>和<strong>學習難度</strong>。</p>
  </div>

</div>

<hr />

<h2 id="誤差類型">誤差類型</h2>

<div class="section">
  <div class="section-label green">Training vs. Generalization</div>

  <div class="math-block">

<strong>Training Error（經驗風險）：</strong>

$$

\hat{R}(h) = \frac{1}{N} \sum_{i=1}^N \mathbb{1}[h(x_i) \neq y_i]

$$
$h$ 在訓練集上的錯誤率。

<strong>Generalization Error（真實風險）：</strong>

$$

R(h) = \mathbb{E}_{(x,y) \sim \mathcal{D}}[\mathbb{1}[h(x) \neq y]]

$$
$h$ 在所有可能資料上的真實錯誤率（來自未知的真實分佈 $\mathcal{D}$）。

</div>

  <h3 id="section-2">核心問題</h3>

  <div class="warning-box">
    <p><strong>⚠️ 關鍵挑戰：</strong><br />
Training error 低 $\neq$ Generalization error 低<br /><br />
<strong>Overfitting：</strong>模型在訓練資料上表現完美，但在新資料上表現差。</p>
  </div>

  <h3 id="overfitting">為什麼會 Overfitting？</h3>

  <ol>
    <li><strong>模型太複雜：</strong> $\mathcal{H}$ 太大，能「記住」訓練資料的雜訊</li>
    <li><strong>訓練資料太少：</strong> 無法充分代表真實分佈</li>
    <li><strong>訓練時間太長：</strong> 過度優化訓練誤差</li>
  </ol>

</div>

<hr />

<h2 id="vc-dimension">VC Dimension</h2>

<div class="section">
  <div class="section-label purple">模型複雜度</div>

  <h3 id="section-3">定義</h3>

  <div class="theorem-box">
<div class="theorem-title">Definition: VC Dimension</div>

<strong>Vapnik-Chervonenkis Dimension** 衡量 hypothesis class $\mathcal{H}$ 的**複雜度（表達能力）</strong>。

<strong>Shattering：</strong> 若 $\mathcal{H}$ 能對某個大小為 $N$ 的資料集實現**所有可能的 labeling**（$2^N$ 種），
稱 $\mathcal{H}$ **shatters** 這個資料集。

$$

VC(\mathcal{H}) = \max\{N : \mathcal{H} \text{ can shatter some dataset of size } N\}

$$

</div>

  <h3 id="section-4">直觀理解</h3>

  <div class="highlight-box">
    <p>VC dimension 是 $\mathcal{H}$ 能完美記住（shatter）的<strong>最大資料集大小</strong>。<br /><br />
VC dimension 越大 → 模型越複雜 → 表達能力越強 → 需要更多資料才能學好。</p>
  </div>

  <h3 id="section-5">經典例子</h3>

  <div class="example-box">
    <p><strong>例 1：平面上的直線分類器</strong><br /><br /></p>

    <p>$\mathcal{H} = {h(x, y) = \text{sign}(ax + by + c)}$</p>

    <p><strong>問：</strong>VC dimension 是多少？</p>

    <p><strong>答：</strong>$VC(\mathcal{H}) = 3$</p>

    <p><strong>證明概念：</strong></p>
    <ul>
      <li>存在 3 個點，可以被直線 shatter（任意 $2^3 = 8$ 種 labeling 都能分開）</li>
      <li>任意 4 個點，至少有一種 labeling 無法被直線分開（XOR 問題）</li>
    </ul>

    <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c0/VC_dimension.svg/400px-VC_dimension.svg.png" alt="VC Dimension 示意" style="max-width: 100%; margin: 16px 0;" /></p>
  </div>

  <div class="example-box">
    <p><strong>例 2：$\mathbb{R}^n$ 上的線性分類器</strong><br /><br /></p>

    <p>$\mathcal{H} = {h(x) = \text{sign}(w^T x + b)}$，其中 $x \in \mathbb{R}^n$</p>

\[VC(\mathcal{H}) = n + 1\]

    <p><strong>意義：</strong>參數數量 = $n + 1$（$w$ 有 $n$ 個元素 + bias $b$）</p>

    <p>一般來說，參數數量可以作為 VC dimension 的粗略估計。</p>
  </div>

  <h3 id="vc-dimension--generalization">VC Dimension 與 Generalization</h3>

  <div class="theorem-box">
<div class="theorem-title">Theorem: VC Generalization Bound</div>

若 $VC(\mathcal{H}) = d$，則以機率至少 $1 - \delta$：

$$

R(h) \leq \hat{R}(h) + \sqrt{\frac{d \log(N/d) + \log(1/\delta)}{N}}

$$

<strong>意義：</strong>
- Generalization error 由 training error + 複雜度懲罰 組成
- $d$ 越大 → 複雜度懲罰越大 → 需要更多資料
- $N$ 越大 → 複雜度懲罰越小 → generalization 越好

</div>

</div>

<hr />

<h2 id="pac-learning">PAC Learning</h2>

<div class="section">
  <div class="section-label red">可學習性理論</div>

  <h3 id="section-6">定義</h3>

  <div class="theorem-box">
<div class="theorem-title">Definition: PAC Learning</div>

**Probably Approximately Correct Learning**

給定：
- 誤差上限 $\epsilon$（**Approximately** Correct）
- 失敗機率上限 $\delta$（**Probably**）

若存在演算法，使用 $N$ 個訓練樣本後，以機率至少 $1 - \delta$ 輸出 hypothesis $h$ 滿足：

$$

R(h) \leq \epsilon

$$

則稱 $\mathcal{H}$ 是 **PAC learnable**。

</div>

  <h3 id="sample-complexity">Sample Complexity</h3>

  <p><strong>問：需要多少訓練資料 $N$？</strong></p>

  <div class="theorem-box">
<div class="theorem-title">Theorem: Haussler (有限 Hypothesis Space)</div>

若 $|\mathcal{H}| &lt; \infty$（有限個 hypothesis），則：

$$

N \geq \frac{1}{\epsilon} \left( \ln |\mathcal{H}| + \ln \frac{1}{\delta} \right)

$$

保證以機率 $1 - \delta$，generalization error $\leq \epsilon$。

</div>

  <h3 id="section-7">三個變數的關係</h3>

  <div class="math-block">

**1. $\epsilon$ 越小（要求越精確）**

$$

N \propto \frac{1}{\epsilon}

$$

需要更多資料

**2. $\delta$ 越小（要求更有把握）**

$$

N \propto \ln \frac{1}{\delta}

$$

需要更多資料（但只是對數成長）

**3. $|\mathcal{H}|$ 越大（模型越複雜）**

$$

N \propto \ln |\mathcal{H}|

$$

需要更多資料

</div>

  <h3 id="section-8">實務意涵</h3>

  <div class="highlight-box">
    <p><strong>Occam’s Razor（奧坎剃刀原則）：</strong><br />
在表現相同時，偏好<strong>較簡單</strong>的模型。<br /><br />
<strong>原因：</strong></p>
    <ul>
  <li>簡單模型需要較少資料</li>
  <li>泛化能力更好</li>
  <li>更易理解和維護</li>
</ul>
  </div>

  <div class="warning-box">
    <p><strong>⚠️ No Free Lunch Theorem：</strong><br />
沒有一個演算法在所有問題上都最優。<br /><br />
必須根據<strong>問題特性</strong>和<strong>先驗知識</strong>選擇合適的 $\mathcal{H}$。</p>
  </div>

</div>

<hr />

<h2 id="regression-vs-classification">Regression vs. Classification</h2>

<div class="section">
  <div class="section-label blue">兩種主要任務</div>

  <table style="width: 100%; border-collapse: collapse; margin: 16px 0;">
  <thead>
    <tr style="background: #f5f5f3;">
      <th style="padding: 12px; border: 1px solid #e5e5e0;"></th>
      <th style="padding: 12px; border: 1px solid #e5e5e0;">Classification</th>
      <th style="padding: 12px; border: 1px solid #e5e5e0;">Regression</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">**Output 空間**</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">離散（class label）</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">連續（實數）</td>
    </tr>
    <tr>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">**例子**</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">垃圾郵件偵測、圖像識別</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">房價預測、溫度預測</td>
    </tr>
    <tr>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">**常見 Loss**</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">0/1 loss, cross-entropy</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">Squared loss, absolute loss</td>
    </tr>
    <tr>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">**評估指標**</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">Accuracy, Precision, Recall, F1</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">MSE, MAE, $R^2$</td>
    </tr>
  </tbody>
</table>

  <p><strong>共同點：</strong></p>
  <ul>
    <li>都屬於 supervised learning</li>
    <li>都需要標註資料</li>
    <li>都面臨 overfitting 問題</li>
    <li>都可用 VC dimension 和 PAC learning 理論分析</li>
  </ul>

</div>

<hr />

<h2 id="總結">總結</h2>

<div class="section">

  <p><strong>監督式學習的核心：</strong></p>
  <ol>
    <li>從 hypothesis space $\mathcal{H}$ 中選擇最佳 $h$</li>
    <li>平衡 training error 與 generalization error</li>
    <li>模型複雜度與資料量的權衡</li>
  </ol>

  <p><strong>理論工具：</strong></p>
  <ul>
    <li><strong>VC Dimension：</strong> 衡量模型複雜度</li>
    <li><strong>PAC Learning：</strong> 分析樣本複雜度</li>
    <li><strong>Occam’s Razor：</strong> 偏好簡單模型</li>
  </ul>

  <p><strong>下一步：</strong></p>
  <ul>
    <li>Bayesian Decision Theory：如何做最優決策</li>
    <li>具體演算法：Linear Models, SVM, Decision Trees 等</li>
  </ul>

</div>

<hr />

<h2 id="參考資料">參考資料</h2>

<ul>
  <li>Shalev-Shwartz &amp; Ben-David, <em>Understanding Machine Learning</em>, Chapters 2-6</li>
  <li>Abu-Mostafa et al., <em>Learning from Data</em>, Chapters 1-2</li>
  <li>Vapnik, <em>The Nature of Statistical Learning Theory</em></li>
</ul>

<h3 id="延伸影片">延伸影片</h3>

<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; margin: 20px 0;">
  <iframe style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" src="https://www.youtube.com/embed/EmSVek5QMnE" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe>
</div>]]></content><author><name>Chien-Chih Tseng</name></author><category term="機器學習" /><category term="Supervised" /><category term="Hypothesis" /><category term="VC-Dimension" /><category term="PAC-Learning" /><summary type="html"><![CDATA[監督式學習框架、Hypothesis Space、VC Dimension、PAC Learning 理論]]></summary></entry><entry><title type="html">Chernoff Bound</title><link href="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/chernoff-bound.html" rel="alternate" type="text/html" title="Chernoff Bound" /><published>2026-03-16T02:00:00+00:00</published><updated>2026-03-16T02:00:00+00:00</updated><id>https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/chernoff-bound</id><content type="html" xml:base="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/chernoff-bound.html"><![CDATA[<style>
:root {
  --accent: #667eea;
  --accent-light: #eef3fb;
  --border: #e5e5e0;
  --text-muted: #6b6b65;
}

.oneliner {
  background: var(--accent-light);
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 32px 0;
  font-size: 1.05rem;
  font-style: italic;
  color: #1a3a6b;
}

.section {
  margin: 40px 0;
}

.section-label {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-family: monospace;
  font-size: 11px;
  font-weight: bold;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 14px;
}

.section-label::before {
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  background: #d4a847;
}

.section-label.blue::before { background: #4a90d9; }
.section-label.green::before { background: #5aaa72; }
.section-label.purple::before { background: #9b72c8; }

.math-block {
  background: #fafaf8;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 16px 20px;
  margin: 16px 0;
  overflow-x: auto;
}

.math-step {
  display: flex;
  gap: 16px;
  align-items: baseline;
  padding: 6px 0;
  border-bottom: 1px solid #f0f0ec;
}

.math-step:last-child { border-bottom: none; }

.math-step-num {
  font-family: monospace;
  font-size: 12px;
  color: var(--text-muted);
  min-width: 20px;
}

.math-step-note {
  font-size: 13px;
  color: var(--text-muted);
  font-style: italic;
  margin-left: auto;
  padding-left: 16px;
  white-space: nowrap;
}

.conditions {
  list-style: none;
  padding: 0;
}

.conditions li {
  padding: 8px 0;
  border-bottom: 1px solid var(--border);
}

.conditions li:last-child { border-bottom: none; }

.cond-check { color: #5aaa72; font-weight: bold; margin-right: 8px; }
.cond-cross { color: #d96b5a; font-weight: bold; margin-right: 8px; }

.related-links {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  margin-top: 16px;
}

.link-card {
  background: white;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 12px 14px;
  text-decoration: none;
  color: inherit;
  transition: all 0.15s;
}

.link-card:hover {
  border-color: var(--accent);
  background: var(--accent-light);
}

.link-card-title {
  font-weight: bold;
  color: var(--accent);
  margin-bottom: 4px;
}

.link-card-desc {
  font-size: 0.85rem;
  color: var(--text-muted);
}
</style>

<!-- MathJax 配置 -->
<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$']],
    displayMath: [['$$', '$$']],
    tags: 'ams'
  }
};
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async=""></script>

<hr />

<h2 id="一句話解釋">一句話解釋</h2>

<div class="oneliner">
  <p>對獨立 0/1 隨機變數的和，給出比 Chebyshev 更緊的尾部機率上界。</p>
</div>

<hr />

<h2 id="直覺理解">直覺理解</h2>

<div class="section">
  <div class="section-label blue">直覺理解</div>

  <p>Markov 和 Chebyshev 只用到期望值或變異數，丟掉了大量資訊。Chernoff 的想法是：對任意 $\lambda &gt; 0$，把事件 ${X \geq t}$ 換成 ${e^{\lambda X} \geq e^{\lambda t}}$，再對 $e^{\lambda X}$ 用 Markov。</p>

  <p>指數函數會把尾部「放大」，讓上界隨 $t$ 指數衰減，而不是像 Chebyshev 的多項式衰減。最後再對 $\lambda$ 取最優值，讓上界盡可能緊。</p>

</div>

<hr />

<h2 id="數學推導">數學推導</h2>

<div class="section">
  <div class="section-label">數學推導</div>

  <h3 id="section">設定</h3>

  <p>令 $X_1, \dots, X_n$ 獨立，$X_i \in {0,1}$，$\Pr[X_i=1]=p_i$。令 $X = \sum X_i$，$\mu = \mathbb{E}[X]$。</p>

  <h3 id="section-1">推導步驟</h3>

  <div class="math-block">
<div class="math-step">
  <span class="math-step-num">1</span>
  <span>$$\Pr[X \geq (1+\delta)\mu] = \Pr\!\left[e^{\lambda X} \geq e^{\lambda(1+\delta)\mu}\right]$$</span>
  <span class="math-step-note">改寫事件</span>
</div>
<div class="math-step">
  <span class="math-step-num">2</span>
  <span>$$\leq \frac{\mathbb{E}[e^{\lambda X}]}{e^{\lambda(1+\delta)\mu}}$$</span>
  <span class="math-step-note">Markov 不等式</span>
</div>
<div class="math-step">
  <span class="math-step-num">3</span>
  <span>$$= \frac{\prod_i \mathbb{E}[e^{\lambda X_i}]}{e^{\lambda(1+\delta)\mu}}$$</span>
  <span class="math-step-note">獨立性 → MGF 可分解</span>
</div>
<div class="math-step">
  <span class="math-step-num">4</span>
  <span>$$\leq \left(\frac{e^\delta}{(1+\delta)^{1+\delta}}\right)^\mu$$</span>
  <span class="math-step-note">取最優 λ，化簡</span>
</div>
</div>

  <h3 id="delta-leq-1">常用形式（$\delta \leq 1$）</h3>

  <div class="math-block">

<strong>上尾（Upper Tail）：</strong>

$$\Pr[X \geq (1+\delta)\mu] \leq e^{-\mu\delta^2/3}$$

<strong>下尾（Lower Tail）：</strong>

$$\Pr[X \leq (1-\delta)\mu] \leq e^{-\mu\delta^2/2}$$

</div>

</div>

<hr />

<h2 id="前提條件--適用範圍">前提條件 / 適用範圍</h2>

<div class="section">
  <div class="section-label green">前提條件 / 適用範圍</div>

  <ul class="conditions">
  <li><span class="cond-check">✓</span> $X_i$ 彼此獨立</li>
  <li><span class="cond-check">✓</span> $X_i \in \{0,1\}$（或有界）</li>
  <li><span class="cond-check">✓</span> $\delta \in (0,1]$（常用形式）</li>
  <li><span class="cond-cross">✗</span> $X_i$ 有相關性時不能直接套用</li>
  <li><span class="cond-cross">✗</span> 無界的連續分佈需改用 Hoeffding 或 Bernstein</li>
</ul>

</div>

<hr />

<h2 id="範例硬幣投擲">範例：硬幣投擲</h2>

<div class="section">

  <h3 id="section-2">問題</h3>

  <p>投擲 $n=1000$ 次公平硬幣，出現正面的次數 $X$ 超過 $600$ 次的機率上界？</p>

  <h3 id="section-3">解答</h3>

  <ul>
    <li>$\mu = np = 1000 \times 0.5 = 500$</li>
    <li>要求 $\Pr[X \geq 600] = \Pr[X \geq (1+0.2) \times 500]$</li>
    <li>這裡 $\delta = 0.2$</li>
  </ul>

  <p>使用 Chernoff Bound（上尾）：</p>

\[\Pr[X \geq 600] \leq e^{-500 \times (0.2)^2 / 3} = e^{-500 \times 0.04/3} \approx e^{-6.67} \approx 0.0013\]

  <p><strong>結論</strong>：超過 600 次的機率小於 0.13%，非常不可能發生。</p>

  <h3 id="chebyshev-">與 Chebyshev 比較</h3>

  <p>Chebyshev 給出：</p>

\[\Pr[|X - 500| \geq 100] \leq \frac{\text{Var}(X)}{100^2} = \frac{250}{10000} = 0.025\]

  <p>Chernoff 的上界（$\approx 0.0013$）遠比 Chebyshev（$\approx 0.025$）緊！</p>

</div>

<hr />

<h2 id="與其他概念的關係">與其他概念的關係</h2>

<div class="section">
  <div class="section-label purple">相關概念</div>

  <div class="related-links">
  <div class="link-card">
    <div class="link-card-title">Markov Inequality</div>
    <div class="link-card-desc">推導基礎，第一步就用到</div>
  </div>
  <div class="link-card">
    <div class="link-card-title">Chebyshev Inequality</div>
    <div class="link-card-desc">Chernoff 更緊，條件也更多</div>
  </div>
  <div class="link-card">
    <div class="link-card-title">MGF (Moment Generating Function)</div>
    <div class="link-card-desc">核心工具，獨立性讓 MGF 可分解</div>
  </div>
  <div class="link-card">
    <div class="link-card-title">Hoeffding Bound</div>
    <div class="link-card-desc">有界但非 0/1 的推廣版本</div>
  </div>
</div>

</div>

<hr />

<h2 id="參考資料">參考資料</h2>

<ul>
  <li>Mitzenmacher &amp; Upfal, <em>Probability and Computing</em></li>
  <li><a href="https://en.wikipedia.org/wiki/Chernoff_bound">Wikipedia: Chernoff Bound</a></li>
  <li>Lecture notes on Randomized Algorithms</li>
</ul>]]></content><author><name>Chien-Chih Tseng</name></author><category term="隨機演算法" /><category term="機率工具" /><category term="Concentration Inequalities" /><summary type="html"><![CDATA[對獨立 0/1 隨機變數的和，給出比 Chebyshev 更緊的尾部機率上界]]></summary></entry><entry><title type="html">Ch01: Introduction to Machine Learning</title><link href="https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/ml-intro.html" rel="alternate" type="text/html" title="Ch01: Introduction to Machine Learning" /><published>2026-03-16T02:00:00+00:00</published><updated>2026-03-16T02:00:00+00:00</updated><id>https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/ml-intro</id><content type="html" xml:base="https://xiaomingtseng.github.io/blog/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/2026/03/16/ml-intro.html"><![CDATA[<style>
:root {
  --accent: #f093fb;
  --accent-light: #fef5ff;
  --border: #f5e5f0;
  --text-muted: #6b6b65;
}

.oneliner {
  background: var(--accent-light);
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 32px 0;
  font-size: 1.05rem;
  font-style: italic;
  color: #8b2c7a;
}

.section {
  margin: 40px 0;
}

.section-label {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-family: monospace;
  font-size: 11px;
  font-weight: bold;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 14px;
}

.section-label::before {
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  background: #d4a847;
}

.section-label.blue::before { background: #4a90d9; }
.section-label.green::before { background: #5aaa72; }
.section-label.purple::before { background: #d96bc8; }
.section-label.red::before { background: #d96b5a; }

.math-block {
  background: #fafaf8;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 16px 20px;
  margin: 16px 0;
  overflow-x: auto;
}

.highlight-box {
  background: #fff8f8;
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.definition-box {
  background: #f0f9ff;
  border-left: 4px solid #4a90d9;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.type-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.type-card {
  background: #fafaf8;
  border: 2px solid var(--border);
  border-radius: 8px;
  padding: 16px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.type-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(240, 147, 251, 0.2);
}

.type-card h4 {
  color: var(--accent);
  margin-top: 0;
  margin-bottom: 8px;
}
</style>

<!-- MathJax 配置 -->
<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$']],
    displayMath: [['$$', '$$']],
    tags: 'ams'
  }
};
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async=""></script>

<hr />

<h2 id="一句話解釋">一句話解釋</h2>

<div class="oneliner">
  <p>讓電腦透過範例資料或過去經驗，自動優化某個 performance criterion。</p>
</div>

<hr />

<h2 id="什麼是機器學習">什麼是機器學習？</h2>

<div class="section">
  <div class="section-label blue">核心定義</div>

  <div class="definition-box">
    <p><strong>Machine Learning：</strong><br />
設計並執行程式，透過<strong>樣本資料</strong>或<strong>過去經驗</strong>來優化某個<strong>性能指標（performance criterion）</strong>的過程。</p>
  </div>

  <h3 id="section">核心元素</h3>

  <ul>
    <li><strong>核心工具：</strong> 統計與機率理論</li>
    <li><strong>核心任務：</strong> 從樣本做<strong>推論（inference）</strong></li>
    <li><strong>“Learning”：</strong> 執行程式來優化模型參數</li>
    <li><strong>“Model”：</strong> 對未來做預測，或從資料中獲取知識</li>
  </ul>

  <h3 id="section-1">與傳統編程的差異</h3>

  <table style="width: 100%; border-collapse: collapse; margin: 16px 0;">
  <thead>
    <tr style="background: #f5f5f3;">
      <th style="padding: 12px; border: 1px solid #e5e5e0;">傳統編程</th>
      <th style="padding: 12px; border: 1px solid #e5e5e0;">機器學習</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">人工設計規則</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">從資料中學習規則</td>
    </tr>
    <tr>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">規則明確、可解釋</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">可能是黑盒模型</td>
    </tr>
    <tr>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">適合規則清晰的問題</td>
      <td style="padding: 12px; border: 1px solid #e5e5e0;">適合規則複雜、難以明確描述的問題</td>
    </tr>
  </tbody>
</table>

</div>

<hr />

<h2 id="機器學習的主要類型">機器學習的主要類型</h2>

<div class="section">
  <div class="section-label green">分類方式</div>

  <div class="type-grid">

<div class="type-card">
<h4>Supervised Learning</h4>
<p><strong>訓練資料：</strong>有標準答案（label）</p>
<p><strong>目標：</strong>學習 input → output 的映射</p>
<p><strong>例子：</strong></p>
<ul>
  <li>分類（Classification）</li>
  <li>迴歸（Regression）</li>
</ul>
</div>

<div class="type-card">
<h4>Unsupervised Learning</h4>
<p><strong>訓練資料：</strong>**沒有** label</p>
<p><strong>目標：</strong>發現資料內在結構</p>
<p><strong>例子：</strong></p>
<ul>
  <li>聚類（Clustering）</li>
  <li>密度估計（Density Estimation）</li>
</ul>
</div>

<div class="type-card">
<h4>Reinforcement Learning</h4>
<p><strong>訓練方式：</strong>與環境互動</p>
<p><strong>目標：</strong>依據 reward/penalty 學習策略</p>
<p><strong>例子：</strong></p>
<ul>
  <li>遊戲 AI</li>
  <li>機器人控制</li>
</ul>
</div>

</div>

  <h3 id="section-2">其他學習類型</h3>

  <ul>
    <li><strong>Semisupervised Learning：</strong> 少量有 label + 大量無 label 資料</li>
    <li><strong>Self-supervised Learning：</strong> 從資料本身構造監督訊號</li>
    <li><strong>Federated Learning：</strong> 分散式學習，保護資料隱私</li>
    <li><strong>Transfer Learning：</strong> 將一個任務學到的知識遷移到另一個任務</li>
    <li><strong>Active Learning：</strong> 主動選擇最有價值的樣本進行標註</li>
  </ul>

</div>

<hr />

<h2 id="機器學習的核心議題">機器學習的核心議題</h2>

<div class="section">
  <div class="section-label purple">理論基礎</div>

  <h3 id="section-3">三個關鍵問題</h3>

  <div class="math-block">

**1. 什麼時候演算法能學得好？**
- Learnability（可學習性）
- 需要滿足什麼條件？

**2. Generalization（泛化能力）**
- 訓練好的模型能推廣到新資料嗎？
- 如何避免 overfitting？

**3. 樣本複雜度（Sample Complexity）**
- 需要多少資料才夠？
- 資料量與模型複雜度的關係？

</div>

  <h3 id="bias-variance-trade-off">Bias-Variance Trade-off</h3>

  <div class="highlight-box">
    <p><strong>核心衝突：</strong><br /></p>
    <ul>
      <li><strong>Bias（偏差）：</strong>模型太簡單，無法捕捉資料複雜性 → Underfitting<br /></li>
      <li><strong>Variance（變異）：</strong>模型太複雜，過度擬合訓練資料 → Overfitting<br /><br />
機器學習的藝術在於找到兩者的平衡點。</li>
    </ul>
  </div>

  <h3 id="section-4">評估方式</h3>

  <ul>
    <li><strong>訓練集（Training Set）：</strong> 用於學習模型參數</li>
    <li><strong>驗證集（Validation Set）：</strong> 用於調整超參數、選擇模型</li>
    <li><strong>測試集（Test Set）：</strong> 用於評估最終模型的泛化能力</li>
  </ul>

  <div class="highlight-box">
    <p>⚠️ <strong>重要：</strong>測試集只能在最後使用一次，否則會洩漏資訊！</p>
  </div>

</div>

<hr />

<h2 id="bayes-rule基礎工具">Bayes’ Rule（基礎工具）</h2>

<div class="section">
  <div class="section-label red">機率推論</div>

  <h3 id="section-5">公式</h3>

  <div class="math-block">

$$

p(C \mid x) = \frac{p(x \mid C)\, p(C)}{p(x)}

$$

<strong>各項意義：</strong>
- $p(C)$：**Prior（先驗機率）** — 觀察資料前對 $C$ 的信念
- $p(x \mid C)$：**Likelihood（似然）** — 給定 $C$ 時觀察到 $x$ 的機率
- $p(C \mid x)$：**Posterior（後驗機率）** — 觀察到 $x$ 後對 $C$ 的信念
- $p(x)$：**Evidence（證據）** — 歸一化常數，$p(x) = \sum_C p(x \mid C) p(C)$

</div>

  <h3 id="section-6">貝氏推論的哲學</h3>

  <div class="definition-box">
    <p><strong>Bayesian Inference：</strong><br />
先有一個 prior belief，觀察到資料後，用 Bayes’ Rule 更新成 posterior belief。</p>
  </div>

  <p><strong>解讀：</strong></p>

\[\text{Posterior} \propto \text{Likelihood} \times \text{Prior}\]

  <ul>
    <li>Likelihood 高：資料支持這個假設</li>
    <li>Prior 高：在觀察前就相信這個假設</li>
    <li>Posterior 結合兩者，給出最終的信念</li>
  </ul>

  <h3 id="section-7">實例：醫療診斷</h3>

  <p>假設某疾病發生率 1%（prior），某測試：</p>
  <ul>
    <li>有病時測出陽性 95%（sensitivity）</li>
    <li>無病時測出陽性 5%（false positive rate）</li>
  </ul>

  <p><strong>問：測出陽性時，真的有病的機率？</strong></p>

  <div class="math-block">

設 $D$ = 有病，$+$ = 測試陽性

$$

\begin{align}
p(D \mid +) &amp;= \frac{p(+ \mid D) \, p(D)}{p(+)} \\
&amp;= \frac{0.95 \times 0.01}{0.95 \times 0.01 + 0.05 \times 0.99} \\
&amp;= \frac{0.0095}{0.0095 + 0.0495} \\
&amp;\approx 0.161
\end{align}
$$

</div>

  <div class="highlight-box">
    <p><strong>驚人結論：</strong>即使測試陽性，真的有病的機率只有 16.1%！<br />
這是因為疾病太罕見（prior 低），false positive 影響很大。</p>
  </div>

</div>

<hr />

<h2 id="總結">總結</h2>

<div class="section">

  <p><strong>機器學習的本質：</strong></p>
  <ol>
    <li>從資料中<strong>學習</strong>模式</li>
    <li>用學到的模式對<strong>未見資料</strong>做預測或決策</li>
    <li>核心挑戰是<strong>泛化能力</strong></li>
  </ol>

  <p><strong>基礎工具：</strong></p>
  <ul>
    <li>機率論：建模不確定性</li>
    <li>Bayes’ Rule：從觀察更新信念</li>
    <li>統計推論：從樣本推廣到母體</li>
  </ul>

  <p><strong>下一步：</strong></p>
  <ul>
    <li>監督式學習的詳細框架</li>
    <li>VC Dimension 與 PAC Learning</li>
    <li>Bayesian Decision Theory</li>
  </ul>

</div>

<hr />

<h2 id="參考資料">參考資料</h2>

<ul>
  <li>Bishop, <em>Pattern Recognition and Machine Learning</em>, Chapter 1</li>
  <li>Murphy, <em>Machine Learning: A Probabilistic Perspective</em>, Chapter 1</li>
  <li>Alpaydin, <em>Introduction to Machine Learning</em>, Chapter 1</li>
</ul>]]></content><author><name>Chien-Chih Tseng</name></author><category term="機器學習" /><category term="Introduction" /><category term="Supervised" /><category term="Unsupervised" /><category term="Bayes" /><summary type="html"><![CDATA[機器學習簡介：定義、主要類型、核心議題與 Bayes' Rule]]></summary></entry><entry><title type="html">Karger’s Min-Cut Algorithm</title><link href="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/karger-min-cut.html" rel="alternate" type="text/html" title="Karger’s Min-Cut Algorithm" /><published>2026-03-16T02:00:00+00:00</published><updated>2026-03-16T02:00:00+00:00</updated><id>https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/karger-min-cut</id><content type="html" xml:base="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/karger-min-cut.html"><![CDATA[<style>
:root {
  --accent: #667eea;
  --accent-light: #eef3fb;
  --border: #e5e5e0;
  --text-muted: #6b6b65;
}

.oneliner {
  background: var(--accent-light);
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 32px 0;
  font-size: 1.05rem;
  font-style: italic;
  color: #1a3a6b;
}

.section {
  margin: 40px 0;
}

.section-label {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-family: monospace;
  font-size: 11px;
  font-weight: bold;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 14px;
}

.section-label::before {
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  background: #d4a847;
}

.section-label.blue::before { background: #4a90d9; }
.section-label.green::before { background: #5aaa72; }
.section-label.purple::before { background: #9b72c8; }
.section-label.red::before { background: #d96b5a; }

.math-block {
  background: #fafaf8;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 16px 20px;
  margin: 16px 0;
  overflow-x: auto;
}

.algo-box {
  background: #f8f9fa;
  border: 2px solid #667eea;
  border-radius: 8px;
  padding: 20px;
  margin: 20px 0;
  font-family: 'Courier New', monospace;
}

.algo-box .algo-title {
  font-weight: bold;
  color: #667eea;
  margin-bottom: 12px;
  font-size: 1.1rem;
}

.algo-box ol {
  margin: 0;
  padding-left: 20px;
}

.algo-box li {
  margin: 8px 0;
  line-height: 1.6;
}

.highlight-box {
  background: #fff8e6;
  border-left: 4px solid #d4a847;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.example-box {
  background: #f0f9ff;
  border-left: 4px solid #4a90d9;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}
</style>

<!-- MathJax 配置 -->
<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$']],
    displayMath: [['$$', '$$']],
    tags: 'ams'
  }
};
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async=""></script>

<hr />

<h2 id="一句話解釋">一句話解釋</h2>

<div class="oneliner">
  <p>隨機選邊並收縮（contract），重複到剩兩個節點，剩下的邊就是候選割；成功率約 $\frac{2}{n^2}$，重複 $O(n^2 \log n)$ 次可高機率成功。</p>
</div>

<hr />

<h2 id="問題定義min-cut">問題定義：Min-Cut</h2>

<div class="section">
  <div class="section-label blue">問題設定</div>

  <h3 id="minimum-cut">最小割（Minimum Cut）</h3>

  <p>給定無向圖 $G = (V, E)$：</p>
  <ul>
    <li><strong>割（Cut）：</strong> 將頂點集 $V$ 分成兩個非空子集 $S$ 和 $T = V \setminus S$</li>
    <li><strong>割的大小：</strong> 連接 $S$ 和 $T$ 的邊數</li>
    <li><strong>最小割：</strong> 所有割中大小最小的</li>
  </ul>

  <div class="math-block">

$$

\text{Min-Cut}(G) = \min_{S \subset V, S \neq \emptyset, V} |\{(u,v) \in E : u \in S, v \in V \setminus S\}|

$$

</div>

  <h3 id="section">應用</h3>

  <ul>
    <li><strong>網路可靠性：</strong> 最小割 = 切斷網路的最少邊數</li>
    <li><strong>圖像分割：</strong> 將影像分成前景與背景</li>
    <li><strong>社群檢測：</strong> 找出社交網路的分群</li>
  </ul>

  <h3 id="section-1">確定性演算法</h3>

  <ul>
    <li><strong>Max-Flow Min-Cut：</strong> $O(mn)$ 或更好（但需選擇 source-sink 對）</li>
    <li><strong>Stoer-Wagner：</strong> $O(mn + n^2 \log n)$，確定性找全局最小割</li>
  </ul>

  <p>Karger 的演算法更簡單，且對某些問題（如找所有近似最小割）更有效。</p>

</div>

<hr />

<h2 id="kargers-演算法">Karger’s 演算法</h2>

<div class="section">
  <div class="section-label purple">Edge Contraction</div>

  <h3 id="edge-contraction">核心操作：邊收縮（Edge Contraction）</h3>

  <p><strong>Contraction（收縮）</strong> 一條邊 $(u, v)$：</p>
  <ol>
    <li>將 $u$ 和 $v$ 合併成一個新節點（超節點）</li>
    <li>所有連到 $u$ 或 $v$ 的邊，都改連到新節點</li>
    <li>移除自環（self-loops）</li>
  </ol>

  <div class="example-box">
    <p><strong>範例：</strong><br />
圖 $G$ 有邊 $(u, v)$，收縮後：</p>
    <ul>
  <li>$u$ 和 $v$ 變成單一節點 $w$</li>
  <li>原本的 $(u, x)$ 和 $(v, y)$ 變成 $(w, x)$ 和 $(w, y)$</li>
  <li>如果 $u$ 和 $v$ 之間有多條邊，收縮後變成自環（被移除）</li>
</ul>
  </div>

  <h3 id="section-2">演算法流程</h3>

  <div class="algo-box">
<div class="algo-title">Algorithm: Karger's Min-Cut</div>
<strong>Input:</strong> 無向圖 $G = (V, E)$，$|V| = n$<br />
<strong>Output:</strong> 一個割（候選最小割）

<ol>
  <li>**While** 圖還有超過 2 個節點：
    <ul style="list-style: none; padding-left: 20px;">
      <li>a. 隨機均勻選擇一條邊 $e \in E$</li>
      <li>b. 收縮 $e$（將兩端點合併）</li>
    </ul>
  </li>
  <li>**Return** 剩下的兩個超節點之間的所有邊（這是候選割）</li>
</ol>
</div>

  <h3 id="section-3">關鍵觀察</h3>

  <ul>
    <li>每次收縮減少一個節點：$n \to n-1 \to \cdots \to 2$</li>
    <li>總共收縮 $n-2$ 次</li>
    <li>每次收縮都是隨機選擇，所以最終結果是隨機的</li>
  </ul>

  <div class="highlight-box">
    <p><strong>💡 為什麼可能成功？</strong><br />
如果我們<strong>從未收縮最小割中的邊</strong>，最後剩下的邊就是最小割！<br />
問題是：這件事的機率有多大？</p>
  </div>

</div>

<hr />

<h2 id="成功率分析">成功率分析</h2>

<div class="section">
  <div class="section-label red">機率分析</div>

  <h3 id="section-4">定理</h3>

  <div class="math-block">

<strong>Theorem:</strong>  
對於有 $n$ 個節點的圖 $G$，Karger 演算法找到最小割的機率**至少**為：

$$

\Pr[\text{成功}] \geq \frac{2}{n(n-1)} \geq \frac{2}{n^2}

$$

</div>

  <h3 id="section-5">證明思路</h3>

  <table>
    <tbody>
      <tr>
        <td>令 $C$ 是最小割，$</td>
        <td>C</td>
        <td>= k$（最小割的大小）。</td>
      </tr>
    </tbody>
  </table>

  <p><strong>目標：</strong> 證明 $\Pr[\text{沒有收縮到 } C \text{ 中的邊}] \geq \frac{2}{n^2}$</p>

  <h4 id="step-1-">Step 1: 每個節點的度數下界</h4>

  <div class="math-block">

因為最小割大小是 $k$，每個節點的度數至少是 $k$（否則該節點自己形成的割更小）。

$$

\deg(v) \geq k, \quad \forall v \in V

$$

因此總邊數：

$$

|E| \geq \frac{nk}{2}

$$

</div>

  <h4 id="step-2--min-cut-">Step 2: 第一次收縮不碰到 min-cut 的機率</h4>

  <div class="math-block">

第一次隨機選邊，選到 $C$ 中的邊的機率：

$$

\Pr[\text{選到 } C] = \frac{k}{|E|} \leq \frac{k}{nk/2} = \frac{2}{n}

$$

所以**不選到** $C$ 的機率：

$$

\Pr[\text{不選到 } C] \geq 1 - \frac{2}{n} = \frac{n-2}{n}

$$

</div>

  <h4 id="step-3--i-">Step 3: 第 $i$ 次收縮</h4>

  <div class="math-block">

在第 $i$ 次收縮時，還剩 $n-i+1$ 個（超）節點。

<strong>關鍵：</strong> 最小割仍是 $k$（收縮不會減少最小割的大小，只要我們沒碰到它）。

邊數至少：$\frac{(n-i+1) \cdot k}{2}$

不選到 $C$ 的機率：

$$

\Pr[\text{第 } i \text{ 次不選到 } C \mid \text{前 } i-1 \text{ 次都沒選到}] \geq \frac{n-i-1}{n-i+1}

$$

</div>

  <h4 id="step-4-">Step 4: 連鎖機率</h4>

  <div class="math-block">

所有 $n-2$ 次收縮都不選到 $C$ 的機率：

$$

\begin{align}
\Pr[\text{成功}] &amp;= \prod_{i=1}^{n-2} \Pr[\text{第 } i \text{ 次不選到 } C \mid \text{前面都沒選到}] \\
&amp;\geq \prod_{i=1}^{n-2} \frac{n-i-1}{n-i+1} \\
&amp;= \frac{n-2}{n} \cdot \frac{n-3}{n-1} \cdot \frac{n-4}{n-2} \cdots \frac{2}{4} \cdot \frac{1}{3} \\
&amp;= \frac{2 \cdot 1}{n \cdot (n-1)} = \frac{2}{n(n-1)}
\end{align}
$$

</div>

  <div class="highlight-box">
    <p><strong>🎯 結論：</strong><br />
單次執行成功率約 $\frac{2}{n^2}$。雖然很小，但<strong>多項式級別</strong>（不是指數小）！<br />
這意味著重複多項式次就能高機率成功。</p>
  </div>

</div>

<hr />

<h2 id="重複策略">重複策略</h2>

<div class="section">
  <div class="section-label green">提升成功率</div>

  <h3 id="section-6">重複執行</h3>

  <p>單次成功率 $p \geq \frac{2}{n^2}$，失敗率 $1-p \leq 1 - \frac{2}{n^2}$。</p>

  <p>執行 $k$ 次，<strong>全部失敗</strong>的機率：</p>

  <div class="math-block">

$$

\Pr[\text{全部失敗}] = (1-p)^k \leq \left(1 - \frac{2}{n^2}\right)^k

$$

利用不等式 $1-x \leq e^{-x}$：

$$

\Pr[\text{全部失敗}] \leq e^{-2k/n^2}

$$

</div>

  <h3 id="section-7">選擇重複次數</h3>

  <div class="math-block">

<strong>要達到成功率 $\geq 1 - \delta$：</strong>

$$

e^{-2k/n^2} \leq \delta \quad \Rightarrow \quad k \geq \frac{n^2}{2} \ln \frac{1}{\delta}

$$

<strong>常見選擇：</strong>
- $\delta = 1/n$：$k = O(n^2 \log n)$，成功率 $\geq 1 - 1/n$
- $\delta = 0.01$：$k = O(n^2)$，成功率 $\geq 99\%$

</div>

  <h3 id="section-8">總時間複雜度</h3>

  <div class="math-block">

- <strong>單次執行：</strong> $O(n^2)$（$n-2$ 次收縮，每次 $O(n)$）
- <strong>重複 $k$ 次：</strong> $O(k \cdot n^2) = O(n^4 \log n)$（若 $k = O(n^2 \log n)$）

<strong>改進版（Karger-Stein）：</strong> $O(n^2 \log^3 n)$，用遞迴策略

</div>

</div>

<hr />

<h2 id="範例">範例</h2>

<div class="section">

  <h3 id="section-9">簡單例子</h3>

  <p>考慮 4 個節點的環狀圖：</p>

  <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>A --- B
|     |
D --- C
</code></pre></div>  </div>

  <p>最小割大小 = 2（例如切掉 AB 和 CD）。</p>

  <p><strong>執行過程（一個可能的情況）：</strong></p>
  <ol>
    <li>隨機選 AB，收縮 → 剩 3 個超節點</li>
    <li>隨機選 BC，收縮 → 剩 2 個超節點</li>
    <li>剩下的邊 = {AD, CD}（不是最小割，失敗）</li>
  </ol>

  <p><strong>成功情況：</strong>
如果一直不選 AB 和 CD（假設它們是最小割的邊），最後剩下這兩條邊 → 成功！</p>

  <p>成功率：$\frac{2}{4 \times 3} = \frac{1}{6} \approx 16.7\%$</p>

</div>

<hr />

<h2 id="總結">總結</h2>

<div class="section">

  <p><strong>Karger’s Min-Cut</strong> 是隨機演算法的經典範例：</p>

  <ol>
    <li><strong>極簡演算法：</strong> 隨機選邊、收縮、重複</li>
    <li><strong>Monte Carlo 類型：</strong> 多項式時間，但可能失敗</li>
    <li><strong>成功率分析：</strong> 單次 $\geq \frac{2}{n^2}$，看似小但夠用</li>
    <li><strong>重複策略：</strong> $O(n^2 \log n)$ 次 → 高機率成功</li>
    <li><strong>總複雜度：</strong> $O(n^4 \log n)$（樸素版）</li>
  </ol>

  <p><strong>關鍵技巧：</strong> 機率分析中的連鎖機率、Union Bound、以及 amplification by repetition。</p>

</div>

<hr />

<h2 id="參考資料">參考資料</h2>

<ul>
  <li>Karger, “Global Min-Cuts in RNC and Other Ramifications of a Simple Min-Cut Algorithm”, 1993</li>
  <li>Karger &amp; Stein, “A New Approach to the Minimum Cut Problem”, 1996</li>
  <li>Motwani &amp; Raghavan, <em>Randomized Algorithms</em>, Chapter 10</li>
</ul>]]></content><author><name>Chien-Chih Tseng</name></author><category term="隨機演算法" /><category term="圖論" /><category term="Min-Cut" /><category term="機率分析" /><summary type="html"><![CDATA[用隨機邊收縮找最小割，分析成功率與重複次數]]></summary></entry><entry><title type="html">機率基礎工具</title><link href="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/probability-basics.html" rel="alternate" type="text/html" title="機率基礎工具" /><published>2026-03-16T02:00:00+00:00</published><updated>2026-03-16T02:00:00+00:00</updated><id>https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/probability-basics</id><content type="html" xml:base="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/probability-basics.html"><![CDATA[<style>
:root {
  --accent: #667eea;
  --accent-light: #eef3fb;
  --border: #e5e5e0;
  --text-muted: #6b6b65;
}

.oneliner {
  background: var(--accent-light);
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 32px 0;
  font-size: 1.05rem;
  font-style: italic;
  color: #1a3a6b;
}

.section {
  margin: 40px 0;
}

.section-label {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-family: monospace;
  font-size: 11px;
  font-weight: bold;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 14px;
}

.section-label::before {
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  background: #d4a847;
}

.section-label.blue::before { background: #4a90d9; }
.section-label.green::before { background: #5aaa72; }
.section-label.purple::before { background: #9b72c8; }
.section-label.red::before { background: #d96b5a; }

.math-block {
  background: #fafaf8;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 16px 20px;
  margin: 16px 0;
  overflow-x: auto;
}

.highlight-box {
  background: #fff8e6;
  border-left: 4px solid #d4a847;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.example-box {
  background: #f0f9ff;
  border-left: 4px solid #4a90d9;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.theorem-box {
  background: #fef5ff;
  border: 2px solid #9b72c8;
  border-radius: 8px;
  padding: 16px 20px;
  margin: 20px 0;
}

.theorem-box .theorem-title {
  font-weight: bold;
  color: #9b72c8;
  margin-bottom: 8px;
}
</style>

<!-- MathJax 配置 -->
<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$']],
    displayMath: [['$$', '$$']],
    tags: 'ams'
  }
};
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async=""></script>

<hr />

<h2 id="一句話解釋">一句話解釋</h2>

<div class="oneliner">
  <p>分析隨機演算法的數學基礎：機率、條件機率、期望值，以及最重要的 Linearity of Expectation。</p>
</div>

<hr />

<h2 id="機率空間與公理">機率空間與公理</h2>

<div class="section">
  <div class="section-label blue">基本定義</div>

  <h3 id="section">機率空間</h3>

  <p>一個<strong>機率空間</strong>由三個元素組成：$(\Omega, \mathcal{F}, \Pr)$</p>

  <ul>
    <li><strong>樣本空間 $\Omega$：</strong> 所有可能結果的集合</li>
    <li><strong>事件空間 $\mathcal{F}$：</strong> $\Omega$ 的子集合族（可測事件）</li>
    <li><strong>機率測度 $\Pr$：</strong> $\mathcal{F} \to [0, 1]$ 的函數</li>
  </ul>

  <h3 id="kolmogorov-">Kolmogorov 機率公理</h3>

  <div class="math-block">

<strong>公理 1（非負性）：</strong>

$$\Pr[A] \geq 0, \quad \forall A \in \mathcal{F}$$

<strong>公理 2（規範性）：</strong>

$$\Pr[\Omega] = 1$$

<strong>公理 3（可數可加性）：</strong>
若 $A_1, A_2, \dots$ 兩兩互斥，則：
$$\Pr\left[\bigcup_{i=1}^\infty A_i\right] = \sum_{i=1}^\infty \Pr[A_i]$$

</div>

  <h3 id="section-1">衍生性質</h3>

  <div class="math-block">

1. <strong>補集：</strong> $\Pr[\bar{A}] = 1 - \Pr[A]$
2. <strong>單調性：</strong> 若 $A \subseteq B$，則 $\Pr[A] \leq \Pr[B]$
3. <strong>聯集界（Union Bound）：</strong>
   $$\Pr[A \cup B] \leq \Pr[A] + \Pr[B]$$
4. <strong>包含排斥原理：</strong>
   $$\Pr[A \cup B] = \Pr[A] + \Pr[B] - \Pr[A \cap B]$$

</div>

</div>

<hr />

<h2 id="條件機率與獨立性">條件機率與獨立性</h2>

<div class="section">
  <div class="section-label purple">條件機率</div>

  <h3 id="section-2">條件機率</h3>

  <div class="math-block">

<strong>定義：</strong> 給定事件 $B$ 發生，事件 $A$ 發生的機率：

$$

\Pr[A \mid B] = \frac{\Pr[A \cap B]}{\Pr[B]}, \quad \text{若 } \Pr[B] &gt; 0

$$

</div>

  <h3 id="bayes-">Bayes 定理</h3>

  <div class="theorem-box">
<div class="theorem-title">Theorem: Bayes' Theorem</div>

$$

\Pr[A \mid B] = \frac{\Pr[B \mid A] \cdot \Pr[A]}{\Pr[B]}

$$

<strong>全機率公式（Law of Total Probability）：</strong>

若 $B_1, \dots, B_n$ 分割 $\Omega$（兩兩互斥且聯集為 $\Omega$），則：

$$

\Pr[A] = \sum_{i=1}^n \Pr[A \mid B_i] \cdot \Pr[B_i]

$$

</div>

  <div class="example-box">
    <p><strong>範例：疾病檢測</strong><br /></p>
    <ul>
      <li>疾病盛行率：$\Pr[\text{病}] = 0.01$<br /></li>
      <li>檢測靈敏度：$\Pr[\text{陽性} \mid \text{病}] = 0.99$<br /></li>
      <li>偽陽性率：$\Pr[\text{陽性} \mid \text{健康}] = 0.05$<br /><br /></li>
    </ul>

    <p><strong>問：檢測陽性時，真的有病的機率？</strong><br /></p>

\[\begin{align}
\Pr[\text{病} \mid \text{陽性}] &amp;= \frac{\Pr[\text{陽性} \mid \text{病}] \cdot \Pr[\text{病}]}{\Pr[\text{陽性}]} \\
&amp;= \frac{0.99 \times 0.01}{0.99 \times 0.01 + 0.05 \times 0.99} \\
&amp;\approx 0.166
\end{align}\]

    <p>只有 16.6%！偽陽性嚴重稀釋了陽性結果的意義。</p>
  </div>

  <h3 id="section-3">獨立性</h3>

  <div class="math-block">

<strong>定義：</strong> 事件 $A$ 和 $B$ **獨立**若：

$$

\Pr[A \cap B] = \Pr[A] \cdot \Pr[B]

$$

<strong>等價條件：</strong>
- $\Pr[A \mid B] = \Pr[A]$（$B$ 不影響 $A$ 的機率）
- $\Pr[B \mid A] = \Pr[B]$

<strong>多個事件獨立：</strong>

事件 $A_1, \dots, A_n$ **互相獨立**若對任意子集 $I \subseteq \{1, \dots, n\}$：

$$

\Pr\left[\bigcap_{i \in I} A_i\right] = \prod_{i \in I} \Pr[A_i]

$$

</div>

</div>

<hr />

<h2 id="隨機變數與期望值">隨機變數與期望值</h2>

<div class="section">
  <div class="section-label green">期望值</div>

  <h3 id="section-4">隨機變數</h3>

  <p><strong>隨機變數</strong> $X$ 是從樣本空間到實數的函數：$X: \Omega \to \mathbb{R}$</p>

  <h3 id="section-5">期望值</h3>

  <div class="math-block">

<strong>離散情況：</strong>

$$\mathbb{E}[X] = \sum_{x} x \cdot \Pr[X = x]$$

<strong>連續情況：</strong>

$$\mathbb{E}[X] = \int_{-\infty}^\infty x \cdot f_X(x) \, dx$$

</div>

  <h3 id="section-6">期望值的性質</h3>

  <div class="theorem-box">
<div class="theorem-title">Theorem: Linearity of Expectation</div>

<strong>線性性：</strong>

$$\mathbb{E}[aX + bY] = a\mathbb{E}[X] + b\mathbb{E}[Y]$$

**關鍵：不需要 $X$ 和 $Y$ 獨立！**

<strong>推廣：</strong>

$$\mathbb{E}\left[\sum_{i=1}^n X_i\right] = \sum_{i=1}^n \mathbb{E}[X_i]$$

</div>

  <div class="highlight-box">
    <p><strong>🔑 為什麼重要？</strong><br />
Linearity of Expectation 是隨機演算法分析的<strong>最強工具</strong>：</p>
    <ul>
  <li>即使變數高度相關，期望仍可加</li>
  <li>可以把複雜問題分解成簡單部分</li>
  <li>不需要計算聯合分佈</li>
</ul>
  </div>

  <h3 id="section-7">經典應用：期望比較次數</h3>

  <div class="example-box">
    <p><strong>問題：</strong> Quicksort 的期望比較次數？<br /><br /></p>

    <p>定義指示變數（Indicator）：</p>

\[X_{ij} = \begin{cases} 1 &amp; \text{若元素 } i \text{ 和 } j \text{ 有比較} \\ 0 &amp; \text{否則} \end{cases}\]

    <p>總比較次數：</p>

\[X = \sum_{i&lt;j} X_{ij}\]

    <p>期望：</p>

\[\mathbb{E}[X] = \sum_{i&lt;j} \mathbb{E}[X_{ij}] = \sum_{i&lt;j} \Pr[i \text{ 和 } j \text{ 比較}]\]

    <p>分析得 $\Pr[i \text{ 和 } j \text{ 比較}] = \frac{2}{j-i+1}$，所以：</p>

\[\mathbb{E}[X] = 2n \ln n + O(n) = O(n \log n)\]

    <p><strong>關鍵：</strong> 不需要知道 $X_{ij}$ 之間的相關性！</p>
  </div>

</div>

<hr />

<h2 id="常見分佈">常見分佈</h2>

<div class="section">
  <div class="section-label red">重要分佈</div>

  <h3 id="bernoulli-">Bernoulli 分佈</h3>

  <div class="math-block">

<strong>定義：</strong> 單次試驗，成功率 $p$

$$

X \sim \text{Bernoulli}(p)

$$

- $\Pr[X = 1] = p$，$\Pr[X = 0] = 1-p$
- $\mathbb{E}[X] = p$
- $\text{Var}(X) = p(1-p)$

</div>

  <h3 id="binomial-">Binomial 分佈</h3>

  <div class="math-block">

<strong>定義：</strong> $n$ 次獨立 Bernoulli$(p)$ 試驗的成功次數

$$

X \sim \text{Binomial}(n, p)

$$

- $\Pr[X = k] = \binom{n}{k} p^k (1-p)^{n-k}$
- $\mathbb{E}[X] = np$
- $\text{Var}(X) = np(1-p)$

<strong>推導（用 Linearity）：</strong>

令 $X = X_1 + \cdots + X_n$，其中 $X_i \sim \text{Bernoulli}(p)$

$$

\mathbb{E}[X] = \mathbb{E}[X_1] + \cdots + \mathbb{E}[X_n] = np

$$

</div>

  <h3 id="geometric-">Geometric 分佈</h3>

  <div class="math-block">

<strong>定義：</strong> 直到第一次成功的試驗次數

$$

X \sim \text{Geometric}(p)

$$

- $\Pr[X = k] = (1-p)^{k-1} p$
- $\mathbb{E}[X] = \frac{1}{p}$
- $\text{Var}(X) = \frac{1-p}{p^2}$

<strong>無記憶性（Memoryless）：</strong>

$$\Pr[X &gt; n+m \mid X &gt; n] = \Pr[X &gt; m]$$

</div>

</div>

<hr />

<h2 id="變異數與協方差">變異數與協方差</h2>

<div class="section">

  <h3 id="section-8">變異數</h3>

  <div class="math-block">

$$

\text{Var}(X) = \mathbb{E}[(X - \mathbb{E}[X])^2] = \mathbb{E}[X^2] - (\mathbb{E}[X])^2

$$

<strong>性質：</strong>
- $\text{Var}(aX + b) = a^2 \text{Var}(X)$
- 若 $X, Y$ 獨立：$\text{Var}(X + Y) = \text{Var}(X) + \text{Var}(Y)$

</div>

  <h3 id="section-9">協方差</h3>

  <div class="math-block">

$$

\text{Cov}(X, Y) = \mathbb{E}[(X - \mathbb{E}[X])(Y - \mathbb{E}[Y])] = \mathbb{E}[XY] - \mathbb{E}[X]\mathbb{E}[Y]

$$

<strong>性質：</strong>
- 若 $X, Y$ 獨立，則 $\text{Cov}(X, Y) = 0$（反之不一定）
- $\text{Var}(X + Y) = \text{Var}(X) + \text{Var}(Y) + 2\text{Cov}(X, Y)$

</div>

</div>

<hr />

<h2 id="總結">總結</h2>

<div class="section">

  <p>機率工具是隨機演算法的基礎：</p>

  <ol>
    <li><strong>機率公理</strong> → Union Bound、包含排斥</li>
    <li><strong>條件機率</strong> → Bayes 定理、全機率</li>
    <li><strong>獨立性</strong> → 簡化計算</li>
    <li><strong>期望值</strong> → <strong>Linearity of Expectation</strong>（最重要！）</li>
    <li><strong>常見分佈</strong> → Bernoulli, Binomial, Geometric</li>
  </ol>

  <p>下一步：用這些工具分析演算法的時間、正確性與效能！</p>

</div>

<hr />

<h2 id="參考資料">參考資料</h2>

<ul>
  <li>Mitzenmacher &amp; Upfal, <em>Probability and Computing</em>, Chapter 1-2</li>
  <li>Motwani &amp; Raghavan, <em>Randomized Algorithms</em>, Appendix A</li>
  <li>Ross, <em>A First Course in Probability</em></li>
</ul>]]></content><author><name>Chien-Chih Tseng</name></author><category term="隨機演算法" /><category term="機率論" /><category term="期望值" /><category term="Linearity of Expectation" /><summary type="html"><![CDATA[機率公理、條件機率、Bayes 定理、期望值線性、常見分佈]]></summary></entry><entry><title type="html">隨機複雜度類別</title><link href="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/complexity-classes.html" rel="alternate" type="text/html" title="隨機複雜度類別" /><published>2026-03-16T02:00:00+00:00</published><updated>2026-03-16T02:00:00+00:00</updated><id>https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/complexity-classes</id><content type="html" xml:base="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/complexity-classes.html"><![CDATA[<style>
:root {
  --accent: #667eea;
  --accent-light: #eef3fb;
  --border: #e5e5e0;
  --text-muted: #6b6b65;
}

.oneliner {
  background: var(--accent-light);
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 32px 0;
  font-size: 1.05rem;
  font-style: italic;
  color: #1a3a6b;
}

.section {
  margin: 40px 0;
}

.section-label {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-family: monospace;
  font-size: 11px;
  font-weight: bold;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 14px;
}

.section-label::before {
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  background: #d4a847;
}

.section-label.blue::before { background: #4a90d9; }
.section-label.green::before { background: #5aaa72; }
.section-label.purple::before { background: #9b72c8; }
.section-label.red::before { background: #d96b5a; }

.math-block {
  background: #fafaf8;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 16px 20px;
  margin: 16px 0;
  overflow-x: auto;
}

.comparison-table {
  width: 100%;
  border-collapse: collapse;
  margin: 16px 0;
  font-size: 0.9rem;
}

.comparison-table th,
.comparison-table td {
  padding: 10px;
  border: 1px solid var(--border);
  text-align: left;
}

.comparison-table th {
  background: #f5f5f3;
  font-weight: bold;
  color: #2a2a28;
}

.comparison-table tr:hover {
  background: var(--accent-light);
}

.highlight-box {
  background: #fff8e6;
  border-left: 4px solid #d4a847;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.diagram {
  background: white;
  border: 2px solid var(--accent);
  border-radius: 8px;
  padding: 20px;
  margin: 20px 0;
  text-align: center;
  font-family: monospace;
}
</style>

<!-- MathJax 配置 -->
<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$']],
    displayMath: [['$$', '$$']],
    tags: 'ams'
  }
};
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async=""></script>

<hr />

<h2 id="一句話解釋">一句話解釋</h2>

<div class="oneliner">
  <p>隨機演算法擴展了複雜度理論：RP 允許單向錯誤、BPP 允許雙向錯誤、ZPP 是 Las Vegas，都在多項式時間內。</p>
</div>

<hr />

<h2 id="turing-machine-基礎">Turing Machine 基礎</h2>

<div class="section">
  <div class="section-label blue">計算模型</div>

  <h3 id="deterministic-turing-machine-dtm">Deterministic Turing Machine (DTM)</h3>

  <p><strong>組成：</strong></p>
  <ul>
    <li>無限長紙帶（tape）</li>
    <li>讀寫頭（head）</li>
    <li>有限狀態控制（finite control）</li>
    <li>轉移函數 $\delta(q, a) = (q’, a’, D)$
      <ul>
        <li>$q$: 當前狀態，$a$: 讀到的符號</li>
        <li>$q’$: 新狀態，$a’$: 寫入符號，$D$: 移動方向</li>
      </ul>
    </li>
  </ul>

  <h3 id="probabilistic-turing-machine-ptm">Probabilistic Turing Machine (PTM)</h3>

  <p>加入<strong>隨機選擇</strong>：</p>

  <div class="math-block">

轉移函數變成機率分佈：

$$

\delta(q, a) = \{(q'_1, a'_1, D_1, p_1), (q'_2, a'_2, D_2, p_2), \dots\}

$$

其中 $\sum_i p_i = 1$

等價於：機器可以「擲硬幣」來決定下一步。

</div>

</div>

<hr />

<h2 id="傳統複雜度類別">傳統複雜度類別</h2>

<div class="section">
  <div class="section-label green">P 與 NP</div>

  <h3 id="ppolynomial-time">P（Polynomial Time）</h3>

  <div class="math-block">

<strong>定義：</strong> 可在**確定性**多項式時間內解決的決策問題集合。

$$

\text{P} = \bigcup_{k \geq 0} \text{DTIME}(n^k)

$$

<strong>範例：</strong>
- 最短路徑（Dijkstra）
- 排序（Merge Sort）
- 線性規劃（Ellipsoid Method）

</div>

  <h3 id="npnondeterministic-polynomial-time">NP（Nondeterministic Polynomial Time）</h3>

  <div class="math-block">

<strong>定義：</strong> 可在多項式時間內**驗證**解的決策問題集合。

等價定義：**非確定性** Turing Machine 可在多項式時間內解決。

$$

\text{NP} = \bigcup_{k \geq 0} \text{NTIME}(n^k)

$$

<strong>範例：</strong>
- SAT（Boolean Satisfiability）
- TSP（Traveling Salesman，判定版本）
- Graph Coloring

</div>

  <h3 id="co-np">co-NP</h3>

  <div class="math-block">

<strong>定義：</strong> 補問題（complement）在 NP 的問題集合。

$$

L \in \text{co-NP} \iff \bar{L} \in \text{NP}

$$

<strong>範例：</strong>
- UNSAT（不可滿足性）
- TAUTOLOGY（永真式）

</div>

  <h3 id="section">關係</h3>

  <div class="diagram">
P ⊆ NP<br />
P ⊆ co-NP<br />
P = NP ∩ co-NP （已知）<br />
<br />
<strong>未知：</strong> P ?= NP, NP ?= co-NP
</div>

</div>

<hr />

<h2 id="隨機複雜度類別">隨機複雜度類別</h2>

<div class="section">
  <div class="section-label purple">RP, co-RP, ZPP, BPP</div>

  <h3 id="rprandomized-polynomial-time">RP（Randomized Polynomial Time）</h3>

  <div class="math-block">

<strong>定義：</strong> Monte Carlo 演算法，**單向錯誤**（one-sided error）。

對語言 $L$：
- 若 $x \in L$：$\Pr[\text{Accept}] \geq \frac{1}{2}$
- 若 $x \notin L$：$\Pr[\text{Accept}] = 0$（**不會誤判**）

<strong>特性：</strong>
- Yes 答案一定對
- No 答案可能錯（但重複可降低錯誤率）

</div>

  <div class="example-box">
    <p><strong>範例：質數測試（某些版本）</strong><br /></p>
    <ul>
      <li>若 $n$ 是質數：高機率通過測試<br /></li>
      <li>若 $n$ 是合數：一定不通過測試</li>
    </ul>
  </div>

  <h3 id="co-rp">co-RP</h3>

  <div class="math-block">

<strong>定義：</strong> RP 的補類別。

對語言 $L$：
- 若 $x \in L$：$\Pr[\text{Accept}] = 1$
- 若 $x \notin L$：$\Pr[\text{Reject}] \geq \frac{1}{2}$

<strong>特性：</strong>
- No 答案一定對
- Yes 答案可能錯

</div>

  <h3 id="zppzero-error-probabilistic-polynomial">ZPP（Zero-error Probabilistic Polynomial）</h3>

  <div class="math-block">

<strong>定義：</strong> Las Vegas 演算法，**期望**多項式時間。

$$

\text{ZPP} = \text{RP} \cap \text{co-RP}

$$

<strong>特性：</strong>
- 總是給出正確答案
- 運行時間隨機，期望多項式

</div>

  <div class="example-box">
    <p><strong>範例：Randomized Quicksort</strong><br />
期望時間 $O(n \log n)$，總是正確排序。</p>
  </div>

  <h3 id="bppbounded-error-probabilistic-polynomial">BPP（Bounded-error Probabilistic Polynomial）</h3>

  <div class="math-block">

<strong>定義：</strong> Monte Carlo，**雙向錯誤**（two-sided error）。

對語言 $L$：
- 若 $x \in L$：$\Pr[\text{Accept}] \geq \frac{2}{3}$
- 若 $x \notin L$：$\Pr[\text{Reject}] \geq \frac{2}{3}$

<strong>關鍵：</strong> 錯誤率可透過重複降到任意小。

</div>

  <div class="highlight-box">
    <p><strong>💡 為什麼用 2/3？</strong><br />
任何常數 $&gt; 1/2$ 都可以（透過 amplification 達到任意接近 1）。<br />
2/3 只是慣例，計算方便。</p>
  </div>

  <h3 id="ppprobabilistic-polynomial-time">PP（Probabilistic Polynomial Time）</h3>

  <div class="math-block">

<strong>定義：</strong> 成功率 $&gt; 1/2$（但可以非常接近 1/2）。

- 若 $x \in L$：$\Pr[\text{Accept}] &gt; \frac{1}{2}$
- 若 $x \notin L$：$\Pr[\text{Accept}] &lt; \frac{1}{2}$

<strong>問題：</strong> 錯誤率可能是 $1/2 - 1/2^{n^{100}}$，無法有效 amplify！

</div>

</div>

<hr />

<h2 id="類別關係圖">類別關係圖</h2>

<div class="section">

  <div class="diagram" style="line-height: 2;">
<strong>已知關係：</strong><br /><br />
P ⊆ ZPP ⊆ RP ⊆ NP<br />
P ⊆ ZPP ⊆ co-RP ⊆ co-NP<br />
RP ⊆ BPP ⊆ PP<br />
co-RP ⊆ BPP ⊆ PP<br />
BPP ⊆ PSPACE<br />
<br />
<strong>猜測（未證明）：</strong><br />
P = BPP （多數人相信）<br />
RP ≠ NP
</div>

  <h3 id="section-1">比較表</h3>

  <table class="comparison-table">
  <thead>
    <tr>
      <th>類別</th>
      <th>模型</th>
      <th>錯誤類型</th>
      <th>範例</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>**P**</td>
      <td>確定性</td>
      <td>無錯誤</td>
      <td>排序、最短路</td>
    </tr>
    <tr>
      <td>**RP**</td>
      <td>隨機</td>
      <td>單向（Yes 對）</td>
      <td>質數測試（某些）</td>
    </tr>
    <tr>
      <td>**co-RP**</td>
      <td>隨機</td>
      <td>單向（No 對）</td>
      <td>多項式等價測試</td>
    </tr>
    <tr>
      <td>**ZPP**</td>
      <td>隨機</td>
      <td>無錯誤（Las Vegas）</td>
      <td>Randomized Quicksort</td>
    </tr>
    <tr>
      <td>**BPP**</td>
      <td>隨機</td>
      <td>雙向（可 amplify）</td>
      <td>多項式等價測試</td>
    </tr>
    <tr>
      <td>**PP**</td>
      <td>隨機</td>
      <td>雙向（難 amplify）</td>
      <td>Majority-SAT</td>
    </tr>
  </tbody>
</table>

</div>

<hr />

<h2 id="amplification降低錯誤率">Amplification：降低錯誤率</h2>

<div class="section">
  <div class="section-label red">重複執行</div>

  <h3 id="bpp--amplification">BPP 的 Amplification</h3>

  <div class="math-block">

<strong>原始：</strong> 錯誤率 $\leq 1/3$

<strong>重複 $k$ 次，取多數決（Majority Vote）：</strong>

錯誤率降為：

$$

\epsilon_k \leq e^{-\Omega(k)}

$$

具體地，Chernoff Bound 給出：

$$

\epsilon_k \leq 2^{-\Omega(k)}

$$

<strong>範例：</strong> 重複 $k = O(\log n)$ 次 → 錯誤率 $\leq 1/n^c$（多項式小）

</div>

  <h3 id="rp--amplification">RP 的 Amplification</h3>

  <div class="math-block">

<strong>原始：</strong> 成功率 $\geq 1/2$

<strong>重複 $k$ 次：</strong>

失敗率（全部失敗）：

$$

(1/2)^k \leq 2^{-k}

$$

<strong>範例：</strong> 重複 $k = O(\log n)$ 次 → 失敗率 $\leq 1/n^c$

</div>

</div>

<hr />

<h2 id="coin-transformation">Coin Transformation</h2>

<div class="section">
  <div class="section-label green">硬幣轉換</div>

  <h3 id="section-2">問題</h3>

  <p>只有<strong>有偏硬幣</strong>（bias coin），如何模擬<strong>公平硬幣</strong>？</p>

  <h3 id="von-neumann-trick">Von Neumann Trick</h3>

  <div class="math-block">

<strong>假設：</strong> 硬幣正面機率 $p \in (0, 1)$（未知）

<strong>方法：</strong>
1. 擲兩次，觀察結果
2. 若 $(H, T)$ → 輸出 $0$
3. 若 $(T, H)$ → 輸出 $1$
4. 若 $(H, H)$ 或 $(T, T)$ → 重擲

<strong>分析：</strong>

$$

\Pr[(H,T)] = p(1-p) = \Pr[(T,H)]

$$

所以輸出 0 和 1 的機率相等（$1/2$）！

<strong>期望擲幣次數：</strong>

$$

\mathbb{E}[\text{擲幣次數}] = \frac{2}{2p(1-p)} = \frac{1}{p(1-p)}

$$

</div>

  <h3 id="section-3">逆問題：模擬有偏硬幣</h3>

  <p>用公平硬幣模擬機率 $p = k/2^n$ 的事件：</p>
  <ul>
    <li>擲 $n$ 次公平硬幣，得二進位數 $m \in [0, 2^n-1]$</li>
    <li>若 $m &lt; k$，輸出 1；否則輸出 0</li>
  </ul>

</div>

<hr />

<h2 id="總結">總結</h2>

<div class="section">

  <p>隨機複雜度類別擴展了計算理論：</p>

  <ol>
    <li><strong>RP：</strong> 單向錯誤（Yes 對），如質數測試</li>
    <li><strong>co-RP：</strong> 單向錯誤（No 對）</li>
    <li><strong>ZPP = RP ∩ co-RP：</strong> 無錯誤但時間隨機（Las Vegas）</li>
    <li><strong>BPP：</strong> 雙向錯誤，但可 amplify（最廣泛使用）</li>
    <li><strong>PP：</strong> 雙向但難 amplify（較不實用）</li>
  </ol>

  <p><strong>大猜想：</strong> P = BPP（隨機不真的增加計算能力？）</p>

</div>

<hr />

<h2 id="參考資料">參考資料</h2>

<ul>
  <li>Arora &amp; Barak, <em>Computational Complexity: A Modern Approach</em>, Chapter 7</li>
  <li>Goldreich, <em>Computational Complexity: A Conceptual Perspective</em></li>
  <li>Sipser, <em>Introduction to the Theory of Computation</em>, Chapter 10</li>
</ul>]]></content><author><name>Chien-Chih Tseng</name></author><category term="隨機演算法" /><category term="複雜度理論" /><category term="P" /><category term="NP" /><category term="RP" /><category term="BPP" /><category term="ZPP" /><summary type="html"><![CDATA[從 Turing Machine 到 P/NP，再到隨機複雜度類別 RP/BPP/ZPP]]></summary></entry><entry><title type="html">隨機快速排序與選擇</title><link href="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/randomized-sorting.html" rel="alternate" type="text/html" title="隨機快速排序與選擇" /><published>2026-03-16T02:00:00+00:00</published><updated>2026-03-16T02:00:00+00:00</updated><id>https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/randomized-sorting</id><content type="html" xml:base="https://xiaomingtseng.github.io/blog/%E9%9A%A8%E6%A9%9F%E6%BC%94%E7%AE%97%E6%B3%95/2026/03/16/randomized-sorting.html"><![CDATA[<style>
:root {
  --accent: #667eea;
  --accent-light: #eef3fb;
  --border: #e5e5e0;
  --text-muted: #6b6b65;
}

.oneliner {
  background: var(--accent-light);
  border-left: 4px solid var(--accent);
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 32px 0;
  font-size: 1.05rem;
  font-style: italic;
  color: #1a3a6b;
}

.section {
  margin: 40px 0;
}

.section-label {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-family: monospace;
  font-size: 11px;
  font-weight: bold;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 14px;
}

.section-label::before {
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  background: #d4a847;
}

.section-label.blue::before { background: #4a90d9; }
.section-label.green::before { background: #5aaa72; }
.section-label.purple::before { background: #9b72c8; }
.section-label.red::before { background: #d96b5a; }

.math-block {
  background: #fafaf8;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 16px 20px;
  margin: 16px 0;
  overflow-x: auto;
}

.algo-box {
  background: #f8f9fa;
  border: 2px solid #667eea;
  border-radius: 8px;
  padding: 20px;
  margin: 20px 0;
  font-family: 'Courier New', monospace;
}

.algo-box .algo-title {
  font-weight: bold;
  color: #667eea;
  margin-bottom: 12px;
  font-size: 1.1rem;
}

.highlight-box {
  background: #fff8e6;
  border-left: 4px solid #d4a847;
  border-radius: 0 6px 6px 0;
  padding: 16px 20px;
  margin: 16px 0;
}

.code-block {
  background: #1e1e1e;
  color: #d4d4d4;
  padding: 16px;
  border-radius: 6px;
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
  overflow-x: auto;
  margin: 16px 0;
}
</style>

<!-- MathJax 配置 -->
<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$']],
    displayMath: [['$$', '$$']],
    tags: 'ams'
  }
};
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async=""></script>

<hr />

<h2 id="一句話解釋">一句話解釋</h2>

<div class="oneliner">
  <p>隨機選 pivot 讓 Quicksort 期望 O(n log n)，避免 worst-case O(n²)；隨機選擇演算法期望 O(n) 找第 k 小。</p>
</div>

<hr />

<h2 id="randomized-quicksort">Randomized QuickSort</h2>

<div class="section">
  <div class="section-label blue">演算法設計</div>

  <h3 id="quicksort-">確定性 Quicksort 的問題</h3>

  <p><strong>Worst-case：</strong> $O(n^2)$</p>
  <ul>
    <li>每次 pivot 都是最小/最大值</li>
    <li>例如已排序陣列 + 總是選第一個元素</li>
  </ul>

  <p><strong>問題：</strong> 對手（adversary）可以構造最壞輸入</p>

  <h3 id="section">隨機化解法</h3>

  <div class="algo-box">
<div class="algo-title">Algorithm: Randomized QuickSort</div>
<strong>Input:</strong> 陣列 $A[1..n]$<br />
<strong>Output:</strong> 排序後的陣列

<ol>
  <li>**If** $n \leq 1$: **Return** $A$</li>
  <li>**隨機均勻**選擇 pivot $p \in A$</li>
  <li>分割（Partition）：
    <ul style="list-style: none; padding-left: 20px;">
      <li>$L = \{x \in A : x &lt; p\}$</li>
      <li>$M = \{x \in A : x = p\}$</li>
      <li>$R = \{x \in A : x &gt; p\}$</li>
    </ul>
  </li>
  <li>遞迴排序 $L$ 和 $R$</li>
  <li>**Return** QuickSort$(L)$ + $M$ + QuickSort$(R)$</li>
</ol>
</div>

  <div class="code-block">
def randomized_quicksort(A):
    if len(A) &lt;= 1:
        return A
    
    pivot = random.choice(A)  # 隨機選 pivot
    L = [x for x in A if x &lt; pivot]
    M = [x for x in A if x == pivot]
    R = [x for x in A if x &gt; pivot]
    
    return randomized_quicksort(L) + M + randomized_quicksort(R)
</div>

  <h3 id="section-1">關鍵觀察</h3>

  <ul>
    <li><strong>隨機性在演算法內部</strong>，不依賴輸入分佈</li>
    <li><strong>任何</strong>輸入的期望時間都是 $O(n \log n)$</li>
    <li>Worst-case 仍是 $O(n^2)$，但機率極小</li>
  </ul>

</div>

<hr />

<h2 id="期望時間分析">期望時間分析</h2>

<div class="section">
  <div class="section-label green">比較次數</div>

  <h3 id="section-2">分析策略</h3>

  <p><strong>關鍵：</strong> 分析<strong>比較次數</strong>（dominate 運行時間）</p>

  <h3 id="section-3">設定</h3>

  <p>排序後陣列為 $z_1 \leq z_2 \leq \cdots \leq z_n$。</p>

  <p>定義<strong>指示變數</strong>：</p>

  <div class="math-block">

$$

X_{ij} = \begin{cases}
1 &amp; \text{若 } z_i \text{ 和 } z_j \text{ 有被比較} \\
0 &amp; \text{否則}
\end{cases}
$$

總比較次數：

$$

X = \sum_{i=1}^{n-1} \sum_{j=i+1}^n X_{ij}

$$

</div>

  <h3 id="section-4">期望值計算</h3>

  <div class="math-block">

用 **Linearity of Expectation**：

$$

\mathbb{E}[X] = \sum_{i=1}^{n-1} \sum_{j=i+1}^n \mathbb{E}[X_{ij}] = \sum_{i=1}^{n-1} \sum_{j=i+1}^n \Pr[z_i \text{ 和 } z_j \text{ 比較}]

$$

</div>

  <h3 id="section-5">關鍵引理</h3>

  <div class="math-block">

<strong>Lemma:</strong> 

$$\Pr[z_i \text{ 和 } z_j \text{ 比較}] = \frac{2}{j - i + 1}$$

<strong>證明思路：</strong>

$z_i$ 和 $z_j$ 會比較，若且唯若：
- 在 $\{z_i, z_{i+1}, \dots, z_j\}$ 中，**第一個被選為 pivot 的是 $z_i$ 或 $z_j$**

原因：
- 若先選中間某個 $z_k$（$i &lt; k &lt; j$），則 $z_i$ 和 $z_j$ 被分到不同子陣列，永不比較
- 若先選 $z_i$ 或 $z_j$，它們會在 partition 時比較

<strong>機率：</strong>

在 $\{z_i, \dots, z_j\}$ 共 $j-i+1$ 個元素中，隨機選一個作為第一個 pivot：

$$

\Pr[\text{選到 } z_i \text{ 或 } z_j] = \frac{2}{j-i+1}

$$

</div>

  <h3 id="section-6">最終計算</h3>

  <div class="math-block">

$$

\begin{align}
\mathbb{E}[X] &amp;= \sum_{i=1}^{n-1} \sum_{j=i+1}^n \frac{2}{j-i+1} \\
&amp;= \sum_{i=1}^{n-1} \sum_{k=2}^{n-i+1} \frac{2}{k} \quad (\text{令 } k = j-i+1) \\
&amp;\leq \sum_{i=1}^{n-1} \sum_{k=2}^{n} \frac{2}{k} \\
&amp;= (n-1) \cdot 2 \sum_{k=2}^{n} \frac{1}{k} \\
&amp;= (n-1) \cdot 2 (H_n - 1) \\
&amp;= O(n \log n)
\end{align}
$$

其中 $H_n = 1 + \frac{1}{2} + \cdots + \frac{1}{n} = \Theta(\log n)$ 是調和級數。

</div>

  <div class="highlight-box">
    <p><strong>🎯 結論：</strong><br />
Randomized QuickSort 的期望比較次數是 $O(n \log n)$，對<strong>任何</strong>輸入都成立！</p>
  </div>

</div>

<hr />

<h2 id="randomized-selection第-k-小">Randomized Selection（第 k 小）</h2>

<div class="section">
  <div class="section-label purple">QuickSelect</div>

  <h3 id="section-7">問題</h3>

  <p><strong>輸入：</strong> 陣列 $A[1..n]$，整數 $k \in [1, n]$<br />
<strong>輸出：</strong> 第 $k$ 小的元素</p>

  <h3 id="section-8">演算法</h3>

  <div class="algo-box">
<div class="algo-title">Algorithm: Randomized Select</div>

<ol>
  <li>隨機選 pivot $p \in A$</li>
  <li>分割成 $L, M, R$（同 QuickSort）</li>
  <li>**If** $k \leq |L|$: **Return** Select$(L, k)$</li>
  <li>**Else If** $k \leq |L| + |M|$: **Return** $p$</li>
  <li>**Else**: **Return** Select$(R, k - |L| - |M|)$</li>
</ol>
</div>

  <div class="code-block">
def randomized_select(A, k):
    if len(A) == 1:
        return A[0]
    
    pivot = random.choice(A)
    L = [x for x in A if x &lt; pivot]
    M = [x for x in A if x == pivot]
    R = [x for x in A if x &gt; pivot]
    
    if k &lt;= len(L):
        return randomized_select(L, k)
    elif k &lt;= len(L) + len(M):
        return pivot
    else:
        return randomized_select(R, k - len(L) - len(M))
</div>

  <h3 id="section-9">關鍵差異</h3>

  <ul>
    <li>QuickSort：遞迴<strong>兩邊</strong></li>
    <li>QuickSelect：只遞迴<strong>一邊</strong>（包含第 $k$ 小的那邊）</li>
  </ul>

</div>

<hr />

<h2 id="quickselect-期望分析">QuickSelect 期望分析</h2>

<div class="section">
  <div class="section-label red">期望時間</div>

  <h3 id="section-10">遞迴關係</h3>

  <p>令 $T(n)$ 是期望運行時間。</p>

  <div class="math-block">

<strong>Partition 的期望行為：</strong>

假設 pivot 落在排序後的第 $i$ 位置（$1 \leq i \leq n$），機率 $\frac{1}{n}$。

- 若 $k \leq i$：遞迴到 $L$，大小 $\leq i-1$
- 若 $k &gt; i$：遞迴到 $R$，大小 $\leq n-i$

<strong>遞迴式：</strong>

$$

T(n) \leq \frac{1}{n} \sum_{i=1}^{n} \left[ O(n) + T(\max(i-1, n-i)) \right]

$$

</div>

  <h3 id="section-11">簡化分析</h3>

  <div class="math-block">

<strong>定義「好的 pivot」：</strong>

pivot 落在中間 50%（第 $n/4$ 到第 $3n/4$ 位）。

機率：$\frac{1}{2}$

好的 pivot → 問題大小縮小到 $\leq \frac{3n}{4}$

<strong>期望步數直到好的 pivot：</strong> 2 次

<strong>期望總時間：</strong>

$$

T(n) \leq 2 \cdot O(n) + T(3n/4) = O(n) + T(3n/4)

$$

<strong>展開：</strong>

$$

\begin{align}
T(n) &amp;\leq cn + T(3n/4) \\
&amp;\leq cn + c(3n/4) + T((3/4)^2 n) \\
&amp;\leq cn \sum_{i=0}^\infty (3/4)^i = cn \cdot \frac{1}{1 - 3/4} = 4cn = O(n)
\end{align}

$$

</div>

  <div class="highlight-box">
    <p><strong>🎯 結論：</strong><br />
Randomized Select 的期望時間是 $O(n)$，<strong>線性時間</strong>找第 k 小！</p>
  </div>

  <h3 id="section-12">與確定性演算法比較</h3>

  <p><strong>確定性 Median-of-Medians 演算法：</strong></p>
  <ul>
    <li>Worst-case $O(n)$</li>
    <li>但常數很大，實務上較慢</li>
  </ul>

  <p><strong>Randomized Select：</strong></p>
  <ul>
    <li>期望 $O(n)$，worst-case $O(n^2)$（機率極小）</li>
    <li>簡單實作，實務上很快</li>
  </ul>

</div>

<hr />

<h2 id="實務考量">實務考量</h2>

<div class="section">

  <h3 id="hybrid-">Hybrid 策略</h3>

  <p>實務中常用的優化：</p>

  <ol>
    <li><strong>小陣列用 Insertion Sort</strong>（$n \leq 10$）</li>
    <li><strong>Median-of-3：</strong> 選三個元素的中位數作 pivot（降低壞 pivot 機率）</li>
    <li><strong>三分法：</strong> 分成 $&lt; p$, $= p$, $&gt; p$ 處理重複元素</li>
  </ol>

  <h3 id="python--sorted">Python 的 sorted()</h3>

  <p>CPython 使用 <strong>Timsort</strong>（基於 Merge Sort + Insertion Sort），不是 Quicksort。</p>

  <p>原因：</p>
  <ul>
    <li>Stable（穩定排序）</li>
    <li>對部分排序資料很快</li>
    <li>Worst-case $O(n \log n)$（Quicksort 是期望）</li>
  </ul>

  <p>但很多語言（C++ std::sort, Java）用混合的 Quicksort。</p>

</div>

<hr />

<h2 id="總結">總結</h2>

<div class="section">

  <p><strong>Randomized Sorting &amp; Selection</strong> 是隨機演算法的經典應用：</p>

  <ol>
    <li><strong>Randomized QuickSort：</strong>
      <ul>
        <li>期望 $O(n \log n)$ 比較</li>
        <li>簡單、實用、快速</li>
        <li>分析用 Linearity of Expectation</li>
      </ul>
    </li>
    <li><strong>Randomized Select：</strong>
      <ul>
        <li>期望 $O(n)$ 找第 $k$ 小</li>
        <li>比確定性演算法簡單得多</li>
        <li>關鍵：只遞迴一邊</li>
      </ul>
    </li>
    <li><strong>分析技巧：</strong>
      <ul>
        <li>指示變數 + Linearity</li>
        <li>「好的 pivot」機率分析</li>
        <li>幾何級數求和</li>
      </ul>
    </li>
  </ol>

</div>

<hr />

<h2 id="參考資料">參考資料</h2>

<ul>
  <li>CLRS, <em>Introduction to Algorithms</em>, Chapter 7 &amp; 9</li>
  <li>Motwani &amp; Raghavan, <em>Randomized Algorithms</em>, Chapter 1</li>
  <li>Hoare, “Quicksort” (1961)</li>
</ul>]]></content><author><name>Chien-Chih Tseng</name></author><category term="隨機演算法" /><category term="Randomized Quicksort" /><category term="Selection" /><category term="期望分析" /><summary type="html"><![CDATA[Randomized QuickSort 期望 O(n log n)，Randomized Select 期望 O(n)]]></summary></entry></feed>