<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>BigQuery - 東東 GCP 教學 - GCP 實戰講師</title>
	<atom:link href="https://dongdonggcp.com/tag/bigquery/feed/" rel="self" type="application/rss+xml" />
	<link>https://dongdonggcp.com</link>
	<description>助你考取證照，轉職成功</description>
	<lastBuildDate>Sun, 25 Oct 2026 12:08:47 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://dongdonggcp.com/wp-content/uploads/2025/04/cropped-340838097_121391010914395_5443948698124160121_n-32x32.jpg</url>
	<title>BigQuery - 東東 GCP 教學 - GCP 實戰講師</title>
	<link>https://dongdonggcp.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>ML 用哪個資料服務？BigQuery、Cloud Storage、Feature Store、Bigtable 怎麼選</title>
		<link>https://dongdonggcp.com/2026/10/25/gcp-data-services-for-ml-bigquery-cloud-storage-feature-store-bigtable/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=gcp-data-services-for-ml-bigquery-cloud-storage-feature-store-bigtable</link>
					<comments>https://dongdonggcp.com/2026/10/25/gcp-data-services-for-ml-bigquery-cloud-storage-feature-store-bigtable/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 25 Oct 2026 05:46:00 +0000</pubDate>
				<category><![CDATA[AI 和機器學習]]></category>
		<category><![CDATA[證照考試]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[BigQuery]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[PMLE]]></category>
		<category><![CDATA[Vertex AI]]></category>
		<category><![CDATA[機器學習]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=12888</guid>

					<description><![CDATA[<p>ML 用哪個資料服務？算延遲預算：線上預測剩 50 毫秒查特徵，BigQuery 以秒計不行，要用 Bigtable；Feature Store V2、Dataflow vs Spark、預訓練 AI API 怎麼選，附 PMLE 考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/10/25/gcp-data-services-for-ml-bigquery-cloud-storage-feature-store-bigtable/">ML 用哪個資料服務？BigQuery、Cloud Storage、Feature Store、Bigtable 怎麼選</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>ML 用哪個資料服務？訓練用 BigQuery、檔案放 Cloud Storage、線上查特徵用 Feature Store 配 Bigtable。</strong></p>



<p class="wp-block-paragraph">機器學習的資料不是「存起來」就好。訓練時要一次掃幾億筆，線上預測時要在幾十毫秒內查出一個會員的特徵，照片和模型檔又是另一種東西。一個服務做不到全部，所以 Google Cloud 有一整排：BigQuery、Cloud Storage、Bigtable、Memorystore、Feature Store，再加上處理資料的 Dataflow、Spark，和直接拿來用的 AI API。</p>



<p class="wp-block-paragraph">這篇把 PMLE 筆記最後一塊「基礎服務與工具」一次整理：<strong>存在哪、怎麼算、怎麼端上桌</strong>，每個服務用一句白話加一個飲料店的情境，最後給你一張「看到什麼需求就選什麼」的表。</p>



<p class="wp-block-paragraph">照系列慣例先說名稱：Vertex AI 在 2026 年 4 月起改名為 <strong>Gemini Enterprise Agent Platform</strong>（簡稱 Agent Platform），Feature Store 現在叫 Feature Store on Gemini Enterprise Agent Platform；Dataproc 改叫 Managed Service for Apache Spark；Cloud Composer 改叫 Managed Service for Apache Airflow；Cloud Functions 改叫 Cloud Run functions。文末有完整對照表。</p>



<p class="wp-block-paragraph">一樣用有 2,000 間分店、50 萬名會員的連鎖飲料店當例子（教學假設）：POS 每天進 300 萬筆交易、App 有會員照片、要做流失模型和推薦。</p>



<figure class="wp-block-image aligncenter size-full"><img fetchpriority="high" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-01-four-stores.png" alt="ML 用哪個資料服務：用飲料店比喻四個儲存服務，BigQuery 是總部帳本用 SQL 問大問題、Cloud Storage 是倉庫什麼檔案都能放、Bigtable 是櫃台的會員卡機按卡號毫秒內查出、Memorystore 是櫃台抽屜最快但小又貴，Feature Store 是特徵的統一供應站" class="wp-image-12883" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-01-four-stores.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-01-four-stores-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-01-four-stores-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-01-four-stores-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>存錯地方，模型上線就慢</strong>：線上預測要在 100 毫秒內回答，去 BigQuery 查一筆要一秒以上，整個端點就卡住。這是最常見的架構錯誤</li>

<li><strong>算錯地方，帳單爆炸</strong>：每天 300 萬筆交易用 Python 在筆記本裡跑，記憶體爆掉；全部丟 Spark 叢集又貴。考試指南 2.1 直接寫「<strong>依規模和複雜度選前處理工具</strong>」</li>

<li><strong>重複造輪子</strong>：Vision API 一行呼叫就能 OCR，很多人還是自己訓練模型。考試 1.2 考的就是「什麼時候用現成的 API」</li>

<li><strong>證照必考</strong>：2.1 選前處理工具與 Feature Store、3.2 訓練資料放 Cloud Storage 還是 BigQuery、4.2 用 Feature Store 服務特徵、1.2 產業 API，這篇全包</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">1. 先搞懂：資料有三種用法，服務跟著分三類</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph">機器學習對資料有三種動作，每種對速度的要求不一樣：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>動作</th><th>白話</th><th>要多快</th><th>飲料店</th></tr></thead><tbody><tr><td><strong>分析與訓練</strong></td><td>一次掃<strong>幾億筆</strong>，算統計、做特徵、訓練模型</td><td>幾秒到幾分鐘都可以</td><td>算每個會員 90 天來店次數</td></tr><tr><td><strong>線上查詢</strong></td><td>預測當下，查<strong>一個人</strong>的資料</td><td><strong>幾十毫秒內</strong></td><td>會員掃碼，馬上推薦一杯</td></tr><tr><td><strong>放檔案</strong></td><td>照片、影片、模型檔、CSV，<strong>整個檔案</strong>存取</td><td>看情況</td><td>50 萬會員的照片、訓練好的模型檔</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>毫秒</strong>是千分之一秒。眨一次眼大約 100～150 毫秒，線上預測的預算常常就是「一次眨眼」。</p>



<h3 class="wp-block-heading">比喻：飲料店的四個地方</h3>


<ul class="wp-block-list">
<li><strong>BigQuery</strong> 是<strong>總部的帳本</strong>：所有交易都記在這，老闆問「哪個分店的珍奶賣最好」，一句 SQL 幾秒就有答案。但要查「這一位會員剛剛買什麼」，翻帳本太慢</li>

<li><strong>Cloud Storage</strong> 是<strong>倉庫</strong>：什麼都能放，照片、影片、模型檔、備份，按件計價，一件一件拿</li>

<li><strong>Bigtable</strong> 是<strong>櫃台的會員卡機</strong>：刷卡號，毫秒內跳出這個人的資料，而且全台 2,000 家同時刷也不卡。但它只認卡號，不能問「誰買最多」</li>

<li><strong>Memorystore</strong> 是<strong>櫃台抽屜</strong>：手伸過去就拿到，最快，但空間小、放的是最常用的幾樣</li>
</ul>



<p class="wp-block-paragraph"><strong>Feature Store</strong> 不是第五個倉庫，它是<strong>特徵的供應站</strong>：帳本（BigQuery）算好的特徵，自動搬一份到會員卡機（Bigtable），訓練和線上預測拿到的是同一份。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">這些名字對應四種資料庫家族：<strong>資料倉儲</strong>（data warehouse，給分析用）、<strong>物件儲存</strong>（object storage，放檔案）、<strong>NoSQL</strong>（不用表格、按鍵查值、能橫向擴張）、<strong>快取</strong>（cache，放記憶體的暫存）。BigQuery 是 Google 把內部的 Dremel 做成服務，Bigtable 是 2006 年那篇著名論文的服務版，Cloud Storage 對應其他雲的 S3。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">考題給你一個情境（延遲、資料量、資料長相），問你選哪個。分不清「分析用」和「線上查詢用」，一定選錯。</p>



<figure class="wp-block-image aligncenter size-full"><img decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-02-latency-budget.png" alt="線上預測的延遲預算算一次：端點要在 100 毫秒內回應，扣掉網路 20 毫秒和模型推論 30 毫秒，剩 50 毫秒查特徵；BigQuery 單筆查詢以秒計所以不行，Bigtable 毫秒級可以，Memorystore 次毫秒最快但容量小；旁邊是存什麼選哪個的決策表" class="wp-image-12884" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-02-latency-budget.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-02-latency-budget-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-02-latency-budget-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-02-latency-budget-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">2. 四個儲存服務，各自長什麼樣</h2>



<h3 class="wp-block-heading">BigQuery：分析與訓練的主場</h3>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/bigquery/docs/introduction">官方</a>叫它「全代管、AI 就緒的資料平台」：<strong>無伺服器</strong>（白話：你不用開機器，丟 SQL 進去就跑），儲存和運算分開，查 TB 級資料幾秒、PB 級幾分鐘。</p>



<p class="wp-block-paragraph">跟機器學習有關的：</p>


<ul class="wp-block-list">
<li><strong>欄位式儲存</strong>：一次只讀用到的欄，算特徵快又便宜（第 15 篇 BigQuery ML 直接在裡面訓練）</li>

<li><strong>串流寫入</strong>：Storage Write API；Pub/Sub 有 <a href="https://docs.cloud.google.com/pubsub/docs/bigquery">BigQuery 訂閱</a>可以把訊息直接寫進表，不用 Dataflow</li>

<li><strong>Feature Store V2 的離線倉庫就是它</strong>（下一節）</li>

<li>站上有兩篇講過：<a href="https://dongdonggcp.com/2025/07/04/is-bigquery-a-database-what-is-the-usage/">BigQuery 跟資料庫差在哪</a>、<a href="https://dongdonggcp.com/2026/03/27/bigquery-billing-guide/">BigQuery 計費方式</a></li>
</ul>



<p class="wp-block-paragraph"><strong>不適合</strong>：單筆低延遲查詢。它是為掃全表設計的，查一筆也要排程啟動，通常以秒計。</p>



<h3 class="wp-block-heading">Cloud Storage：檔案、照片、模型檔</h3>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/storage/docs/introduction">官方</a>：存<strong>非結構化資料</strong>的服務，資料是<strong>物件</strong>（object，白話就是一個檔案），放在<strong>值區</strong>（bucket，白話是資料夾的最上層）。耐久度 11 個 9（一年掉一個檔的機率是千億分之一）。</p>



<p class="wp-block-paragraph">機器學習用它放：訓練影像（第 13 篇的 TFRecords）、模型檔、管線的中間產物（第 18 篇）、TensorBoard 日誌（第 22 篇）。考試 3.2 寫「訓練資料放在 Cloud Storage 和 BigQuery」：<strong>表格資料放 BigQuery，檔案類放 Cloud Storage</strong>。</p>



<p class="wp-block-paragraph"><strong>儲存類別</strong>（<a href="https://docs.cloud.google.com/storage/docs/storage-classes">官方表</a>）是考點，差別在「多久拿一次」：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>類別</th><th>最短存放天數</th><th>取回費</th><th>適合</th></tr></thead><tbody><tr><td><strong>Rapid</strong></td><td>無</td><td>無</td><td>單一區域、AI／ML 訓練要極高吞吐，配 Rapid Bucket</td></tr><tr><td><strong>Standard</strong></td><td>無</td><td>無</td><td>常常讀的「熱」資料：正在訓練的資料集</td></tr><tr><td><strong>Nearline</strong></td><td>30 天</td><td>有</td><td>一個月碰一次：上個月的訓練快照</td></tr><tr><td><strong>Coldline</strong></td><td>90 天</td><td>有</td><td>一季碰一次：舊版訓練資料</td></tr><tr><td><strong>Archive</strong></td><td>365 天</td><td>有</td><td>一年碰不到一次：法規要留的原始資料</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">算一次給你看：照片放哪一級</h3>



<p class="wp-block-paragraph">飲料店 50 萬會員、每人 20 張照片、每張 2 MB（教學假設）：</p>



<pre class="wp-block-code"><code>50 萬 × 20 × 2 MB = 20,000,000 MB = 20 TB</code></pre>



<p class="wp-block-paragraph">訓練封膜檢查模型（第 14 篇）用過這批照片之後，接下來 90 天內不會再碰。選 <strong>Coldline</strong>（最短 90 天剛好）。如果貪便宜放 <strong>Archive</strong>，第 100 天要重訓拿出來：</p>


<ul class="wp-block-list">
<li>取回費要付</li>

<li>最短 365 天，<strong>就算第 100 天刪掉，也照 365 天收費</strong></li>
</ul>



<p class="wp-block-paragraph"><strong>數字怎麼看</strong>：類別越冷，每 GB 月費越低，但最短天數和取回費越高。「多久拿一次」才是選擇依據，不是「現在想省多少」。不確定就開 <strong>Autoclass</strong>，讓 Cloud Storage 依存取頻率自動換類別。</p>



<h3 class="wp-block-heading">Bigtable：線上預測查特徵</h3>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/bigtable/docs/overview">官方</a>：<strong>稀疏表</strong>，能到幾十億列、幾千欄，存 TB 到 PB，<strong>單一鍵值</strong>（single-keyed）資料的低延遲讀寫，高吞吐。</p>



<p class="wp-block-paragraph">白話：一張超大的表，每列有一個 <strong>row key</strong>（列鍵，像會員卡號），只能靠這個鍵快速查，查到就是毫秒級。欄沒用到不占空間，所以叫「稀疏」。適合時間序列、購買紀錄、IoT 資料，官方明寫「機器學習應用」。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>特色</th><th>白話</th></tr></thead><tbody><tr><td>加節點就變快</td><td>2,000 家分店同時刷，加機器就撐得住，不停機</td></tr><tr><td>HBase 相容</td><td>原本用 Hadoop 生態的程式搬過來不用改</td></tr><tr><td>自動擴縮</td><td>看 CPU 自動加減節點</td></tr><tr><td>免費試用</td><td>10 天、500 GB SSD、1 個節點，可延到 90 天</td></tr><tr><td>分層儲存（預覽）</td><td>不常用的資料放便宜的層；還有記憶體層做次毫秒讀取</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>不適合</strong>：問「誰買最多」這種要掃全表的分析，那是 BigQuery 的事。</p>



<h3 class="wp-block-heading">Memorystore：最快的那一層</h3>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview">官方</a>：全代管的 <strong>Redis</strong>（開源的記憶體資料庫），<strong>次毫秒</strong>存取。有 Redis、Redis Cluster，和較新的 <a href="https://docs.cloud.google.com/memorystore/docs/valkey/product-overview">Valkey</a>（Redis 的開源分支）三種。</p>



<p class="wp-block-paragraph">白話：資料放<strong>記憶體</strong>不放硬碟，所以最快；代價是貴、容量有限（單一 Redis 執行個體到 300 GB）。機器學習用它放：推薦結果的快取、熱門會員的特徵、Dataflow 串流處理的中間資料。</p>



<h3 class="wp-block-heading">四個放一起</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th><strong>BigQuery</strong></th><th><strong>Cloud Storage</strong></th><th><strong>Bigtable</strong></th><th><strong>Memorystore</strong></th></tr></thead><tbody><tr><td>存什麼</td><td>表格</td><td>檔案</td><td>鍵值、寬表</td><td>鍵值（記憶體）</td></tr><tr><td>怎麼查</td><td>SQL，掃全表</td><td>整個檔案拿</td><td>按 row key</td><td>按 key</td></tr><tr><td>延遲</td><td>秒</td><td>看檔案大小</td><td>毫秒</td><td>次毫秒</td></tr><tr><td>容量</td><td>PB</td><td>無上限</td><td>PB</td><td>GB 級</td></tr><tr><td>ML 用途</td><td>分析、特徵、訓練、BigQuery ML</td><td>影像、模型檔、管線產物</td><td>線上特徵、時間序列</td><td>快取、熱資料</td></tr><tr><td>飲料店</td><td>總部帳本</td><td>倉庫</td><td>會員卡機</td><td>櫃台抽屜</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">算一次給你看：延遲預算</h3>



<p class="wp-block-paragraph">線上預測端點（第 17 篇）要求 100 毫秒內回應（教學假設）：</p>



<pre class="wp-block-code"><code>總預算：100 ms
− 網路來回：20 ms
− 模型推論：30 ms
= 剩 50 ms 給「查特徵」

BigQuery 單筆查詢：通常 1,000 ms 以上 → 超出 20 倍，不行
Bigtable 單列讀取：毫秒級（假設 5 ms）→ 可以
Memorystore：次毫秒（假設 0.5 ms）→ 可以，但要放得下</code></pre>



<p class="wp-block-paragraph"><strong>數字怎麼看</strong>：預算越緊（例如要 20 毫秒），越要往記憶體靠；資料越大（幾 TB 的會員特徵），越要用 Bigtable 而不是 Memorystore。這題的答案不是「哪個最快」，是「<strong>在預算內、放得下、最便宜</strong>」。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">3. Feature Store：訓練和線上用同一份特徵</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>Feature Store on Gemini Enterprise Agent Platform</strong>（舊名 Vertex AI Feature Store）：把算好的特徵集中管理，<strong>訓練時從 BigQuery 拿、線上預測時從 Bigtable 拿，兩邊是同一份</strong>。<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/featurestore/latest/overview">官方</a>：它是 BigQuery 資料來源上面的一層<strong>中繼資料層</strong>，直接從 BigQuery 把最新特徵值搬去線上服務。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">中央廚房。各分店不自己熬珍珠（各團隊不自己算「90 天來店次數」），總部熬好一鍋（BigQuery 算好），配送到每家店的保溫桶（線上倉庫）。客人拿到的和品管抽驗的是同一鍋。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">第 20 篇講的<strong>訓練與服務偏差</strong>（training-serving skew）最常見的原因就是：訓練時特徵用 SQL 算，上線時工程師用另一套程式重算，兩邊不一樣。Feature Store 的存在理由就是讓它們<strong>只有一個來源</strong>。另一個理由是重用：推薦模型和流失模型都要「90 天來店次數」，算一次大家用。</p>



<h3 class="wp-block-heading">現在的版本（V2）長什麼樣</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>元件</th><th>白話</th><th>飲料店</th></tr></thead><tbody><tr><td><strong>離線倉庫</strong></td><td>就是 <strong>BigQuery 的表或檢視</strong>，每欄一個特徵、有 ID 欄和時間戳記欄；<strong>不用另外複製</strong></td><td><code>member_features</code> 表</td></tr><tr><td><strong>Feature group／Feature</strong></td><td>把 BigQuery 表登記進<strong>特徵登錄表</strong>（registry），可選；登記了才能按時間戳記只給最新值、才能<strong>監控漂移</strong></td><td>登記「90 天來店次數」「距上次消費天數」</td></tr><tr><td><strong>Online store</strong></td><td>線上服務叢集</td><td>會員卡機</td></tr><tr><td><strong>Feature view</strong></td><td>從 registry 或 BigQuery 挑幾個特徵，掛到 online store，<strong>排程同步</strong></td><td>推薦模型要的 8 個特徵</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">線上服務有兩種：</p>


<ul class="wp-block-list">
<li><strong>Bigtable online serving</strong>：給 TB 級、常更新的資料，<strong>不支援嵌入</strong>（第 11 篇的向量）</li>

<li><strong>Optimized online serving</strong>：超低延遲、支援嵌入，但<strong>已在 2026 年 2 月 17 日淘汰、2027 年 2 月 17 日停用</strong>；<a href="https://docs.cloud.google.com/vertex-ai/docs/deprecations">淘汰公告</a>要你改用 Bigtable online serving，嵌入改用 <strong>Vector Search</strong></li>
</ul>



<p class="wp-block-paragraph"><strong>Vertex AI Feature Store（Legacy）</strong>，也就是舊題庫寫的 featurestore／entity type 那套，同樣 2026 年 2 月 17 日淘汰、2027 年 2 月 17 日停用，官方說要搬到 V2。</p>



<h3 class="wp-block-heading">算一次給你看：同步頻率</h3>



<p class="wp-block-paragraph">Feature view 排程從 BigQuery 同步到線上（教學假設）：</p>



<pre class="wp-block-code"><code>每小時同步一次 → 線上拿到的特徵最舊 60 分鐘
改成每 10 分鐘 → 最舊 10 分鐘，但同步次數 × 6，費用跟著上升</code></pre>



<p class="wp-block-paragraph"><strong>數字怎麼看</strong>：「特徵多新鮮」和「花多少錢」是對換的。流失模型看 90 天行為，一小時一次夠；要做「剛剛買了 A 就推 B」這種即時特徵，Feature Store 的排程同步不夠，要走第 4 節的 Dataflow 串流直接寫 Bigtable。</p>



<figure class="wp-block-image aligncenter size-full"><img decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-03-feature-store-v2.png" alt="Feature Store V2 的結構：BigQuery 表就是離線倉庫不用另外複製，登記成 feature group 和 feature 後，feature view 排程同步到 online store 用 Bigtable online serving 給線上端點查，訓練直接從 BigQuery 拿，兩邊同一份避免訓練與服務偏差；Legacy 與 Optimized online serving 2027 年 2 月停用，嵌入改用 Vector Search" class="wp-image-12885" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-03-feature-store-v2.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-03-feature-store-v2-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-03-feature-store-v2-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-03-feature-store-v2-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">4. 處理資料：BigQuery SQL、Dataflow、Spark、Python 怎麼選</h2>



<p class="wp-block-paragraph">考試指南 2.1 的原話：「依<strong>規模</strong>和<strong>複雜度</strong>選前處理工具（例如 BigQuery SQL、Dataflow、Apache Spark、記憶體內的 Python 框架）」。四個工具的分界：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>工具</th><th>白話</th><th>什麼時候選</th><th>飲料店</th></tr></thead><tbody><tr><td><strong>Python（pandas）</strong></td><td>在筆記本裡、<strong>全部塞進記憶體</strong></td><td>資料幾 GB 以內，探索階段</td><td>抽 10 萬筆看分布</td></tr><tr><td><strong>BigQuery SQL</strong></td><td>資料已經在 BigQuery，<strong>用 SQL 做特徵</strong></td><td>表格、能用 SQL 表達的轉換，規模不是問題</td><td>算每個會員 90 天來店次數</td></tr><tr><td><strong>Dataflow</strong></td><td>Google 代管的 <strong>Apache Beam</strong>，<strong>批次和串流同一套程式</strong></td><td>要<strong>即時</strong>處理、要<strong>自訂程式邏輯</strong>、資料從 Pub/Sub 來</td><td>交易一進來就更新「最近一筆」特徵</td></tr><tr><td><strong>Managed Service for Apache Spark</strong></td><td>代管的 <strong>Spark／Hadoop</strong>（舊名 <strong>Dataproc</strong>）</td><td>已有 Spark 程式、要用 Spark MLlib、團隊熟 Spark</td><td>把舊的 Spark 特徵程式搬上雲</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">Dataflow</h3>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/dataflow/docs/overview">官方</a>：<strong>統一的串流與批次處理</strong>，全代管、自動擴縮，預設<strong>恰好一次</strong>（exactly-once）處理。用途包括「串流資料的即時 ML 分析」、ETL 進 BigQuery。</p>



<p class="wp-block-paragraph">白話：寫一次 Beam 程式，歷史資料用批次跑、新資料用串流跑，邏輯同一份，正好解決第 20 篇的偏差。它有<strong>範本</strong>（templates）：Pub/Sub 到 BigQuery 這種常見流程不用寫程式。</p>



<p class="wp-block-paragraph"><strong>Pub/Sub</strong> 是訊息佇列（站上有<a href="https://dongdonggcp.com/2025/08/06/cloud-pub-sub-tutorial-better-than-rabbitmq-mqtt/">教學</a>），白話是「郵筒」：POS 把交易丟進去，誰要就來收。<a href="https://docs.cloud.google.com/pubsub/docs/bigquery">官方</a>說：訊息<strong>不用處理</strong>直接進表，用 BigQuery 訂閱就好，省掉 Dataflow；要<strong>轉換、開窗、彙總</strong>才用 Dataflow。</p>



<h3 class="wp-block-heading">Managed Service for Apache Spark（舊名 Dataproc）</h3>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/dataproc/docs/concepts/overview">官方</a>：叢集 90 秒內開好，每個 vCPU 每小時 1 美分加上機器費，整合 BigQuery、Cloud Storage、Bigtable。另有 <a href="https://docs.cloud.google.com/dataproc-serverless/docs/overview">Serverless 版</a>：不開叢集，丟批次工作或在 BigQuery Studio 筆記本開互動 session。站上有<a href="https://dongdonggcp.com/2025/04/23/whai-is-dataproc-architecture-and-usage-introduction/">Dataproc 是什麼</a>。</p>



<p class="wp-block-paragraph"><strong>Dataflow vs Spark 怎麼選</strong>（考試愛考）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>看到</th><th>選</th></tr></thead><tbody><tr><td>「串流」「即時」「Pub/Sub」「Beam」「批次串流同一套」</td><td><strong>Dataflow</strong></td></tr><tr><td>「已有 Spark／Hadoop 程式」「MLlib」「Hive」「搬遷」</td><td><strong>Managed Service for Apache Spark</strong></td></tr><tr><td>「不想管叢集」「偶爾跑一次 Spark」</td><td><strong>Serverless Spark</strong></td></tr><tr><td>「資料在 BigQuery、SQL 做得到」</td><td><strong>BigQuery SQL</strong>，最省事</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">不寫程式的：Data Fusion、Dataprep</h3>


<ul class="wp-block-list">
<li><strong>Cloud Data Fusion</strong>：<a href="https://docs.cloud.google.com/data-fusion/docs/concepts/overview">官方</a>說是「全代管的資料整合服務」，用開源 CDAP，<strong>拖拉點選</strong>建 ETL 管線，批次和即時都行。白話：給不想寫程式的資料工程師</li>

<li><strong>Dataprep</strong>：筆記寫的「資料清理與探索」工具，是 Trifacta（後來被 Alteryx 收購）的產品。現況：Google 的 Dataprep 產品頁已經<strong>導向 BigQuery</strong>，主控台裡以 <strong>Alteryx Designer Cloud</strong> 的名稱出現；Google 自己主推的是 <a href="https://docs.cloud.google.com/bigquery/docs/data-prep-introduction">BigQuery 內建的資料準備</a>，用 Gemini 看資料給清理建議，Dataform 排程。舊題庫看到 Dataprep，知道它是第三方工具、現在有 BigQuery 內建替代</li>
</ul>



<h3 class="wp-block-heading">排程與協調：Managed Service for Apache Airflow</h3>



<p class="wp-block-paragraph">第 18 篇講過，<strong>Cloud Composer</strong> 現在叫 <a href="https://docs.cloud.google.com/composer/docs/composer-3/composer-overview">Managed Service for Apache Airflow</a>，用 DAG 排整條資料流程：每天凌晨 Spark 算特徵 → BigQuery 更新 → Feature view 同步 → 觸發訓練管線。考試 5.1 把它和 Agent Platform Pipelines、Ray 並列為協調工具。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-04-processing-and-apis.png" alt="資料處理工具怎麼選：幾 GB 以內用 Python 在記憶體裡做、資料在 BigQuery 用 SQL 做特徵、要即時或自訂邏輯用 Dataflow 的 Beam 批次串流同一套、已有 Spark 程式用 Managed Service for Apache Spark 舊名 Dataproc、不寫程式用 Data Fusion；預訓練 AI API 一覽：Vision、Natural Language、Speech-to-Text、Translation、Document AI、AI Commerce Search" class="wp-image-12886" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-04-processing-and-apis.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-04-processing-and-apis-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-04-processing-and-apis-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-04-processing-and-apis-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">5. 現成的 AI API：先問「有沒有人做好了」</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>預訓練 API</strong>（pre-trained API）：Google 已經用海量資料訓練好的模型，你<strong>丟資料進去拿結果</strong>，不用準備訓練資料、不用訓練。考試 1.2 寫「用產業專用 API（Document AI、Vision、Translate）建方案」。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">買現成的手搖飲料基底，而不是自己種茶葉。自己種（自訂訓練）只有在現成的味道不對時才值得。</p>



<h3 class="wp-block-heading">有哪些</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>API</th><th>做什麼</th><th>飲料店</th></tr></thead><tbody><tr><td><strong>Vision API</strong></td><td><a href="https://docs.cloud.google.com/vision/docs/features-list">功能表</a>：OCR（一般文字、密集文件與手寫）、標籤、物件定位、logo、地標、裁切建議、以圖搜圖</td><td>讀發票、找出杯子上的 logo</td></tr><tr><td><strong>Natural Language API</strong></td><td><a href="https://docs.cloud.google.com/natural-language/docs/basics">功能</a>：情感、實體、實體情感、語法、內容分類，自動偵測語言</td><td>評論是正面還是負面、提到哪家分店</td></tr><tr><td><strong>Speech-to-Text</strong></td><td><a href="https://docs.cloud.google.com/speech-to-text/docs/basics">三種模式</a>：同步（1 分鐘內）、非同步（到 480 分鐘）、串流（邊講邊轉）；建議 16 kHz</td><td>客服電話轉文字</td></tr><tr><td><strong>Cloud Translation</strong></td><td><a href="https://docs.cloud.google.com/translate/docs/overview">兩版</a>：Basic 用 NMT 模型；Advanced 多了翻譯 LLM、詞彙表、文件翻譯、批次</td><td>菜單翻成日文，「珍珠」固定譯法用詞彙表</td></tr><tr><td><strong>Document AI</strong></td><td><a href="https://docs.cloud.google.com/document-ai/docs/overview">處理器</a>分三類：數位化（Enterprise Document OCR）、擷取（Form Parser、Layout Parser、自訂擷取器）、分類（自訂分類器、分割器）</td><td>供應商發票自動填進系統</td></tr><tr><td><strong>AI Commerce Search</strong></td><td>舊名 <strong>Recommendations AI</strong>、Vertex AI Search for Commerce；<a href="https://docs.cloud.google.com/retail/docs/overview">同一份</a>商品目錄＋使用者事件同時做推薦和搜尋</td><td>App 的「你可能也喜歡」</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">怎麼判斷「用 API 還是自己訓練」</h3>


<ol class="wp-block-list">
<li>任務是通用的（OCR、翻譯、情感）→ <strong>API</strong></li>

<li>API 做得到但類別要客製（「封膜有沒有破」不在 Vision 的標籤裡）→ 第 14 篇的 <strong>AutoML 影像</strong>，或 Document AI 的自訂擷取器</li>

<li>文字、影片的客製需求 → AutoML Text 和 Video 已停用，改 <strong>Gemini 調校</strong></li>

<li>以上都不行 → <strong>自訂訓練</strong>（第 16 篇）</li>
</ol>



<p class="wp-block-paragraph">Vision 文件自己也說：掃描文件要 OCR 加表單欄位擷取，去用 <strong>Document AI</strong>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">6. 應用平台：程式跑在哪</h2>



<p class="wp-block-paragraph">筆記最後一塊「Cloud Functions、App Engine」，現況：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>服務</th><th>現在</th><th>ML 裡的角色</th></tr></thead><tbody><tr><td><strong>Cloud Functions</strong></td><td>改叫 <strong>Cloud Run functions</strong>（<a href="https://docs.cloud.google.com/run/docs/functions/comparison">對照</a>：原 2nd gen 直接部署成 Cloud Run 服務；1st gen 還在）</td><td><strong>事件觸發</strong>：Cloud Storage 有新檔 → 啟動訓練管線（第 19 篇）；輕量前處理</td></tr><tr><td><strong>App Engine</strong></td><td>還在，但<a href="https://docs.cloud.google.com/appengine/docs/an-overview-of-app-engine">官方</a>寫「新使用者建議改用 Cloud Run」</td><td>舊的 Web／API 前端</td></tr><tr><td><strong>Cloud Run</strong></td><td>現在的主力無伺服器平台</td><td><a href="https://dongdonggcp.com/2026/10/25/model-deployment-online-vs-batch-prediction-traffic-split/">第 17 篇</a>：自己包容器服務模型，或 Agent Platform 端點以外的選擇</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Cloud Run functions 的規格：HTTP 觸發最長 60 分鐘、16 GiB 記憶體 4 vCPU、一個執行個體可以同時接 1,000 個請求，映像只能放 Artifact Registry（Container Registry 已淘汰）。站上有<a href="https://dongdonggcp.com/2025/07/20/cloud-run-functions-tutorials/">Cloud Run Functions 簡介</a>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">在 GCP 上怎麼做</h2>



<h3 class="wp-block-heading">飲料店的完整資料架構（2026 年 10 月）</h3>


<ol class="wp-block-list">
<li><strong>交易進來</strong>：POS → <strong>Pub/Sub</strong>。不用轉換的直接開 <strong>BigQuery 訂閱</strong>進 <code>transactions</code> 表；要算「最近 5 分鐘消費」這種開窗特徵的走 <strong>Dataflow</strong> 串流，直接寫 <strong>Bigtable</strong></li>

<li><strong>照片進來</strong>：App 上傳到 <strong>Cloud Storage</strong>（Standard），訓練完 90 天沒碰自動轉 Coldline（開 Autoclass）</li>

<li><strong>算特徵</strong>：每天凌晨 <strong>BigQuery SQL</strong> 算 90 天來店次數等慢特徵，寫 <code>member_features</code> 表；舊的 Spark 程式搬到 <strong>Managed Service for Apache Spark</strong>，用 <strong>Managed Service for Apache Airflow</strong> 排 DAG</li>

<li><strong>登記特徵</strong>：<code>member_features</code> 登記成 <strong>Feature group</strong>，開特徵監控抓漂移（第 20 篇）</li>

<li><strong>訓練</strong>：從 BigQuery 取特徵（第 15、16 篇），模型檔放 Cloud Storage，登錄 Model Registry（第 22 篇）</li>

<li><strong>上線</strong>：<strong>Feature view</strong> 每小時同步到 <strong>Bigtable online serving</strong>，端點（第 17 篇）50 毫秒內查到特徵；推薦結果快取到 <strong>Memorystore</strong></li>

<li><strong>現成的先用</strong>：發票用 <strong>Document AI</strong>、評論用 <strong>Natural Language API</strong>，不自己訓練</li>

<li><strong>觸發</strong>：Cloud Storage 新資料到 → <strong>Cloud Run functions</strong> → 啟動 Pipelines（第 19 篇）</li>
</ol>



<h3 class="wp-block-heading">改名對照</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>舊名稱（筆記、舊題庫）</th><th>現在</th></tr></thead><tbody><tr><td>Vertex AI Feature Store（Legacy：featurestore、entity type）</td><td><strong>Feature Store on Gemini Enterprise Agent Platform（V2）</strong>；Legacy 2026 年 2 月淘汰、2027 年 2 月停用</td></tr><tr><td>Optimized online serving</td><td>2027 年 2 月停用，改 <strong>Bigtable online serving</strong>；嵌入改 <strong>Vector Search</strong></td></tr><tr><td>Dataproc</td><td><strong>Managed Service for Apache Spark</strong>（叢集版與 Serverless 版）</td></tr><tr><td>Cloud Composer</td><td><strong>Managed Service for Apache Airflow</strong></td></tr><tr><td>Cloud Functions</td><td><strong>Cloud Run functions</strong></td></tr><tr><td>Dataprep</td><td>主控台叫 <strong>Alteryx Designer Cloud</strong>（第三方）；Google 主推 <strong>BigQuery 資料準備</strong></td></tr><tr><td>Recommendations AI、Vertex AI Search for Commerce</td><td><strong>AI Commerce Search</strong>（Recommendations 從 Agent Search 提供）</td></tr><tr><td>Cloud Natural Language API、Cloud Vision API</td><td>名稱沒變；文件歸在 Agent Platform 的「預訓練 API」底下</td></tr><tr><td>Container Registry</td><td><strong>Artifact Registry</strong></td></tr><tr><td>Memorystore for Redis</td><td>還在；新增 <strong>Memorystore for Valkey</strong></td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">考試會怎麼考</h2>



<p class="wp-block-paragraph">Google Cloud <strong>Professional Machine Learning Engineer（PMLE，專業機器學習工程師）</strong> 證照，2026 年 6 月 1 日起的<a href="https://services.google.com/fh/files/misc/professional_machine_learning_engineer_exam_guide_english_new.pdf">官方考試指南</a>裡，這篇對應到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考試區塊</th><th>跟這篇有關的項目</th></tr></thead><tbody><tr><td>第 1 區：低程式碼 AI 方案（約 13%）</td><td>1.2 用<strong>產業專用 API</strong>（Document AI、Vision、Translate）建方案</td></tr><tr><td>第 2 區：跨團隊協作管理資料與模型（約 16%）</td><td>2.1 <strong>依規模與複雜度選前處理工具</strong>（BigQuery SQL、Dataflow、Spark、記憶體內 Python）；在 <strong>Feature Store</strong> 建立與整合特徵</td></tr><tr><td>第 3 區：把原型放大成 ML 模型（約 21%）</td><td>3.2 訓練資料放 <strong>Cloud Storage 和 BigQuery</strong>；從各種來源把結構化與非結構化資料餵進訓練管線</td></tr><tr><td>第 4 區：服務與擴展模型（約 20%）</td><td>4.2 用 <strong>Feature Store 管理與服務特徵</strong></td></tr><tr><td>第 5 區：自動化與協調 ML 管線（約 18%）</td><td>5.1 用 Pipelines、<strong>Managed Service for Apache Airflow</strong>、Ray 協調</td></tr></tbody></table></figure>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-05-exam-keywords.png" alt="PMLE 考試關鍵字：線上預測低延遲查特徵想到 Bigtable 或 Feature Store 線上服務、分析訓練 SQL 想到 BigQuery、影像模型檔想到 Cloud Storage、次毫秒快取想到 Memorystore、串流 Pub/Sub Beam 想到 Dataflow、已有 Spark 程式想到 Managed Service for Apache Spark、訓練與服務偏差想到 Feature Store、OCR 翻譯情感想到預訓練 API、表單發票想到 Document AI" class="wp-image-12887" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-05-exam-keywords.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-05-exam-keywords-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-05-exam-keywords-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml23-05-exam-keywords-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目出現的關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「線上預測」「低延遲查特徵」「毫秒」「row key」「高吞吐」</td><td><strong>Bigtable</strong>（或 Feature Store 的 Bigtable online serving）</td></tr><tr><td>「分析」「SQL」「資料倉儲」「掃全表」「訓練表格資料」</td><td><strong>BigQuery</strong></td></tr><tr><td>「影像」「影片」「模型檔」「非結構化」「TFRecords」</td><td><strong>Cloud Storage</strong></td></tr><tr><td>「很少存取」「保留一年」「最便宜」</td><td>Cloud Storage <strong>Coldline／Archive</strong>，注意最短天數與取回費</td></tr><tr><td>「次毫秒」「快取」「記憶體」「Redis」</td><td><strong>Memorystore</strong></td></tr><tr><td>「訓練和線上特徵不一致」「特徵重用」「集中管理特徵」</td><td><strong>Feature Store</strong></td></tr><tr><td>「嵌入」「向量相似搜尋」</td><td><strong>Vector Search</strong>（Feature Store 的 Optimized serving 停用）</td></tr><tr><td>「串流」「即時」「Pub/Sub」「Apache Beam」「批次串流同一套」</td><td><strong>Dataflow</strong></td></tr><tr><td>「Pub/Sub 直接進 BigQuery 不用轉換」</td><td><strong>BigQuery 訂閱</strong></td></tr><tr><td>「Spark」「Hadoop」「Hive」「搬遷既有程式」</td><td><strong>Managed Service for Apache Spark</strong>（Dataproc）</td></tr><tr><td>「資料小」「探索」「筆記本」</td><td><strong>記憶體內 Python</strong>（pandas）</td></tr><tr><td>「不寫程式的 ETL」「拖拉點選」</td><td><strong>Data Fusion</strong></td></tr><tr><td>「排程」「DAG」「跨服務的工作流」</td><td><strong>Managed Service for Apache Airflow</strong></td></tr><tr><td>「OCR」「翻譯」「情感分析」「語音轉文字」「不想訓練模型」</td><td><strong>預訓練 API</strong></td></tr><tr><td>「表單」「發票」「擷取欄位」</td><td><strong>Document AI</strong></td></tr><tr><td>「商品推薦」「電商搜尋」</td><td><strong>AI Commerce Search</strong>（Recommendations AI）</td></tr><tr><td>「新檔案到就觸發」「事件驅動」</td><td><strong>Cloud Run functions</strong></td></tr></tbody></table></figure>



<h3 class="wp-block-heading">六個常見陷阱</h3>


<ol class="wp-block-list">
<li><strong>線上預測去查 BigQuery</strong>：以秒計的延遲，端點會逾時。線上查特徵用 Bigtable、Memorystore，或 Feature Store 的線上服務</li>

<li><strong>把照片存進 BigQuery</strong>：非結構化檔案放 Cloud Storage，BigQuery 存路徑就好</li>

<li><strong>選 Feature Store（Legacy）的做法</strong>：entity type、featurestore 那套 2027 年 2 月停用，現在是 BigQuery 當離線倉庫的 V2</li>

<li><strong>串流也選 Spark</strong>：Spark 能做串流，但 Google Cloud 的標準答案是 Dataflow（Beam）；Spark 選在「已有 Spark 程式」</li>

<li><strong>自己訓練 OCR</strong>：Vision API 或 Document AI 一行呼叫，考試看到「最少工程量」就選 API</li>

<li><strong>Archive 當一般儲存</strong>：最短 365 天，提早刪也照收，加取回費</li>
</ol>



<h3 class="wp-block-heading">練習情境（自己出的練習，不是真實考題）</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">飲料店 App 的推薦模型部署成線上端點，每次要讀該會員的 8 個特徵，要求 50 毫秒內回應。特徵每天在 BigQuery 用 SQL 算好。該怎麼把特徵端給端點？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「50 毫秒」「線上」→ 不能直接查 BigQuery</li>

<li>「特徵已經在 BigQuery」→ <strong>Feature Store V2</strong>：BigQuery 表登記成 feature group，feature view 同步到 <strong>Bigtable online serving</strong></li>

<li>訓練時從同一張 BigQuery 表拿，沒有訓練與服務偏差</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">每天 300 萬筆交易從 POS 進 Pub/Sub，要算每位會員「最近 5 分鐘消費金額」當即時特徵，也要把原始交易存進 BigQuery 給分析用。工程量最小的做法？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「原始交易存 BigQuery、不用轉換」→ <strong>BigQuery 訂閱</strong>，不用寫程式</li>

<li>「最近 5 分鐘」是開窗彙總 → <strong>Dataflow</strong> 串流，算完寫 <strong>Bigtable</strong> 給線上用</li>

<li>不選 Spark：沒有既有 Spark 程式，Beam 一套程式批次串流都能用</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">供應商每月寄 2,000 張 PDF 發票，要自動抓出品項、金額、日期填進系統。團隊沒有 ML 工程師。該用什麼？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「發票」「抓欄位」「沒有 ML 工程師」→ <strong>Document AI</strong>（發票是常見的預訓練解析器類型，或用 Form Parser）</li>

<li>不選 Vision API：它只給文字和座標，欄位要自己拼</li>

<li>不自己訓練：1.2 的重點就是先用產業 API</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">機器學習的訓練資料該放 BigQuery 還是 Cloud Storage？</h3>



<p class="wp-block-paragraph">表格資料放 BigQuery，用 SQL 做特徵、直接 BigQuery ML 訓練，或讓自訂訓練讀 BigQuery。影像、音訊、影片、模型檔、TFRecords 這些檔案放 Cloud Storage，BigQuery 只存路徑。考試指南 3.2 兩個都列，分界就是「表格」和「檔案」。</p>



<h3 class="wp-block-heading">Bigtable 和 BigQuery 差在哪？</h3>



<p class="wp-block-paragraph">BigQuery 是分析用的資料倉儲：用 SQL 掃全表，查 TB 級幾秒，但查一筆也以秒計。Bigtable 是 NoSQL 寬表：靠 row key 查，毫秒級、高吞吐、能到 PB，但不能做掃全表的分析。線上預測查特徵用 Bigtable，算特徵和訓練用 BigQuery。</p>



<h3 class="wp-block-heading">Feature Store 是什麼？為什麼需要？</h3>



<p class="wp-block-paragraph">集中管理特徵的服務，讓訓練和線上預測拿到同一份特徵，避免訓練與服務偏差，也讓不同模型重用特徵。現在的 V2 版以 BigQuery 的表當離線倉庫，不用另外複製；把表登記成 feature group 和 feature，用 feature view 排程同步到 online store 的 Bigtable online serving 給端點查。</p>



<h3 class="wp-block-heading">Vertex AI Feature Store（Legacy）還能用嗎？</h3>



<p class="wp-block-paragraph">2026 年 2 月 17 日淘汰，2027 年 2 月 17 日停用，官方要求搬到 Feature Store V2。同一天淘汰的還有 V2 的 Optimized online serving，改用 Bigtable online serving；要存和查嵌入向量改用 Vector Search。舊題庫寫的 featurestore、entity type 是 Legacy 的概念。</p>



<h3 class="wp-block-heading">Dataflow 和 Dataproc 怎麼選？</h3>



<p class="wp-block-paragraph">Dataflow 是代管的 Apache Beam，批次和串流同一套程式，自動擴縮，預設恰好一次處理，看到「串流」「即時」「Pub/Sub」就選它。Dataproc 現在叫 Managed Service for Apache Spark，是代管的 Spark／Hadoop，選在「已經有 Spark 程式要搬上雲」「要用 MLlib、Hive」；不想管叢集用 Serverless 版。資料已經在 BigQuery、SQL 做得到，就用 BigQuery SQL 最省事。</p>



<h3 class="wp-block-heading">資料前處理什麼時候用 Python 就好？</h3>



<p class="wp-block-paragraph">資料幾 GB 以內、能整個塞進記憶體、在探索階段，pandas 在筆記本裡最快。資料大到記憶體放不下，表格資料改 BigQuery SQL，要自訂邏輯或串流改 Dataflow，有 Spark 程式改 Managed Service for Apache Spark。考試指南 2.1 說的就是依規模和複雜度選。</p>



<h3 class="wp-block-heading">Cloud Storage 的儲存類別怎麼選？</h3>



<p class="wp-block-paragraph">看多久拿一次：常讀的用 Standard（無最短天數、無取回費）；一個月一次 Nearline（最短 30 天）；一季一次 Coldline（90 天）；一年一次 Archive（365 天）。冷的類別月費低但有取回費和最短天數，提早刪也照最短天數收費。AI／ML 訓練要極高吞吐有單一區域的 Rapid 類別。不確定就開 Autoclass 自動換。</p>



<h3 class="wp-block-heading">什麼時候該用預訓練 API 而不是自己訓練？</h3>



<p class="wp-block-paragraph">任務是通用的就用 API：OCR 和物件辨識用 Vision、情感和實體用 Natural Language、語音用 Speech-to-Text、翻譯用 Cloud Translation、表單發票用 Document AI、電商推薦和搜尋用 AI Commerce Search。類別要客製但影像為主用 AutoML 影像；文字和影片的客製改 Gemini 調校（AutoML Text、Video 已停用）；都不行才自訂訓練。</p>



<h3 class="wp-block-heading">Dataprep 現在還在嗎？</h3>



<p class="wp-block-paragraph">Google 的 Dataprep 產品頁已導向 BigQuery，主控台裡以第三方的 Alteryx Designer Cloud 名稱出現。Google 主推的替代是 BigQuery 內建的資料準備功能：用 Gemini 看資料樣本給清理和轉換建議，由 Dataform 排程。舊題庫看到 Dataprep 要知道它不是 Google 自家服務。</p>



<h3 class="wp-block-heading">Cloud Functions 改名了嗎？</h3>



<p class="wp-block-paragraph">改叫 Cloud Run functions：原本的 2nd gen 直接以 Cloud Run 服務部署，HTTP 觸發最長 60 分鐘、16 GiB 記憶體、一個執行個體可同時接 1,000 個請求；1st gen 還在。機器學習裡最常用在事件觸發：Cloud Storage 有新資料就啟動訓練管線。App Engine 還在，但官方建議新使用者改用 Cloud Run。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>三種動作三類服務</strong>：分析與訓練（<strong>BigQuery</strong>，秒級、掃全表）、線上查詢（<strong>Bigtable</strong> 毫秒、<strong>Memorystore</strong> 次毫秒）、放檔案（<strong>Cloud Storage</strong>，類別依多久拿一次選）</li>

<li><strong>延遲預算</strong>：100 ms − 網路 20 − 推論 30 = 剩 50 ms 查特徵，BigQuery 以秒計所以不行；答案是「預算內、放得下、最便宜」</li>

<li><strong>Feature Store V2</strong>：BigQuery 當離線倉庫、feature view 同步到 <strong>Bigtable online serving</strong>；Legacy 與 Optimized serving 2027 年 2 月停用，嵌入改 Vector Search</li>

<li><strong>前處理依規模與複雜度</strong>：Python（小）→ BigQuery SQL（表格）→ Dataflow（串流、自訂、Beam）→ Managed Service for Apache Spark（既有 Spark）；Pub/Sub 不轉換直接 BigQuery 訂閱</li>

<li><strong>現成的先用</strong>：Vision、Natural Language、Speech-to-Text、Translation、Document AI、AI Commerce Search；客製才 AutoML 影像、Gemini 調校、自訂訓練</li>

<li><strong>改名</strong>：Dataproc → Managed Service for Apache Spark、Composer → Managed Service for Apache Airflow、Cloud Functions → Cloud Run functions、Recommendations AI → AI Commerce Search</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/20/types-of-machine-learning-supervised-unsupervised-reinforcement/">機器學習有哪幾種？監督式、非監督式、強化學習一次看懂</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/10/20/classification-vs-regression-mae-rmse/">分類和迴歸差在哪？一個例子搞懂，附 MAE、RMSE 計算</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">特徵、標籤、超參數是什麼？機器學習 5 個必懂名詞</a></li>

<li>第 4 篇：<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">訓練集、驗證集、測試集怎麼切？時間序列為什麼不能亂切</a></li>

<li>第 5 篇：<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">混淆矩陣是什麼？用快篩搞懂準確率、精確率、召回率、F1</a></li>

<li>第 6 篇：<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">ROC 曲線和 AUC 怎麼看？門檻怎麼調、AUC-PR 差在哪</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">過度擬合是什麼？正則化、Dropout、提前停止 3 招解決</a></li>

<li>第 8 篇：<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">資料洩漏是什麼？模型考試作弊的 3 種常見情況</a></li>

<li>第 9 篇：<a href="https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/">類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</a></li>

<li>第 10 篇：<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">資料前處理怎麼做？標準化、遺失值、高基數類別</a></li>

<li>第 11 篇：<a href="https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/">特徵工程是什麼？特徵交叉、詞嵌入、資料增強一次看懂</a></li>

<li>第 12 篇：<a href="https://dongdonggcp.com/2026/10/25/machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls/">機器學習的資料隱私怎麼保護？DLP、聯邦學習、VPC Service Controls</a></li>

<li>第 13 篇：<a href="https://dongdonggcp.com/2026/10/25/tfrecords-tf-data-prefetch-input-pipeline/">訓練資料讀太慢？TFRecords、tf.data 與 prefetch 加速</a></li>

<li>第 14 篇：<a href="https://dongdonggcp.com/2026/10/25/vertex-ai-automl-bigquery-ml-custom-training-how-to-choose/">Vertex AI AutoML、BigQuery ML、自訂訓練怎麼選？</a></li>

<li>第 15 篇：<a href="https://dongdonggcp.com/2026/10/25/bigquery-ml-tutorial-train-model-with-sql/">BigQuery ML 入門：只會 SQL 也能訓練模型</a></li>

<li>第 16 篇：<a href="https://dongdonggcp.com/2026/10/25/vertex-ai-custom-training-containers-distributed-gpu-tpu/">Vertex AI 自訂訓練：容器、分散式訓練、GPU 與 TPU</a></li>

<li>第 17 篇：<a href="https://dongdonggcp.com/2026/10/25/model-deployment-online-vs-batch-prediction-traffic-split/">模型部署怎麼選？線上預測 vs 批次預測、流量分割</a></li>

<li>第 18 篇：<a href="https://dongdonggcp.com/2026/10/25/what-is-mlops-vertex-ai-pipelines-kubeflow-tfx/">MLOps 是什麼？Vertex AI Pipelines、Kubeflow、TFX 介紹</a></li>

<li>第 19 篇：<a href="https://dongdonggcp.com/2026/10/25/ml-ci-cd-continuous-training-auto-retrain/">機器學習的 CI/CD：程式改了、資料來了，模型自動重訓</a></li>

<li>第 20 篇：<a href="https://dongdonggcp.com/2026/10/25/model-monitoring-drift-training-serving-skew/">模型上線後會變笨？Drift 與 Training-Serving Skew 監控</a></li>

<li>第 21 篇：<a href="https://dongdonggcp.com/2026/10/25/explainable-ai-shapley-integrated-gradients-xrai/">可解釋 AI 是什麼？Shapley、Integrated Gradients、XRAI</a></li>

<li>上一篇：第 22 篇：<a href="https://dongdonggcp.com/2026/10/25/vertex-ai-experiments-ml-metadata-tensorboard-experiment-tracking/">實驗怎麼追蹤？Vertex AI Experiments、Metadata、TensorBoard</a></li>

<li>下一篇：第 24 篇：<a href="https://dongdonggcp.com/2026/10/25/gcp-professional-machine-learning-engineer-certification-guide/">GCP ML 證照怎麼考？PMLE 考試範圍、準備地圖與 23 篇重點整理</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/07/04/is-bigquery-a-database-what-is-the-usage/">BigQuery 是資料庫嗎？跟資料庫差在哪</a></li>

<li><a href="https://dongdonggcp.com/2026/03/27/bigquery-billing-guide/">BigQuery 計費方式完整指南</a></li>

<li><a href="https://dongdonggcp.com/2025/02/12/how-to-upload-data-to-bigquery/">把資料上傳到 BigQuery 的各種方法</a></li>

<li><a href="https://dongdonggcp.com/2025/04/23/whai-is-dataproc-architecture-and-usage-introduction/">Dataproc 是什麼？四大優勢與使用方法</a></li>

<li><a href="https://dongdonggcp.com/2025/08/06/cloud-pub-sub-tutorial-better-than-rabbitmq-mqtt/">Cloud Pub/Sub 教學</a></li>

<li><a href="https://dongdonggcp.com/2025/07/20/cloud-run-functions-tutorials/">Cloud Run Functions 簡介與基本操作</a></li>

<li><a href="https://dongdonggcp.com/2026/05/19/gcp-bill-explosion-prevention-guide/">GCP 帳單爆炸防護指南</a></li>

<li><a href="https://dongdonggcp.com/2025/04/27/gcp-learning-roadmap/">GCP 學習路徑 Roadmap</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">資料放對地方、算對地方，模型才跑得快又不燒錢。如果你想有系統地從雲端基礎一路學到在 GCP 上動手做機器學習，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "機器學習的訓練資料該放 BigQuery 還是 Cloud Storage？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "表格資料放 BigQuery，用 SQL 做特徵、直接 BigQuery ML 訓練，或讓自訂訓練讀 BigQuery。影像、音訊、影片、模型檔、TFRecords 這些檔案放 Cloud Storage，BigQuery 只存路徑。考試指南 3.2 兩個都列，分界就是「表格」和「檔案」。"
      }
    },
    {
      "@type": "Question",
      "name": "Bigtable 和 BigQuery 差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "BigQuery 是分析用的資料倉儲：用 SQL 掃全表，查 TB 級幾秒，但查一筆也以秒計。Bigtable 是 NoSQL 寬表：靠 row key 查，毫秒級、高吞吐、能到 PB，但不能做掃全表的分析。線上預測查特徵用 Bigtable，算特徵和訓練用 BigQuery。"
      }
    },
    {
      "@type": "Question",
      "name": "Feature Store 是什麼？為什麼需要？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "集中管理特徵的服務，讓訓練和線上預測拿到同一份特徵，避免訓練與服務偏差，也讓不同模型重用特徵。現在的 V2 版以 BigQuery 的表當離線倉庫，不用另外複製；把表登記成 feature group 和 feature，用 feature view 排程同步到 online store 的 Bigtable online serving 給端點查。"
      }
    },
    {
      "@type": "Question",
      "name": "Vertex AI Feature Store（Legacy）還能用嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "2026 年 2 月 17 日淘汰，2027 年 2 月 17 日停用，官方要求搬到 Feature Store V2。同一天淘汰的還有 V2 的 Optimized online serving，改用 Bigtable online serving；要存和查嵌入向量改用 Vector Search。舊題庫寫的 featurestore、entity type 是 Legacy 的概念。"
      }
    },
    {
      "@type": "Question",
      "name": "Dataflow 和 Dataproc 怎麼選？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Dataflow 是代管的 Apache Beam，批次和串流同一套程式，自動擴縮，預設恰好一次處理，看到「串流」「即時」「Pub/Sub」就選它。Dataproc 現在叫 Managed Service for Apache Spark，是代管的 Spark／Hadoop，選在「已經有 Spark 程式要搬上雲」「要用 MLlib、Hive」；不想管叢集用 Serverless 版。資料已經在 BigQuery、SQL 做得到，就用 BigQuery SQL 最省事。"
      }
    },
    {
      "@type": "Question",
      "name": "資料前處理什麼時候用 Python 就好？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "資料幾 GB 以內、能整個塞進記憶體、在探索階段，pandas 在筆記本裡最快。資料大到記憶體放不下，表格資料改 BigQuery SQL，要自訂邏輯或串流改 Dataflow，有 Spark 程式改 Managed Service for Apache Spark。考試指南 2.1 說的就是依規模和複雜度選。"
      }
    },
    {
      "@type": "Question",
      "name": "Cloud Storage 的儲存類別怎麼選？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "看多久拿一次：常讀的用 Standard（無最短天數、無取回費）；一個月一次 Nearline（最短 30 天）；一季一次 Coldline（90 天）；一年一次 Archive（365 天）。冷的類別月費低但有取回費和最短天數，提早刪也照最短天數收費。AI／ML 訓練要極高吞吐有單一區域的 Rapid 類別。不確定就開 Autoclass 自動換。"
      }
    },
    {
      "@type": "Question",
      "name": "什麼時候該用預訓練 API 而不是自己訓練？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "任務是通用的就用 API：OCR 和物件辨識用 Vision、情感和實體用 Natural Language、語音用 Speech-to-Text、翻譯用 Cloud Translation、表單發票用 Document AI、電商推薦和搜尋用 AI Commerce Search。類別要客製但影像為主用 AutoML 影像；文字和影片的客製改 Gemini 調校（AutoML Text、Video 已停用）；都不行才自訂訓練。"
      }
    },
    {
      "@type": "Question",
      "name": "Dataprep 現在還在嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Google 的 Dataprep 產品頁已導向 BigQuery，主控台裡以第三方的 Alteryx Designer Cloud 名稱出現。Google 主推的替代是 BigQuery 內建的資料準備功能：用 Gemini 看資料樣本給清理和轉換建議，由 Dataform 排程。舊題庫看到 Dataprep 要知道它不是 Google 自家服務。"
      }
    },
    {
      "@type": "Question",
      "name": "Cloud Functions 改名了嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "改叫 Cloud Run functions：原本的 2nd gen 直接以 Cloud Run 服務部署，HTTP 觸發最長 60 分鐘、16 GiB 記憶體、一個執行個體可同時接 1,000 個請求；1st gen 還在。機器學習裡最常用在事件觸發：Cloud Storage 有新資料就啟動訓練管線。App Engine 還在，但官方建議新使用者改用 Cloud Run。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/10/25/gcp-data-services-for-ml-bigquery-cloud-storage-feature-store-bigtable/">ML 用哪個資料服務？BigQuery、Cloud Storage、Feature Store、Bigtable 怎麼選</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/10/25/gcp-data-services-for-ml-bigquery-cloud-storage-feature-store-bigtable/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>可解釋 AI 是什麼？Shapley、Integrated Gradients、XRAI</title>
		<link>https://dongdonggcp.com/2026/10/25/explainable-ai-shapley-integrated-gradients-xrai/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=explainable-ai-shapley-integrated-gradients-xrai</link>
					<comments>https://dongdonggcp.com/2026/10/25/explainable-ai-shapley-integrated-gradients-xrai/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 25 Oct 2026 05:45:00 +0000</pubDate>
				<category><![CDATA[AI 和機器學習]]></category>
		<category><![CDATA[證照考試]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[BigQuery]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[PMLE]]></category>
		<category><![CDATA[Vertex AI]]></category>
		<category><![CDATA[機器學習]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=12876</guid>

					<description><![CDATA[<p>可解釋 AI 是什麼？用分獎金算一次 Shapley 值，看三種特徵歸因方法各適合哪種模型；Vertex Explainable AI 2027 年停用後改用 SHAP、LIME 與 BigQuery ML，附 PMLE 考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/10/25/explainable-ai-shapley-integrated-gradients-xrai/">可解釋 AI 是什麼？Shapley、Integrated Gradients、XRAI</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>可解釋 AI 是算出每個特徵對預測貢獻多少：樹模型用 Sampled Shapley，神經網路用 Integrated Gradients。</strong></p>



<p class="wp-block-paragraph">模型說 M002 會流失、說這張封膜有問題，<strong>為什麼？</strong> 老闆問、客戶問、法規問，你答不出來，模型就只是一個黑盒子。可解釋 AI 就是打開黑盒子的工具：它不改模型，而是算出「這次預測，每個特徵各出了多少力」。</p>



<p class="wp-block-paragraph">這篇有一個重要的現況：Google 的 <strong>Vertex Explainable AI 已在 2026 年 3 月 16 日淘汰</strong>，2027 年 3 月 16 日停用。概念和方法沒變（考試還是考），但工具要換成 SHAP、LIME 這類開源套件，或 BigQuery ML 內建的解釋函數。文末會整理。</p>



<p class="wp-block-paragraph">一樣用有 2,000 間分店、50 萬名會員的連鎖飲料店當例子（教學假設）：流失模型（表格）和封膜檢查模型（影像）。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-01-shapley.png" alt="可解釋 AI 是什麼：Shapley 值的概念是把每個特徵當成合作的玩家，依它在各種組合裡的平均貢獻分配功勞；兩位員工單獨做 10 和 20、合作做 40，Shapley 值是 15 和 25；線性模型的歸因等於權重乘標準化後的特徵值" class="wp-image-12872" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-01-shapley.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-01-shapley-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-01-shapley-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-01-shapley-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>法規和信任</strong>：金融、醫療、保險的模型，被拒絕的人有權知道原因。BigQuery 的<a href="https://docs.cloud.google.com/bigquery/docs/xai-overview">可解釋 AI 文件</a>說，特徵歸因可以用來「確認模型行為符合預期、找出偏見、改進模型和訓練資料」</li>

<li><strong>除錯</strong>：<a href="https://docs.cloud.google.com/vertex-ai/docs/explainable-ai/overview">Vertex Explainable AI 總覽</a>說，特徵歸因能抓到「標準評估方法通常會漏掉的資料問題」。第 8 篇的資料洩漏，常常是看到某個特徵貢獻大到不合理才發現的</li>

<li><strong>監控要用</strong>：第 20 篇的特徵歸因漂移、偏見監控，底層就是這篇的方法</li>

<li><strong>證照必考</strong>：PMLE 考試指南 6.1「Agent Platform 上的模型可解釋性」；3.1「依可解釋性需求選建模技術」；6.1「監控偏見」。筆記裡的採樣 Shapley、整合梯度、XRAI 三個名詞全在這篇</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">先搞懂：可解釋 AI 是什麼</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>可解釋 AI</strong>（Explainable AI，XAI）：讓人看懂模型<strong>為什麼</strong>做出某個預測的方法。最主要的做法是<strong>特徵歸因</strong>（feature attribution）：算出每個特徵對這次預測的貢獻值，有正有負，加起來等於預測值和基準值的差。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">一碗牛肉麵好吃，到底是湯、麵、肉、還是辣油的功勞？特徵歸因就是「給每樣材料打分數」：湯 +4、肉 +3、麵 +1、辣油 −1，加起來是這碗麵比「平均水準」好吃多少。</p>



<h3 class="wp-block-heading">兩種解釋：局部和全域</h3>



<p class="wp-block-paragraph">BigQuery 的文件分得很清楚：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th><strong>局部解釋</strong>（local）</th><th><strong>全域解釋</strong>（global）</th></tr></thead><tbody><tr><td>白話</td><td><strong>這一筆</strong>預測，每個特徵貢獻多少</td><td>模型<strong>整體</strong>最看重哪些特徵</td></tr><tr><td>怎麼算</td><td>對單一樣本算歸因</td><td>把全部樣本的歸因<strong>彙總</strong>（取絕對值平均）</td></tr><tr><td>飲料店</td><td>M002 為什麼被判會流失</td><td>流失模型整體最看「距上次消費天數」</td></tr><tr><td>BigQuery ML</td><td><code>ML.EXPLAIN_PREDICT</code></td><td><code>ML.GLOBAL_EXPLAIN</code>、<code>ML.FEATURE_IMPORTANCE</code></td></tr></tbody></table></figure>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">模型越強越像黑盒子：線性迴歸（第 2 篇）的權重一看就懂，但 XGBoost 幾百棵樹、神經網路幾百萬個參數，沒人看得懂。2017 年前後，SHAP、Integrated Gradients 這些方法陸續出來，Google 把它們整合進 Vertex AI 叫 Vertex Explainable AI。現在 Google 把它淘汰，建議回頭用開源的 SHAP 和 LIME，BigQuery ML 則把解釋功能內建在 SQL 函數裡。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">考試 3.1 有一條「依可解釋性需求選建模技術」：題目說「法規要求能解釋每筆決定」，答案可能是選線性模型、樹模型這種<strong>本身就可解釋</strong>的，或是用特徵歸因。分不清就選錯。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">1. Shapley 值：公平分功勞的數學</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>Shapley 值</strong>（Shapley value）：把每個特徵當成一個「玩家」，算它在<strong>所有可能的合作組合</strong>裡平均貢獻多少，當作它的功勞。<a href="https://docs.cloud.google.com/vertex-ai/docs/explainable-ai/overview">Vertex Explainable AI 文件</a>說，三種特徵歸因方法<strong>都是以 Shapley 值為基礎</strong>，它來自合作賽局理論（cooperative game theory），專門處理「一群人一起做出一個結果，功勞怎麼分」。</p>



<h3 class="wp-block-heading">算一次給你看：兩個員工分獎金</h3>



<p class="wp-block-paragraph">飲料店兩位員工 A、B，單獨做一天業績 A 是 10 杯、B 是 20 杯，<strong>一起做</strong>是 40 杯（有合作效應）。獎金怎麼分才公平？</p>



<p class="wp-block-paragraph">Shapley 的算法：考慮<strong>每種加入順序</strong>，看每個人「加入時多帶來多少」：</p>



<pre class="wp-block-code"><code>順序 1：A 先來，B 後來
  A 加入：0 → 10，帶來 10
  B 加入：10 → 40，帶來 30

順序 2：B 先來，A 後來
  B 加入：0 → 20，帶來 20
  A 加入：20 → 40，帶來 20

A 的 Shapley 值 = (10 + 20) ÷ 2 = 15
B 的 Shapley 值 = (30 + 20) ÷ 2 = 25
15 + 25 = 40 ✓（功勞加起來等於總業績）</code></pre>



<p class="wp-block-paragraph"><strong>數字怎麼看</strong>：</p>


<ul class="wp-block-list">
<li>A 單獨只做 10，但分到 15，因為他跟 B 合作時貢獻更大。這就是 Shapley 值的優點：<strong>考慮了交互作用</strong>（第 11 篇的特徵交叉）</li>

<li>功勞<strong>一定加總等於結果</strong>，這是它被選為特徵歸因標準的原因</li>
</ul>



<p class="wp-block-paragraph">套到模型：每個「玩家」是一個特徵，「業績」是預測值減掉基準值。</p>



<h3 class="wp-block-heading">線性模型的 Shapley 值：直接算</h3>



<p class="wp-block-paragraph">BigQuery 的文件給了一個簡單的公式：線性和邏輯迴歸的 Shapley 值＝<strong>模型權重 × 標準化後的特徵值</strong>（權重是用標準化特徵訓練出來的）。</p>



<p class="wp-block-paragraph">流失模型（邏輯迴歸，第 15 篇）的權重和會員 M002 的標準化特徵值（教學假設）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>特徵</th><th>權重</th><th>M002 標準化後的值</th><th>歸因＝權重 × 值</th></tr></thead><tbody><tr><td>距上次消費天數</td><td>+0.8</td><td>+2.0（比平均久很多）</td><td><strong>+1.6</strong></td></tr><tr><td>90 天來店次數</td><td>−0.6</td><td>−1.5（比平均少很多）</td><td><strong>+0.9</strong></td></tr><tr><td>平均客單價</td><td>−0.2</td><td>+0.5（略高）</td><td><strong>−0.1</strong></td></tr><tr><td><strong>合計</strong></td><td></td><td></td><td><strong>+2.4</strong></td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>標準化</strong>是第 10 篇講的：減平均、除以標準差，0 代表「平均的會員」。</p>



<p class="wp-block-paragraph"><strong>怎麼讀</strong>：</p>


<ul class="wp-block-list">
<li>基準是「平均的會員」，M002 比平均多了 +2.4 的流失分數（這是進 sigmoid 之前的分數，第 2 篇）</li>

<li><strong>+1.6 來自「太久沒來」</strong>，+0.9 來自「來得少」，客單價高一點點反而讓她稍微不像會流失（−0.1）</li>

<li>正負號是方向，絕對值是力道。給客服看就是：「M002 已經 75 天沒來，是主因」</li>
</ul>



<h3 class="wp-block-heading">特徵多了怎麼辦：Sampled Shapley</h3>



<p class="wp-block-paragraph">兩個玩家只有 2 種順序，10 個特徵有 10! ＝ 3,628,800 種順序，20 個特徵算不完。<strong>Sampled Shapley</strong>（採樣 Shapley）：<strong>隨機抽一些順序</strong>來算，用平均值估計真正的 Shapley 值。</p>



<p class="wp-block-paragraph">官方設定裡的 <strong>path count</strong>（路徑數）就是「抽幾條順序」，範圍 1 到 50：越多<strong>近似誤差越小</strong>，但越慢越貴。</p>



<p class="wp-block-paragraph"><strong>適合誰</strong>：官方說 Sampled Shapley 適合<strong>不可微分的模型</strong>，例如<strong>樹的集成</strong>（XGBoost、隨機森林）和 AutoML 表格模型（它是樹和神經網路的混合集成）。<strong>不可微分</strong>白話是「輸出對輸入沒有平滑的斜率」，樹模型是一堆 if-else，就是這種。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">2. Integrated Gradients：沿著一條路累積斜率</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>Integrated Gradients</strong>（整合梯度，IG）：從一個<strong>基準輸入</strong>（例如全黑的圖、或全是中位數的表格）慢慢變成<strong>實際輸入</strong>，沿路每一步算「預測對每個特徵的斜率」（梯度），把斜率累積起來，就是每個特徵的貢獻。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">把一張照片的亮度從全黑慢慢調到正常，看模型的「貓」分數在哪些像素變亮時跳最多，那些像素就是模型認貓的依據。官方文件的說法：想像一個滑桿，把所有像素往黑色縮放。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">官方描述的步驟：</p>


<ol class="wp-block-list">
<li>在縮放參數的不同區間算梯度，區間大小用<strong>高斯求積法</strong>（一種數值積分技巧）決定</li>

<li>用加權平均近似積分</li>

<li>平均梯度<strong>逐元素乘上原始輸入</strong></li>
</ol>



<p class="wp-block-paragraph"><strong>梯度</strong>是第 3 篇講過的「該往哪調、調多少」，神經網路訓練本來就在算它，所以 IG 對神經網路特別自然。</p>



<h3 class="wp-block-heading">適合誰</h3>



<p class="wp-block-paragraph"><strong>可微分的模型</strong>：神經網路（TensorFlow、PyTorch）。表格和影像都能用。設定裡有 <strong>step count</strong>（步數），越多越準越慢，跟 Sampled Shapley 的路徑數是同樣的取捨。</p>



<h3 class="wp-block-heading">基準值很重要</h3>



<p class="wp-block-paragraph">兩種方法都要一個<strong>基準</strong>（baseline）：「沒有資訊」的輸入長什麼樣。官方說沒指定就用<strong>全零</strong>（影像是全黑）。但表格資料的全零常常不合理（客單價 0 元？），官方建議選有意義的基準，例如文件裡的腳踏車例子用「騎乘時間的中位數」。基準選錯，歸因的數字會跟著歪。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">3. XRAI：影像看區域，不看像素</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>XRAI</strong>：IG 算出來的是<strong>每個像素</strong>的貢獻，很碎、人看不懂。XRAI 把影像先切成一塊一塊的<strong>區域</strong>，把區域內像素的貢獻加總，排出「哪幾塊最重要」。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">IG 像拿著放大鏡看每一顆沙子，XRAI 像退後一步看「這片沙灘的哪一區」。</p>



<h3 class="wp-block-heading">官方的三步</h3>


<ol class="wp-block-list">
<li><strong>像素級歸因</strong>：用 IG，而且用<strong>黑色和白色兩種基準</strong>各算一次</li>

<li><strong>過度分割</strong>：用 Felzenszwalb 的圖論方法把影像切成很多小區塊（跟歸因無關，獨立做）</li>

<li><strong>選區域</strong>：把每個區塊裡的像素歸因加總算密度，排序，從最正的排到最不正的</li>
</ol>



<p class="wp-block-paragraph">輸出是一張疊在原圖上的熱圖，標出模型「看哪裡」。封膜檢查模型判「有問題」，XRAI 會標出封膜邊緣那一圈。如果它標的是杯子上的 logo，就知道模型學歪了（第 8 篇的洩漏：也許有問題的那批照片都是某家分店拍的）。</p>



<h3 class="wp-block-heading">適合誰</h3>



<p class="wp-block-paragraph"><strong>影像</strong>，而且官方說特別適合<strong>自然影像</strong>（照片）。表格資料不適用。</p>



<h3 class="wp-block-heading">三種方法一張表</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th><strong>Sampled Shapley</strong></th><th><strong>Integrated Gradients</strong></th><th><strong>XRAI</strong></th></tr></thead><tbody><tr><td>原理</td><td>抽樣估計 Shapley 值</td><td>從基準到輸入累積梯度</td><td>IG＋區域分割</td></tr><tr><td>適合的模型</td><td><strong>不可微分</strong>：樹集成、AutoML 表格</td><td><strong>可微分</strong>：神經網路</td><td>神經網路的<strong>影像</strong>模型</td></tr><tr><td>資料</td><td>表格</td><td>表格、影像</td><td>影像（自然照片）</td></tr><tr><td>輸出</td><td>每個特徵一個分數</td><td>每個特徵或像素一個分數</td><td>每個<strong>區域</strong>的重要性熱圖</td></tr><tr><td>旋鈕</td><td>path count（1～50）</td><td>step count</td><td>同 IG</td></tr><tr><td>飲料店</td><td>流失模型（XGBoost）</td><td>推薦模型（PyTorch 神經網路）</td><td>封膜檢查（影像）</td></tr></tbody></table></figure>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-02-three-methods.png" alt="三種特徵歸因方法比較：Sampled Shapley 抽樣估計 Shapley 值適合樹集成和 AutoML 表格這類不可微分模型；Integrated Gradients 從基準到輸入累積梯度適合神經網路的表格和影像；XRAI 在 IG 之上做區域分割只適合影像，輸出哪一區最重要的熱圖" class="wp-image-12873" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-02-three-methods.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-02-three-methods-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-02-three-methods-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-02-three-methods-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">4. 範例式解釋：找最像的訓練樣本</h2>



<p class="wp-block-paragraph">Vertex Explainable AI 還有第二類：<strong>範例式解釋</strong>（example-based explanations）。做法是用<strong>最近鄰搜尋</strong>，從訓練集找出跟這筆輸入<strong>最像的幾個樣本</strong>。邏輯是「相似的輸入應該有相似的預測」。</p>



<p class="wp-block-paragraph">官方列的四個用途：</p>


<ul class="wp-block-list">
<li><strong>改進資料或模型</strong>：鳥被判成飛機，找出最像的訓練樣本，發現全是飛機的黑色剪影 → 要多加鳥的剪影；如果最像的都是鳥卻還判錯 → 模型太簡單，要加層</li>

<li><strong>解讀新類型的資料</strong>：訓練時只有鳥和飛機，上線遇到無人機，看它最像哪些已標記的樣本</li>

<li><strong>找異常值</strong>：跟所有訓練資料都不像的，就是離群值。神經網路對錯誤常常很有信心，這招能抓出來</li>

<li><strong>主動學習</strong>：最像的樣本一半是感冒一半是流感，代表這筆很難判，值得送給醫生標記</li>
</ul>



<p class="wp-block-paragraph">限制：只支援<strong>能輸出嵌入</strong>（embedding，第 11 篇）的 TensorFlow 模型，樹模型、PyTorch、XGBoost 不支援。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">5. 淘汰之後怎麼辦：SHAP、LIME、BigQuery ML</h2>



<h3 class="wp-block-heading">Vertex Explainable AI 的時程</h3>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/vertex-ai/docs/deprecations">官方淘汰清單</a>：2026 年 3 月 16 日起不再加新功能，<strong>2027 年 3 月 16 日</strong>完全停用、API 不再提供。替代方案官方點名：<strong>SHAP</strong> 和 <strong>LIME</strong>。</p>



<h3 class="wp-block-heading">SHAP</h3>



<p class="wp-block-paragraph"><a href="https://shap.readthedocs.io/">SHAP</a>（SHapley Additive exPlanations）：開源 Python 套件，Shapley 值的工業級實作。對樹模型有 <strong>Tree SHAP</strong>（算<strong>精確</strong>的 Shapley 值，不用抽樣），對任何模型有 Kernel SHAP（抽樣近似），對神經網路也有對應的版本。第 20 篇 Model Monitoring v2 的特徵歸因用的就是 SHAP 值。</p>



<h3 class="wp-block-heading">LIME</h3>



<p class="wp-block-paragraph"><a href="https://github.com/marcotcr/lime">LIME</a>（Local Interpretable Model-agnostic Explanations）：開源套件，<strong>不管模型是什麼</strong>（model-agnostic），只要它能吐出機率就能解釋。做法是在這筆資料附近製造很多擾動過的樣本，用一個簡單的線性模型去「局部模仿」黑盒子，線性模型的權重就是解釋。支援文字、表格、影像。官方範例：把「Host」和「NNTP」兩個字拿掉，分類器判「無神論」的機率從 0.58 降到 0.31。</p>



<h3 class="wp-block-heading">BigQuery ML：解釋內建在 SQL 裡</h3>



<p class="wp-block-paragraph">BigQuery ML 的解釋功能<strong>不受淘汰影響</strong>，<a href="https://docs.cloud.google.com/bigquery/docs/xai-overview">文件</a>列的方法：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>模型</th><th>方法</th><th>局部</th><th>全域</th></tr></thead><tbody><tr><td>線性／邏輯迴歸</td><td>Shapley 值（權重 × 標準化值）；另有標準誤和 p 值做顯著性檢定</td><td><code>ML.EXPLAIN_PREDICT</code></td><td><code>ML.GLOBAL_EXPLAIN</code>、<code>ML.ADVANCED_WEIGHTS</code></td></tr><tr><td>提升樹、隨機森林</td><td><strong>Tree SHAP</strong>（精確）；或近似特徵貢獻（更快）；Gini 重要性（訓練時每個特徵多有用）</td><td><code>ML.EXPLAIN_PREDICT</code></td><td><code>ML.GLOBAL_EXPLAIN</code>、<code>ML.FEATURE_IMPORTANCE</code></td></tr><tr><td>時間序列 ARIMA_PLUS</td><td>拆解趨勢、季節、假日</td><td><code>ML.EXPLAIN_FORECAST</code></td><td></td></tr></tbody></table></figure>



<p class="wp-block-paragraph">第 15 篇示範過 <code>ML.EXPLAIN_PREDICT</code> 的 <code>top_k_features</code>，訓練時開 <code>enable_global_explain = TRUE</code> 才能用 <code>ML.GLOBAL_EXPLAIN</code>。</p>



<h3 class="wp-block-heading">本身就可解釋的模型</h3>



<p class="wp-block-paragraph">考試 3.1「依可解釋性需求選建模技術」的另一個答案：<strong>直接選看得懂的模型</strong>。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><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>樹集成（XGBoost）</td><td>要靠 SHAP</td><td>準</td></tr><tr><td>神經網路</td><td>要靠 IG、SHAP</td><td>最準、最黑</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">法規嚴、解釋比準確度重要 → 前兩種；要準又要解釋 → 後兩種加特徵歸因。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-03-local-global-alternatives.png" alt="局部解釋看這一筆預測每個特徵貢獻多少、全域解釋看模型整體最看重哪些特徵；Vertex Explainable AI 2027 年 3 月停用，替代方案是 SHAP 的 Tree SHAP 和 Kernel SHAP、LIME 的局部線性模仿、BigQuery ML 內建的 ML.EXPLAIN_PREDICT 和 ML.GLOBAL_EXPLAIN" class="wp-image-12874" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-03-local-global-alternatives.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-03-local-global-alternatives-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-03-local-global-alternatives-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-03-local-global-alternatives-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">在 GCP 上怎麼做</h2>



<h3 class="wp-block-heading">現在（2026 年 10 月）的建議路線</h3>


<ol class="wp-block-list">
<li><strong>表格模型在 BigQuery ML</strong>：訓練時 <code>enable_global_explain = TRUE</code>，用 <code>ML.EXPLAIN_PREDICT</code> 看單筆、<code>ML.GLOBAL_EXPLAIN</code> 看整體，最省事</li>

<li><strong>自訂訓練的模型</strong>：在訓練或推論程式裡裝 <code>shap</code>（樹模型用 TreeExplainer，神經網路用 DeepExplainer 或 GradientExplainer），把歸因跟預測一起存到 BigQuery，方便第 20 篇的監控和第 22 篇的追蹤</li>

<li><strong>影像模型</strong>：SHAP 有影像的解釋器，或用開源的 XRAI 實作（Google 的 saliency 套件），輸出熱圖</li>

<li><strong>還在用 Vertex Explainable AI 的</strong>：2027 年 3 月前遷移。Model Registry 裡模型的 explanation 設定（方法、path count、基準）要改成在程式裡做</li>

<li><strong>Model Monitoring v2</strong> 的特徵歸因目標用 SHAP，第 20 篇講過</li>
</ol>



<h3 class="wp-block-heading">基準值怎麼選</h3>


<ul class="wp-block-list">
<li>表格：用訓練資料的<strong>中位數或平均</strong>當基準，代表「一個典型的會員」</li>

<li>影像：黑圖是預設，XRAI 黑白各算一次</li>

<li>基準不同，歸因的絕對值會不同，<strong>比較歸因時要用同一個基準</strong></li>
</ul>



<h3 class="wp-block-heading">改名對照</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>舊名稱（筆記、舊題庫）</th><th>現在</th></tr></thead><tbody><tr><td>Vertex Explainable AI（採樣 Shapley、整合梯度、XRAI）</td><td><strong>2026 年 3 月淘汰、2027 年 3 月停用</strong>；方法概念不變，工具改 SHAP、LIME</td></tr><tr><td>AI Explanations（AI Platform 時代）</td><td>更早的名字，已隨 AI Platform 關閉</td></tr><tr><td>BQML.EXPLAIN_PREDICT（筆記寫法）</td><td><code>ML.EXPLAIN_PREDICT</code>，不受淘汰影響</td></tr><tr><td>Vertex AI Model Monitoring 的特徵歸因</td><td>Model Monitoring v2，用 SHAP 值</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">考試會怎麼考</h2>



<p class="wp-block-paragraph">Google Cloud <strong>Professional Machine Learning Engineer（PMLE，專業機器學習工程師）</strong> 證照，2026 年 6 月 1 日起的<a href="https://services.google.com/fh/files/misc/professional_machine_learning_engineer_exam_guide_english_new.pdf">官方考試指南</a>裡，這篇的內容對應到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考試區塊</th><th>跟這篇有關的項目</th></tr></thead><tbody><tr><td>第 3 區：把原型放大成 ML 模型（約 21%）</td><td>3.1 <strong>依可解釋性需求選建模技術</strong></td></tr><tr><td>第 6 區：監控 AI 方案（約 13%）</td><td>6.1 符合負責任 AI 實務（<strong>監控偏見</strong>）；<strong>Agent Platform 上的模型可解釋性</strong>（例如 Agent Platform Inference）</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">考試指南寫的還是「Agent Platform 上的模型可解釋性」，淘汰公告是 2026 年 3 月、指南是 6 月，題目可能還會出現舊功能的名字。方法名稱（Sampled Shapley、Integrated Gradients、XRAI）和適用情境是重點，不會變。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-04-exam-keywords.png" alt="PMLE 考試關鍵字：表格樹模型 AutoML 表格想到 Sampled Shapley、神經網路可微分想到 Integrated Gradients、影像哪一區重要想到 XRAI、每一筆預測的原因想到局部解釋 ML.EXPLAIN_PREDICT、整體最看重哪些特徵想到全域解釋、法規要求能解釋想到可解釋模型或特徵歸因、找最像的訓練樣本想到範例式解釋" class="wp-image-12875" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-04-exam-keywords.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-04-exam-keywords-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-04-exam-keywords-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml21-04-exam-keywords-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目出現的關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「表格」「XGBoost」「樹集成」「AutoML 表格」「不可微分」</td><td><strong>Sampled Shapley</strong></td></tr><tr><td>「神經網路」「可微分」「TensorFlow 模型的特徵歸因」</td><td><strong>Integrated Gradients</strong></td></tr><tr><td>「影像」「哪個區域」「熱圖」「自然照片」</td><td><strong>XRAI</strong></td></tr><tr><td>「每一筆預測為什麼」「客戶問原因」</td><td><strong>局部解釋</strong>，<code>ML.EXPLAIN_PREDICT</code></td></tr><tr><td>「模型整體最看重什麼」「哪些特徵可以拿掉」</td><td><strong>全域解釋</strong>，<code>ML.GLOBAL_EXPLAIN</code>、<code>ML.FEATURE_IMPORTANCE</code></td></tr><tr><td>「法規要求能解釋」「解釋比準確重要」</td><td>選<strong>可解釋模型</strong>（線性、單棵樹），或加特徵歸因</td></tr><tr><td>「歸因太慢」「近似誤差」</td><td>調 <strong>path count／step count</strong>（少＝快、多＝準）</td></tr><tr><td>「歸因數字怪怪的」「全零不合理」</td><td><strong>基準值</strong>選錯，改用中位數</td></tr><tr><td>「找出最像的訓練樣本」「異常值」「哪些該人工標記」</td><td><strong>範例式解釋</strong>（最近鄰）</td></tr><tr><td>「某個特徵貢獻大到不合理」</td><td>可能是<strong>資料洩漏</strong>（第 8 篇）</td></tr><tr><td>「敏感特徵（性別、年齡）貢獻很大」</td><td><strong>偏見</strong>，6.1</td></tr><tr><td>「Vertex Explainable AI 要停用了」</td><td><strong>SHAP、LIME</strong>，BigQuery ML 內建函數</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">六個常見陷阱</h3>


<ol class="wp-block-list">
<li><strong>樹模型選 Integrated Gradients</strong>：IG 要可微分，樹模型用 Sampled Shapley（或 Tree SHAP）</li>

<li><strong>表格資料選 XRAI</strong>：XRAI 只給影像</li>

<li><strong>用全零當表格的基準</strong>：客單價 0 元不是「典型會員」，歸因會歪</li>

<li><strong>把歸因當因果</strong>：歸因是「模型怎麼想」，不是「世界怎麼運作」。模型看重「城市」可能是訓練資料的偏見</li>

<li><strong>以為解釋功能都沒了</strong>：淘汰的是 Vertex Explainable AI 這個服務，方法還在，SHAP 和 BigQuery ML 都能做</li>

<li><strong>path count 設 50 跑正式推論</strong>：每筆預測都要抽 50 條路徑，延遲和費用暴增，線上用小一點、離線分析再開大</li>
</ol>



<h3 class="wp-block-heading">練習情境（自己出的練習，不是真實考題）</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">飲料店的流失模型是 XGBoost，客服部門要求每一筆「會流失」的判斷都要附三個主要原因。應該怎麼做？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「XGBoost」「每一筆」→ <strong>局部解釋</strong>，樹模型用 <strong>Sampled Shapley</strong>（或 SHAP 的 Tree SHAP）</li>

<li>在 BigQuery ML 的話，<code>ML.EXPLAIN_PREDICT</code> 加 <code>top_k_features = 3</code></li>

<li>自訂訓練的話，推論程式裡用 <code>shap.TreeExplainer</code>，把前三名存進結果表</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">封膜檢查模型（神經網路）把一批正常的杯子判成有問題。工程師想知道模型到底在看照片的哪裡。應該用什麼？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「影像」「看哪裡」→ <strong>XRAI</strong>（區域熱圖）；如果要到像素級細節用 Integrated Gradients</li>

<li>熱圖標在 logo 而不是封膜 → 訓練資料有洩漏，回頭查（第 8 篇）</li>

<li>也可以用<strong>範例式解釋</strong>找出最像的訓練照片，看是不是某家分店的拍法特殊</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">保險公司要用機器學習審核理賠，法規要求每個拒絕都能用人看得懂的規則解釋，而且模型要能被稽核。該怎麼選模型？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「人看得懂的規則」「稽核」→ 3.1 的<strong>可解釋性需求</strong>，優先選<strong>本身可解釋的模型</strong>：邏輯迴歸（權重直接讀）或單棵決策樹（規則一路看）</li>

<li>準確度不夠才升級到樹集成＋SHAP，但要能證明歸因方法</li>

<li>敏感特徵（年齡、性別）的歸因要監控（6.1 偏見）</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">可解釋 AI 是什麼？</h3>



<p class="wp-block-paragraph">讓人看懂模型為什麼做出某個預測的方法，主要做法是特徵歸因：算出每個特徵對這次預測的貢獻值，有正有負，加起來等於預測值和基準值的差。分局部解釋（這一筆每個特徵貢獻多少）和全域解釋（模型整體最看重什麼）。用途是確認模型行為合理、找偏見、除錯、改進資料，也是法規要求的解釋依據。</p>



<h3 class="wp-block-heading">Shapley 值是什麼？</h3>



<p class="wp-block-paragraph">來自合作賽局理論的分功勞方法：把每個特徵當玩家，算它在所有加入順序裡平均帶來多少增量，當作它的貢獻。好處是考慮交互作用，而且所有特徵的貢獻加總一定等於結果。兩位員工單獨做 10 和 20 杯、合作做 40 杯，Shapley 值是 15 和 25。線性模型的 Shapley 值等於權重乘標準化後的特徵值。</p>



<h3 class="wp-block-heading">Sampled Shapley、Integrated Gradients、XRAI 怎麼選？</h3>



<p class="wp-block-paragraph">Sampled Shapley 抽樣估計 Shapley 值，適合不可微分的模型：樹集成（XGBoost、隨機森林）、AutoML 表格。Integrated Gradients 從基準到輸入累積梯度，適合可微分的神經網路，表格和影像都能用。XRAI 在 IG 之上做區域分割，只適合影像，輸出哪一區最重要的熱圖。三種都以 Shapley 值為基礎。</p>



<h3 class="wp-block-heading">基準值（baseline）是什麼？為什麼重要？</h3>



<p class="wp-block-paragraph">「沒有資訊」的輸入長什麼樣，歸因算的是「從基準變成實際輸入，每個特徵帶來多少變化」。預設是全零（影像是全黑），但表格資料全零常不合理（客單價 0 元），官方建議選有意義的基準，例如中位數。基準不同歸因的絕對值不同，比較時要用同一個基準。</p>



<h3 class="wp-block-heading">什麼是範例式解釋？</h3>



<p class="wp-block-paragraph">用最近鄰搜尋從訓練集找出跟這筆輸入最像的幾個樣本，邏輯是相似輸入應有相似預測。用途：找出模型判錯的原因（最像的樣本都是另一類代表資料不夠）、解讀訓練時沒見過的新類型資料、找異常值、挑出值得人工標記的困難樣本。只支援能輸出嵌入的 TensorFlow 模型。</p>



<h3 class="wp-block-heading">Vertex Explainable AI 淘汰了，還能怎麼做解釋？</h3>



<p class="wp-block-paragraph">Vertex Explainable AI 2026 年 3 月 16 日淘汰、2027 年 3 月 16 日停用。官方建議改用開源的 SHAP（樹模型有精確的 Tree SHAP，任何模型有 Kernel SHAP）和 LIME（不管模型是什麼，在資料附近用線性模型局部模仿）。BigQuery ML 的 ML.EXPLAIN_PREDICT、ML.GLOBAL_EXPLAIN、ML.FEATURE_IMPORTANCE 不受影響。Model Monitoring v2 的特徵歸因也是用 SHAP。</p>



<h3 class="wp-block-heading">BigQuery ML 怎麼做解釋？</h3>



<p class="wp-block-paragraph">線性和邏輯迴歸用 Shapley 值（權重乘標準化值），另有標準誤和 p 值；提升樹和隨機森林用 Tree SHAP（精確）或近似特徵貢獻（更快），還有 Gini 重要性；ARIMA_PLUS 用 ML.EXPLAIN_FORECAST 拆趨勢季節假日。局部用 ML.EXPLAIN_PREDICT，全域用 ML.GLOBAL_EXPLAIN（訓練時要開 enable_global_explain）和 ML.FEATURE_IMPORTANCE。</p>



<h3 class="wp-block-heading">法規要求模型能解釋，該怎麼選模型？</h3>



<p class="wp-block-paragraph">考試指南 3.1 的「依可解釋性需求選建模技術」。解釋比準確度重要時，直接選本身可解釋的模型：邏輯迴歸的權重直接讀，單棵決策樹的規則一路看。要準又要解釋，用樹集成或神經網路加特徵歸因（SHAP、IG），但要能說明方法。敏感特徵的歸因要監控有沒有偏見。</p>



<h3 class="wp-block-heading">特徵歸因可以當成因果關係嗎？</h3>



<p class="wp-block-paragraph">不行。歸因說的是「模型怎麼想」，不是「世界怎麼運作」。模型看重「城市」可能只是訓練資料裡某個城市的流失率剛好高。歸因大到不合理反而是警訊：可能是資料洩漏（答案混進特徵），或模型學到了偏見。</p>



<h3 class="wp-block-heading">path count 和 step count 要設多少？</h3>



<p class="wp-block-paragraph">Sampled Shapley 的 path count 是抽幾條順序，1 到 50；Integrated Gradients 的 step count 是沿路算幾步。越多近似誤差越小但越慢越貴。線上推論每筆都要算，設小一點顧延遲；離線分析或除錯再開大。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>可解釋 AI</strong>＝<strong>特徵歸因</strong>：每個特徵對這次預測的貢獻，加總等於預測值減基準值；<strong>局部</strong>（這一筆）vs <strong>全域</strong>（整體）</li>

<li><strong>Shapley 值</strong>：合作賽局分功勞，考慮所有加入順序的平均增量，考慮交互作用、加總等於結果；線性模型＝權重 × 標準化值</li>

<li><strong>三種方法</strong>：<strong>Sampled Shapley</strong>（不可微分：樹集成、AutoML 表格）、<strong>Integrated Gradients</strong>（可微分：神經網路，表格與影像）、<strong>XRAI</strong>（影像區域熱圖）；旋鈕 path count／step count；<strong>基準值</strong>要選有意義的</li>

<li><strong>範例式解釋</strong>：最近鄰找最像的訓練樣本，除錯、新資料、異常值、主動學習；只支援 TensorFlow 嵌入</li>

<li><strong>Vertex Explainable AI 2027 年 3 月停用</strong>：改用 <strong>SHAP</strong>（Tree SHAP）、<strong>LIME</strong>；BigQuery ML 的 <code>ML.EXPLAIN_PREDICT</code>、<code>ML.GLOBAL_EXPLAIN</code> 不受影響</li>

<li><strong>選模型</strong>：法規要解釋 → 線性、單棵樹；要準 → 集成或神經網路＋歸因。歸因不是因果</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/20/types-of-machine-learning-supervised-unsupervised-reinforcement/">機器學習有哪幾種？監督式、非監督式、強化學習一次看懂</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/10/20/classification-vs-regression-mae-rmse/">分類和迴歸差在哪？一個例子搞懂，附 MAE、RMSE 計算</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">特徵、標籤、超參數是什麼？機器學習 5 個必懂名詞</a></li>

<li>第 4 篇：<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">訓練集、驗證集、測試集怎麼切？時間序列為什麼不能亂切</a></li>

<li>第 5 篇：<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">混淆矩陣是什麼？用快篩搞懂準確率、精確率、召回率、F1</a></li>

<li>第 6 篇：<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">ROC 曲線和 AUC 怎麼看？門檻怎麼調、AUC-PR 差在哪</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">過度擬合是什麼？正則化、Dropout、提前停止 3 招解決</a></li>

<li>第 8 篇：<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">資料洩漏是什麼？模型考試作弊的 3 種常見情況</a></li>

<li>第 9 篇：<a href="https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/">類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</a></li>

<li>第 10 篇：<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">資料前處理怎麼做？標準化、遺失值、高基數類別</a></li>

<li>第 11 篇：<a href="https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/">特徵工程是什麼？特徵交叉、詞嵌入、資料增強一次看懂</a></li>

<li>第 12 篇：<a href="https://dongdonggcp.com/2026/10/25/machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls/">機器學習的資料隱私怎麼保護？DLP、聯邦學習、VPC Service Controls</a></li>

<li>第 13 篇：<a href="https://dongdonggcp.com/2026/10/25/tfrecords-tf-data-prefetch-input-pipeline/">訓練資料讀太慢？TFRecords、tf.data 與 prefetch 加速</a></li>

<li>第 14 篇：<a href="https://dongdonggcp.com/2026/10/25/vertex-ai-automl-bigquery-ml-custom-training-how-to-choose/">Vertex AI AutoML、BigQuery ML、自訂訓練怎麼選？</a></li>

<li>第 15 篇：<a href="https://dongdonggcp.com/2026/10/25/bigquery-ml-tutorial-train-model-with-sql/">BigQuery ML 入門：只會 SQL 也能訓練模型</a></li>

<li>第 16 篇：<a href="https://dongdonggcp.com/2026/10/25/vertex-ai-custom-training-containers-distributed-gpu-tpu/">Vertex AI 自訂訓練：容器、分散式訓練、GPU 與 TPU</a></li>

<li>第 17 篇：<a href="https://dongdonggcp.com/2026/10/25/model-deployment-online-vs-batch-prediction-traffic-split/">模型部署怎麼選？線上預測 vs 批次預測、流量分割</a></li>

<li>第 18 篇：<a href="https://dongdonggcp.com/2026/10/25/what-is-mlops-vertex-ai-pipelines-kubeflow-tfx/">MLOps 是什麼？Vertex AI Pipelines、Kubeflow、TFX 介紹</a></li>

<li>第 19 篇：<a href="https://dongdonggcp.com/2026/10/25/ml-ci-cd-continuous-training-auto-retrain/">機器學習的 CI/CD：程式改了、資料來了，模型自動重訓</a></li>

<li>上一篇：第 20 篇：<a href="https://dongdonggcp.com/2026/10/25/model-monitoring-drift-training-serving-skew/">模型上線後會變笨？Drift 與 Training-Serving Skew 監控</a></li>

<li>下一篇：第 22 篇：<a href="https://dongdonggcp.com/2026/10/25/vertex-ai-experiments-ml-metadata-tensorboard-experiment-tracking/">實驗怎麼追蹤？Vertex AI Experiments、Metadata、TensorBoard</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/07/04/is-bigquery-a-database-what-is-the-usage/">BigQuery 是資料庫嗎？跟資料庫差在哪</a></li>

<li><a href="https://dongdonggcp.com/2025/04/14/vertex-ai-functions-agent-builder-model-builder-model-garden-introduction/">Vertex AI 核心功能 Agent Builder、Model Builder 和 Model Garden 介紹</a></li>

<li><a href="https://dongdonggcp.com/2025/08/12/what-is-end-to-end-training-in-machine-learning/">End-to-end Training 是什麼</a></li>

<li><a href="https://dongdonggcp.com/2026/04/22/gcp-organization-policy-introduction/">GCP Organization Policy 完全攻略</a></li>

<li><a href="https://dongdonggcp.com/2025/08/04/cloud-architect-without-coding/">不會寫程式，可以轉職雲端架構師嗎？</a></li>

<li><a href="https://dongdonggcp.com/2025/04/27/gcp-learning-roadmap/">GCP 學習路徑 Roadmap</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">模型說得出「為什麼」，才能被信任、被稽核、被改好。如果你想有系統地從雲端基礎一路學到在 GCP 上動手做機器學習，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "可解釋 AI 是什麼？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "讓人看懂模型為什麼做出某個預測的方法，主要做法是特徵歸因：算出每個特徵對這次預測的貢獻值，有正有負，加起來等於預測值和基準值的差。分局部解釋（這一筆每個特徵貢獻多少）和全域解釋（模型整體最看重什麼）。用途是確認模型行為合理、找偏見、除錯、改進資料，也是法規要求的解釋依據。"
      }
    },
    {
      "@type": "Question",
      "name": "Shapley 值是什麼？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "來自合作賽局理論的分功勞方法：把每個特徵當玩家，算它在所有加入順序裡平均帶來多少增量，當作它的貢獻。好處是考慮交互作用，而且所有特徵的貢獻加總一定等於結果。兩位員工單獨做 10 和 20 杯、合作做 40 杯，Shapley 值是 15 和 25。線性模型的 Shapley 值等於權重乘標準化後的特徵值。"
      }
    },
    {
      "@type": "Question",
      "name": "Sampled Shapley、Integrated Gradients、XRAI 怎麼選？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Sampled Shapley 抽樣估計 Shapley 值，適合不可微分的模型：樹集成（XGBoost、隨機森林）、AutoML 表格。Integrated Gradients 從基準到輸入累積梯度，適合可微分的神經網路，表格和影像都能用。XRAI 在 IG 之上做區域分割，只適合影像，輸出哪一區最重要的熱圖。三種都以 Shapley 值為基礎。"
      }
    },
    {
      "@type": "Question",
      "name": "基準值（baseline）是什麼？為什麼重要？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "「沒有資訊」的輸入長什麼樣，歸因算的是「從基準變成實際輸入，每個特徵帶來多少變化」。預設是全零（影像是全黑），但表格資料全零常不合理（客單價 0 元），官方建議選有意義的基準，例如中位數。基準不同歸因的絕對值不同，比較時要用同一個基準。"
      }
    },
    {
      "@type": "Question",
      "name": "什麼是範例式解釋？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "用最近鄰搜尋從訓練集找出跟這筆輸入最像的幾個樣本，邏輯是相似輸入應有相似預測。用途：找出模型判錯的原因（最像的樣本都是另一類代表資料不夠）、解讀訓練時沒見過的新類型資料、找異常值、挑出值得人工標記的困難樣本。只支援能輸出嵌入的 TensorFlow 模型。"
      }
    },
    {
      "@type": "Question",
      "name": "Vertex Explainable AI 淘汰了，還能怎麼做解釋？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Vertex Explainable AI 2026 年 3 月 16 日淘汰、2027 年 3 月 16 日停用。官方建議改用開源的 SHAP（樹模型有精確的 Tree SHAP，任何模型有 Kernel SHAP）和 LIME（不管模型是什麼，在資料附近用線性模型局部模仿）。BigQuery ML 的 ML.EXPLAIN_PREDICT、ML.GLOBAL_EXPLAIN、ML.FEATURE_IMPORTANCE 不受影響。Model Monitoring v2 的特徵歸因也是用 SHAP。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 怎麼做解釋？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "線性和邏輯迴歸用 Shapley 值（權重乘標準化值），另有標準誤和 p 值；提升樹和隨機森林用 Tree SHAP（精確）或近似特徵貢獻（更快），還有 Gini 重要性；ARIMA_PLUS 用 ML.EXPLAIN_FORECAST 拆趨勢季節假日。局部用 ML.EXPLAIN_PREDICT，全域用 ML.GLOBAL_EXPLAIN（訓練時要開 enable_global_explain）和 ML.FEATURE_IMPORTANCE。"
      }
    },
    {
      "@type": "Question",
      "name": "法規要求模型能解釋，該怎麼選模型？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "考試指南 3.1 的「依可解釋性需求選建模技術」。解釋比準確度重要時，直接選本身可解釋的模型：邏輯迴歸的權重直接讀，單棵決策樹的規則一路看。要準又要解釋，用樹集成或神經網路加特徵歸因（SHAP、IG），但要能說明方法。敏感特徵的歸因要監控有沒有偏見。"
      }
    },
    {
      "@type": "Question",
      "name": "特徵歸因可以當成因果關係嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不行。歸因說的是「模型怎麼想」，不是「世界怎麼運作」。模型看重「城市」可能只是訓練資料裡某個城市的流失率剛好高。歸因大到不合理反而是警訊：可能是資料洩漏（答案混進特徵），或模型學到了偏見。"
      }
    },
    {
      "@type": "Question",
      "name": "path count 和 step count 要設多少？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Sampled Shapley 的 path count 是抽幾條順序，1 到 50；Integrated Gradients 的 step count 是沿路算幾步。越多近似誤差越小但越慢越貴。線上推論每筆都要算，設小一點顧延遲；離線分析或除錯再開大。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/10/25/explainable-ai-shapley-integrated-gradients-xrai/">可解釋 AI 是什麼？Shapley、Integrated Gradients、XRAI</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/10/25/explainable-ai-shapley-integrated-gradients-xrai/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>模型上線後會變笨？Drift 與 Training-Serving Skew 監控</title>
		<link>https://dongdonggcp.com/2026/10/25/model-monitoring-drift-training-serving-skew/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=model-monitoring-drift-training-serving-skew</link>
					<comments>https://dongdonggcp.com/2026/10/25/model-monitoring-drift-training-serving-skew/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 25 Oct 2026 05:44:30 +0000</pubDate>
				<category><![CDATA[AI 和機器學習]]></category>
		<category><![CDATA[證照考試]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[BigQuery]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[PMLE]]></category>
		<category><![CDATA[Vertex AI]]></category>
		<category><![CDATA[機器學習]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=12871</guid>

					<description><![CDATA[<p>模型上線後會變笨？用飲料店的流失模型分清偏差、資料漂移、概念漂移、特徵歸因漂移四種變法，Model Monitoring 怎麼量距離、L-infinity 算一次、門檻視窗取樣率怎麼設、警報怎麼接重訓，附 PMLE 考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/10/25/model-monitoring-drift-training-serving-skew/">模型上線後會變笨？Drift 與 Training-Serving Skew 監控</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>模型上線後會變笨，因為資料變了：跟訓練時不一樣叫偏差，隨時間變叫漂移，Model Monitoring 量距離超過門檻就警報。</strong></p>



<p class="wp-block-paragraph">前兩篇把模型做成管線、自動重訓、自動上線。但有一件事還沒處理：<strong>模型上線之後，怎麼知道它還準不準？</strong> 沒人盯，模型會在你不知道的情況下慢慢變笨，推薦越來越不準、流失名單越來越離譜，等到老闆問才發現。</p>



<p class="wp-block-paragraph">一樣用有 2,000 間分店、50 萬名會員的連鎖飲料店當例子（教學假設）：會員流失模型和推薦模型都上線了，這篇講怎麼監控它們。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-01-four-ways.png" alt="模型上線後會變笨的四種方式：訓練服務偏差是上線資料跟訓練資料不一樣、資料漂移是上線資料隨時間變、概念漂移是特徵和答案的關係變了、特徵歸因漂移是重要特徵的貢獻變了" class="wp-image-12867" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-01-four-ways.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-01-four-ways-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-01-four-ways-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-01-four-ways-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>Google 自己的例子</strong>：<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/model-monitoring/overview">Model Monitoring 總覽</a>說，預測客戶終身價值的模型，客戶習慣一變，當初用來訓練的特徵可能就不再適用。這種資料的偏移叫<strong>漂移</strong></li>

<li><strong>等級 0 的致命傷</strong>：第 18 篇講 MLOps 等級 0 時，官方列的問題之一就是「沒有主動監控模型效能」。模型壞了沒人知道，是最常見的事故</li>

<li><strong>監控是重訓的觸發器</strong>：第 19 篇的「效能下降就重訓」「漂移就重訓」，靠的就是這篇的警報</li>

<li><strong>證照必考</strong>：PMLE 考試指南第 6 區「監控 AI 方案」佔 <strong>13%</strong>，6.2 直接寫「設定和使用 Model Monitoring 建立正式模型的持續評估指標」「監控常見問題（<strong>訓練／服務偏差、資料漂移、概念漂移、特徵歸因漂移</strong>）」；6.1 的「監控偏見」也在這篇</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">先搞懂：模型變笨的四種方式</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph">模型是用<strong>過去的資料</strong>學出來的規則。世界一變，規則就不準。官方和考試指南把「變」分成四種：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>名稱</th><th>白話</th><th>什麼變了</th><th>飲料店</th></tr></thead><tbody><tr><td><strong>訓練／服務偏差</strong>（training-serving skew）</td><td><strong>上線時餵的資料，跟訓練時的不一樣</strong></td><td>訓練 vs 上線</td><td>訓練時客單價單位是「元」，上線 API 傳來的是「百元」</td></tr><tr><td><strong>資料漂移</strong>（data drift，也叫 feature drift）</td><td>上線後，<strong>輸入資料的分布隨時間變了</strong></td><td>上線初期 vs 現在</td><td>夏天來了，冰飲比例從 40% 變 80%</td></tr><tr><td><strong>概念漂移</strong>（concept drift）</td><td>輸入沒變，但<strong>輸入和答案的關係變了</strong></td><td>規則本身</td><td>疫情後，「兩週沒來」不再代表流失，因為大家都改外送</td></tr><tr><td><strong>特徵歸因漂移</strong>（feature attribution drift）</td><td><strong>哪些特徵重要</strong>變了</td><td>模型的依據</td><td>以前「距上次消費天數」最重要，現在變成「是否用外送」</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">另外還有<strong>預測漂移</strong>（prediction drift）：模型<strong>輸出</strong>的分布變了，例如判「會流失」的比例從 5% 跳到 30%。它是結果，前四種是原因。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">流感快篩試劑：</p>


<ul class="wp-block-list">
<li><strong>偏差</strong>：試劑是用成年人的樣本校正的，結果拿去給嬰兒用（訓練和上線的對象不同）</li>

<li><strong>資料漂移</strong>：今年流行的病毒株變了，試劑對新株不敏感（輸入資料變了）</li>

<li><strong>概念漂移</strong>：以前「發燒」幾乎等於流感，現在很多發燒是別的病（症狀和疾病的關係變了）</li>
</ul>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">Google 的<a href="https://developers.google.com/machine-learning/guides/rules-of-ml">機器學習規則</a>對訓練／服務偏差的定義：「訓練時的表現和服務時的表現之間的差異」，原因有兩種：</p>


<ol class="wp-block-list">
<li><strong>訓練和服務的管線處理資料的方式不一樣</strong></li>

<li><strong>訓練和服務之間，資料本身變了</strong></li>
</ol>



<p class="wp-block-paragraph">第 1 種是工程問題（第 10、15 篇講的前處理不一致），第 2 種就是漂移。Model Monitoring 主要抓第 2 種。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">考試 6.2 把這四個詞並列，題目會描述一個症狀問你「這是哪一種、該怎麼辦」。認得出來，才知道該修程式（偏差）、該重訓（漂移）、還是該重新定義問題（概念漂移）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">1. 偏差的第一種原因：訓練和上線的處理不一樣</h2>



<p class="wp-block-paragraph">這一種<strong>監控抓不到</strong>，因為資料看起來「正常」，只是單位、編碼、順序不一樣。要在設計時就防：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>做法</th><th>本系列哪一篇</th></tr></thead><tbody><tr><td>BigQuery ML 的 <strong>TRANSFORM 子句</strong>：訓練怎麼轉，預測自動一樣轉</td><td>第 15 篇</td></tr><tr><td>TFX 的 <strong>Transform</strong>（TFT）：前處理寫一次，訓練和服務共用</td><td>第 18 篇</td></tr><tr><td><strong>Feature Store</strong>：特徵算一次存起來，訓練和線上都從這裡拿</td><td><a href="https://dongdonggcp.com/2026/10/25/gcp-data-services-for-ml-bigquery-cloud-storage-feature-store-bigtable/">第 23 篇</a></td></tr><tr><td>機器學習規則第 29 條：<strong>把服務時用的特徵記下來</strong>，拿去訓練，就能比對一致性</td><td></td></tr><tr><td>機器學習規則第 32 條：<strong>訓練和服務的程式碼盡量共用</strong></td><td></td></tr></tbody></table></figure>



<p class="wp-block-paragraph">飲料店那個「元 vs 百元」的錯，上線第一天流失模型就會把所有人判成「會流失」，監控會看到<strong>預測漂移</strong>（判流失的比例暴增），但根本原因要回去查管線。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">2. Model Monitoring 怎麼量「變了多少」</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>Model Monitoring</strong>（Vertex AI Model Monitoring，現在叫 Model Monitoring on Gemini Enterprise Agent Platform）：Google 的服務，定期把<strong>上線時收到的請求</strong>拿來跟<strong>基準</strong>比，算一個「差多少」的分數，超過門檻就通知你。</p>



<h3 class="wp-block-heading">兩個版本</h3>



<p class="wp-block-paragraph">官方總覽說有兩個版本：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th><strong>v1</strong>（正式版，GA）</th><th><strong>v2</strong>（預覽）</th></tr></thead><tbody><tr><td>綁在哪</td><td>Agent Platform 的<strong>端點</strong>上</td><td><strong>模型版本</strong>上</td></tr><tr><td>監控什麼</td><td>線上推論的輸入特徵</td><td>線上、批次、甚至<strong>不在 Agent Platform 上的模型</strong></td></tr><tr><td>目標</td><td>偏差、漂移</td><td>輸入特徵漂移、<strong>輸出推論漂移</strong>、<strong>特徵歸因</strong></td></tr><tr><td>建議</td><td>需要正式支援、模型部署在端點</td><td>其他情況</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">v1 不用遷移，兩版可以並行。筆記裡的「Vertex AI Model Monitoring 監測 Prediction Drift／Feature Drift／Training-Serving Skew」對應的是 v1 的偏差與漂移，加上 v2 的輸出漂移。</p>



<h3 class="wp-block-heading">v1 的流程</h3>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/model-monitoring/using-model-monitoring">官方說明</a>：</p>


<ol class="wp-block-list">
<li>模型部署到端點、開啟監控後，<strong>每一筆推論請求記錄到 BigQuery</strong> 表</li>

<li>依<strong>取樣率</strong>抽一部分來分析（省錢）</li>

<li>每個<strong>監控視窗</strong>（預設 24 小時，最小 1 小時）算一次最近請求的特徵分布</li>

<li>跟<strong>基準分布</strong>比：<ul class="wp-block-list">
<li><strong>偏差偵測</strong>的基準＝<strong>訓練資料</strong>的分布（所以要提供訓練資料的 BigQuery 或 Cloud Storage 路徑）</li>

<li><strong>漂移偵測</strong>的基準＝<strong>過去在上線環境看到</strong>的分布（沒有訓練資料也能用）</li>
</ul>
</li>

<li>算<strong>距離分數</strong>：類別特徵用 <strong>L-infinity 距離</strong>，數值特徵用 <strong>Jensen-Shannon 散度</strong></li>

<li>分數超過<strong>警報門檻</strong>（預設每個特徵 <strong>0.3</strong>，可各自設）→ 寄 email、寫 Cloud Logging、送 Cloud Monitoring 的通知管道（PagerDuty、Slack、Pub/Sub）</li>

<li>Pub/Sub 接第 19 篇的 Cloud Run 函式 → 自動重訓</li>
</ol>



<p class="wp-block-paragraph">分布怎麼算：類別特徵數每個值的比例；數值特徵把範圍切成等寬區間、數每個區間的比例。基準在建監控工作時算一次，之後只有更新訓練資料才重算。自訂模型要給<strong>分析結構描述</strong>（schema），沒給的話監控會等<strong>前 1,000 筆請求</strong>自動解析。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-02-monitoring-flow.png" alt="Model Monitoring 的流程：推論請求記錄到 BigQuery，依取樣率抽樣，每個監控視窗算特徵分布，跟基準比，偏差的基準是訓練資料、漂移的基準是過去的上線資料，類別特徵算 L-infinity 距離、數值特徵算 Jensen-Shannon 散度，超過門檻就寄 email、寫 Cloud Logging、送 Pub/Sub 觸發重訓" class="wp-image-12868" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-02-monitoring-flow.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-02-monitoring-flow-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-02-monitoring-flow-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-02-monitoring-flow-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">支援哪些模型</h3>



<p class="wp-block-paragraph">v1 只支援<strong>表格</strong>模型：AutoML 表格，或匯入的自訂表格模型；同一端點上的模型都要是這兩種。影像、文字模型要用別的方法（例如自己記錄預測、定期人工抽查）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">3. 算一次給你看：L-infinity 距離</h2>



<p class="wp-block-paragraph"><strong>L-infinity 距離</strong>：兩個分布裡，<strong>每個類別的比例差，取最大的那個</strong>。白話：找出「差最多的那一格」。</p>



<p class="wp-block-paragraph">流失模型的特徵 <code>city</code>（城市），訓練資料的分布：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>城市</th><th>訓練資料</th><th>第 1 個月上線</th><th>差</th></tr></thead><tbody><tr><td>台北</td><td>50%</td><td>35%</td><td>0.15</td></tr><tr><td>台中</td><td>30%</td><td>30%</td><td>0.00</td></tr><tr><td>高雄</td><td>20%</td><td>35%</td><td>0.15</td></tr></tbody></table></figure>



<pre class="wp-block-code"><code>L-infinity = max(0.15, 0.00, 0.15) = 0.15
0.15 &lt; 門檻 0.3 → 不警報</code></pre>



<p class="wp-block-paragraph">第 6 個月（高雄大舉展店）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>城市</th><th>訓練資料</th><th>第 6 個月上線</th><th>差</th></tr></thead><tbody><tr><td>台北</td><td>50%</td><td>10%</td><td>0.40</td></tr><tr><td>台中</td><td>30%</td><td>30%</td><td>0.00</td></tr><tr><td>高雄</td><td>20%</td><td>60%</td><td>0.40</td></tr></tbody></table></figure>



<pre class="wp-block-code"><code>L-infinity = max(0.40, 0.00, 0.40) = 0.40
0.40 &gt; 門檻 0.3 → 警報：city 這個特徵有偏差</code></pre>



<p class="wp-block-paragraph"><strong>數值特徵</strong>（客單價、天數）用 <strong>Jensen-Shannon 散度</strong>，也是 0 到 1 的分數，概念一樣：兩個分布越不像分數越高，超過門檻就警報。算法用到對數，這裡不展開。</p>



<p class="wp-block-paragraph"><strong>數字怎麼看</strong>：</p>


<ul class="wp-block-list">
<li>門檻 <strong>0.3</strong> 是官方預設，不是真理。<strong>重要特徵設低</strong>（0.1 就警報），<strong>本來就會波動的特徵設高</strong></li>

<li>偏差警報不一定代表模型壞了：高雄會員變多，模型對高雄會員本來就會算，只是<strong>跟訓練時的母體不同</strong>，要看效能有沒有跟著掉</li>

<li><strong>多個特徵同時警報</strong>，通常是上游資料管線出問題（偏差的第 1 種原因），不是世界變了</li>
</ul>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-03-l-infinity.png" alt="L-infinity 距離算一次：城市分布訓練時台北 50 台中 30 高雄 20，上線第 1 個月台北 35 台中 30 高雄 35，每格的差取最大是 0.15 低於門檻 0.3 不警報；第 6 個月台北 10 高雄 60，差最大 0.40 超過門檻警報" class="wp-image-12869" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-03-l-infinity.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-03-l-infinity-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-03-l-infinity-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-03-l-infinity-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">4. 門檻、視窗、取樣率：三個旋鈕</h2>



<p class="wp-block-paragraph">官方的「使用 Model Monitoring 的考量」列了三個可以調的東西：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>旋鈕</th><th>預設</th><th>調低</th><th>調高</th></tr></thead><tbody><tr><td><strong>警報門檻</strong></td><td>每個特徵 0.3</td><td>更敏感，但<strong>誤報多</strong></td><td>省心，但<strong>漏掉小變化</strong></td></tr><tr><td><strong>監控視窗</strong>（頻率）</td><td>24 小時</td><td>反應快，但單一視窗樣本少、<strong>噪音大</strong></td><td>穩定，但<strong>發現得慢</strong></td></tr><tr><td><strong>取樣率</strong></td><td>自己設</td><td>省錢，但<strong>小變化看不到</strong></td><td>準，但 BigQuery 記錄和分析費用高</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">飲料店的做法：推薦模型一天 100 萬次請求，取樣 10% 就有 10 萬筆，夠準又省錢；流失模型每週才跑一次批次，用 v2 監控批次推論的輸出就好。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">5. 監控看不到的：概念漂移和真正的效能</h2>



<h3 class="wp-block-heading">問題</h3>



<p class="wp-block-paragraph">Model Monitoring 看的是<strong>輸入的分布</strong>。概念漂移是「輸入沒變、關係變了」，輸入分布<strong>完全正常</strong>，監控不會響。</p>



<h3 class="wp-block-heading">解法：持續評估</h3>



<p class="wp-block-paragraph"><strong>持續評估</strong>（continuous evaluation）：等<strong>真實答案</strong>回來，算模型的真實分數。</p>


<ul class="wp-block-list">
<li>流失模型今天說 M002 會流失，<strong>下個月</strong>才知道她有沒有真的沒來</li>

<li>把預測記下來（Model Monitoring 本來就記在 BigQuery），一個月後跟真實結果 JOIN，算 AUC、召回率（第 5、6 篇）</li>

<li>分數掉了，就是概念漂移或其他問題，觸發重訓或重新設計特徵</li>
</ul>



<p class="wp-block-paragraph">筆記裡的「持續評估（Continuous Evaluation）e.g., Mean Average Precision」就是這個概念；mAP 是物件偵測常用的指標。考試指南 6.2 寫的「用 Model Monitoring <strong>建立持續評估指標</strong>」，v2 的做法是定期跑監控工作，把指標畫成時間序列看趨勢。</p>



<p class="wp-block-paragraph"><strong>延遲標籤</strong>（delayed label）是這裡的難點：答案越晚回來，效能監控越慢。所以兩種監控要並用：輸入漂移監控<strong>早期預警</strong>，持續評估<strong>確認真的壞了</strong>。</p>



<h3 class="wp-block-heading">生成式 AI 也要監控</h3>



<p class="wp-block-paragraph">考試 6.2 最後一條「監控、測試、評估生成式 AI 方案」：大型語言模型沒有「正確答案」可以 JOIN，常用的做法是<strong>用另一個模型當評審</strong>（LLM-as-a-judge，考試指南 2.3 點名）打分、抽樣人工審核、記錄使用者的回饋（按讚、重問）。Model Armor（第 12 篇）則是監控提示詞和回答裡的安全問題。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">6. 偏見監控</h2>



<p class="wp-block-paragraph">考試 6.1「符合負責任 AI 實務（例如<strong>監控偏見</strong>）」。<strong>偏見</strong>（bias）是模型對某些群體系統性地不公平，例如流失模型對某個城市的會員一律判「會流失」，害他們收到更多騷擾簡訊。</p>



<p class="wp-block-paragraph">做法：</p>


<ul class="wp-block-list">
<li><strong>分段評估</strong>：第 19 篇驗證關卡那一招，各群體（城市、年齡層、新舊會員）分開算指標，差太多就是警訊。TFX 的 TFMA 切片評估就是做這個</li>

<li><strong>特徵歸因監控</strong>：v2 的「特徵歸因」目標，用 <strong>SHAP 值</strong>追蹤每個特徵的貢獻。某個敏感特徵（例如性別）的貢獻突然變大，就要查。第 21 篇可解釋 AI 會講 SHAP</li>

<li>注意：v1 的特徵歸因功能依賴 <strong>Vertex Explainable AI</strong>，而它在 2026 年 3 月 16 日<strong>淘汰</strong>、2027 年 3 月 16 日停用，官方建議改用 SHAP、LIME 這類開源工具。第 21 篇細講</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">在 GCP 上怎麼做</h2>



<h3 class="wp-block-heading">v1：端點上開監控</h3>


<ol class="wp-block-list">
<li>模型（表格 AutoML 或自訂表格）部署到端點</li>

<li>建監控工作：選<strong>偏差</strong>（要給訓練資料的 BigQuery 或 Cloud Storage 路徑）和／或<strong>漂移</strong>；設每個特徵的門檻（或用預設 0.3）、監控視窗、取樣率、email、通知管道</li>

<li>自訂模型給分析結構描述，或等前 1,000 筆自動解析</li>

<li>主控台看每個特徵的分布隨時間變化</li>

<li>警報 → Cloud Logging → Pub/Sub → Cloud Run 函式 → 重訓管線（第 19 篇）</li>
</ol>



<pre class="wp-block-code"><code>gcloud ai model-monitoring-jobs create \
  --region=asia-east1 \
  --endpoint=ENDPOINT_ID \
  --display-name=churn-monitor \
  --emails=ml-team@example.com \
  --feature-thresholds=city=0.2,avg_spend=0.3 \
  --monitoring-frequency=24 \
  --bigquery-uri=bq://PROJECT.drink.member_features_train</code></pre>



<h3 class="wp-block-heading">v2：模型版本上建監控器</h3>


<ol class="wp-block-list">
<li>模型註冊到 Model Registry（不在 Agent Platform 上服務的模型也可以，不用上傳模型檔）</li>

<li>建<strong>模型監控器</strong>（model monitor）綁模型版本，定義 schema（AutoML 自動有）</li>

<li>設預設的監控目標（輸入漂移、輸出漂移、特徵歸因）、訓練資料集當基準、輸出位置、通知</li>

<li>跑<strong>一次性</strong>或<strong>排程</strong>的監控工作，指標畫成時間序列</li>

<li>預覽期間 v2 本身不收費，但 BigQuery、Cloud Storage、批次推論、Cloud Logging 照收</li>
</ol>



<h3 class="wp-block-heading">改名對照</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>舊名稱（筆記、舊題庫）</th><th>現在</th></tr></thead><tbody><tr><td>Vertex AI Model Monitoring</td><td>Model Monitoring on Gemini Enterprise Agent Platform（v1 GA、v2 預覽）</td></tr><tr><td>Vertex Explainable AI（特徵歸因用）</td><td>2026 年 3 月淘汰、2027 年 3 月停用，改用 SHAP、LIME</td></tr><tr><td>Prediction Drift</td><td>Output Inference Drift（v2 的叫法）</td></tr><tr><td>Continuous Evaluation（舊的獨立功能）</td><td>用 Model Monitoring v2 的排程工作和自己的 BigQuery 查詢實作</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">考試會怎麼考</h2>



<p class="wp-block-paragraph">Google Cloud <strong>Professional Machine Learning Engineer（PMLE，專業機器學習工程師）</strong> 證照，2026 年 6 月 1 日起的<a href="https://services.google.com/fh/files/misc/professional_machine_learning_engineer_exam_guide_english_new.pdf">官方考試指南</a>裡，這篇的內容對應到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考試區塊</th><th>跟這篇有關的項目</th></tr></thead><tbody><tr><td>第 6 區：監控 AI 方案（約 13%）</td><td>6.1 符合負責任 AI 實務（<strong>監控偏見</strong>）。6.2 <strong>設定和使用 Model Monitoring 建立正式模型的持續評估指標</strong>；<strong>監控常見問題（訓練／服務偏差、資料漂移、概念漂移、特徵歸因漂移）</strong>；監控、測試、評估生成式 AI 方案</td></tr><tr><td>第 5 區：自動化與編排（約 18%）</td><td>5.1 確保訓練和服務的前處理一致（偏差的第 1 種原因）；5.2 重訓政策（監控觸發）</td></tr></tbody></table></figure>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-04-exam-keywords.png" alt="PMLE 考試關鍵字：上線資料跟訓練資料不一樣想到訓練服務偏差要提供訓練資料、上線後資料慢慢變想到資料漂移不用訓練資料、輸入正常但準確率掉想到概念漂移要持續評估、重要特徵的貢獻變了想到特徵歸因漂移、訓練和上線前處理不一致想到 TRANSFORM 或 Feature Store、警報要觸發重訓想到 Cloud Logging 到 Pub/Sub" class="wp-image-12870" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-04-exam-keywords.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-04-exam-keywords-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-04-exam-keywords-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml20-04-exam-keywords-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目出現的關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「上線的輸入分布跟訓練資料不一樣」「有訓練資料可以比」</td><td><strong>訓練／服務偏差</strong>偵測，給訓練資料路徑</td></tr><tr><td>「上線後輸入分布隨時間變」「沒有訓練資料」</td><td><strong>資料漂移</strong>偵測，基準是過去的上線資料</td></tr><tr><td>「輸入看起來正常，但準確率掉了」</td><td><strong>概念漂移</strong>，要<strong>持續評估</strong>（等真實標籤）</td></tr><tr><td>「重要特徵的貢獻突然變了」</td><td><strong>特徵歸因漂移</strong>（v2，SHAP）</td></tr><tr><td>「預測為正的比例突然暴增」</td><td><strong>預測／輸出漂移</strong>，先查上游管線有沒有壞</td></tr><tr><td>「訓練時標準化、上線時沒有」「單位不一樣」</td><td>偏差的第 1 種原因：<strong>TRANSFORM、TFT、Feature Store</strong>、共用程式碼</td></tr><tr><td>「類別特徵的距離」</td><td><strong>L-infinity</strong></td></tr><tr><td>「數值特徵的距離」</td><td><strong>Jensen-Shannon 散度</strong></td></tr><tr><td>「警報太多」</td><td>門檻調高、視窗拉長</td></tr><tr><td>「監控費用太高」</td><td>降<strong>取樣率</strong></td></tr><tr><td>「警報要自動觸發重訓」</td><td>email 以外，<strong>Cloud Logging → Pub/Sub</strong> → 重訓管線</td></tr><tr><td>「模型不是部署在 Agent Platform 端點」「批次推論也要監控」</td><td><strong>Model Monitoring v2</strong></td></tr><tr><td>「某個群體被系統性誤判」</td><td><strong>偏見</strong>：分段評估、特徵歸因監控</td></tr><tr><td>「大型語言模型的輸出品質」</td><td><strong>LLM-as-a-judge</strong>、人工抽查、Model Armor</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">六個常見陷阱</h3>


<ol class="wp-block-list">
<li><strong>以為輸入分布正常就沒事</strong>：概念漂移監控看不到，要持續評估</li>

<li><strong>沒有訓練資料卻選偏差偵測</strong>：偏差要訓練資料當基準，沒有就用漂移</li>

<li><strong>所有特徵都用預設 0.3</strong>：重要特徵要更敏感</li>

<li><strong>一有警報就重訓</strong>：先查是不是上游管線壞了（偏差第 1 種原因），重訓不會修好程式錯誤</li>

<li><strong>用 v1 監控影像模型</strong>：v1 只支援表格模型</li>

<li><strong>警報只寄 email</strong>：要接 Pub/Sub 才能自動重訓</li>
</ol>



<h3 class="wp-block-heading">練習情境（自己出的練習，不是真實考題）</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">飲料店的流失模型部署在 Agent Platform 端點三個月了，團隊有當初的訓練資料。他們想知道現在進來的會員資料是不是跟訓練時差很多，差太多要收到通知。應該怎麼設？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「有訓練資料」「跟訓練時比」→ <strong>偏差偵測</strong>（v1），<code>--bigquery-uri</code> 指向訓練資料</li>

<li>「收到通知」→ email＋Cloud Logging，之後接 Pub/Sub</li>

<li>重要特徵（距上次消費天數）門檻設低一點</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">推薦模型的監控三個月都沒警報，但行銷部門說推薦的點擊率從 8% 掉到 5%。問題可能是什麼？該怎麼抓？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「輸入沒警報、效果變差」→ <strong>概念漂移</strong>（輸入和答案的關係變了）</li>

<li>解法：<strong>持續評估</strong>，把預測和真實點擊 JOIN，定期算指標；用 v2 的排程監控工作畫趨勢</li>

<li>也檢查<strong>特徵歸因</strong>有沒有變（v2）</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">某天早上流失模型突然把 40% 的會員判成會流失（平常 5%），同時 <code>avg_spend</code> 和 <code>visits_90d</code> 兩個特徵一起觸發偏差警報。應該先做什麼？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「突然」「多個特徵同時」「預測比例暴增」→ 大概率是<strong>上游資料管線壞了</strong>（單位、欄位錯），不是世界變了</li>

<li>先<strong>查管線</strong>（偏差第 1 種原因），不是重訓</li>

<li>若是真的資料變了，再走重訓</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">模型上線後為什麼會變笨？</h3>



<p class="wp-block-paragraph">模型是用過去的資料學出來的規則，世界一變規則就不準。四種變法：訓練／服務偏差（上線資料跟訓練資料不一樣）、資料漂移（上線後輸入分布隨時間變）、概念漂移（輸入沒變但輸入和答案的關係變了）、特徵歸因漂移（重要特徵的貢獻變了）。Google 的例子是客戶習慣改變後，當初訓練用的特徵不再適用。</p>



<h3 class="wp-block-heading">Training-serving skew 和 drift 差在哪？</h3>



<p class="wp-block-paragraph">偏差是「上線 vs 訓練」的差異，基準是訓練資料的分布，所以要提供訓練資料；漂移是「現在 vs 之前」的差異，基準是過去在上線環境看到的分布，沒有訓練資料也能用。Google 的機器學習規則補充，偏差還有一種原因是訓練和服務的管線處理資料的方式不一樣，這種要在設計時用 TRANSFORM、Feature Store 防，監控抓不到。</p>



<h3 class="wp-block-heading">概念漂移是什麼？怎麼發現？</h3>



<p class="wp-block-paragraph">輸入資料的分布沒變，但輸入和答案之間的關係變了，例如疫情後「兩週沒來」不再代表流失。因為輸入分布正常，Model Monitoring 的偏差和漂移偵測不會響，要靠持續評估：等真實答案回來，把預測和真實結果 JOIN 算 AUC、召回率，分數掉了才知道。難點是答案常常要等很久（延遲標籤）。</p>



<h3 class="wp-block-heading">Model Monitoring 怎麼算「差多少」？</h3>



<p class="wp-block-paragraph">v1 用 TFDV 算分布：類別特徵數每個值的比例，數值特徵切成等寬區間數比例。然後算最新分布和基準分布的距離：類別特徵用 L-infinity 距離（每格比例差取最大），數值特徵用 Jensen-Shannon 散度，都是 0 到 1。超過你設的門檻（預設每個特徵 0.3）就判定為偏差或漂移並警報。</p>



<h3 class="wp-block-heading">Model Monitoring v1 和 v2 差在哪？</h3>



<p class="wp-block-paragraph">v1 是正式版，綁在 Agent Platform 端點上，監控線上推論輸入特徵的偏差和漂移，只支援表格模型，警報寄 email、Cloud Logging、Cloud Monitoring 通知管道。v2 是預覽版，綁在模型版本上，多了輸出推論漂移和特徵歸因（SHAP），可以監控批次推論和不在 Agent Platform 上服務的模型，用一次性或排程的監控工作把指標畫成時間序列。v1 不用遷移，兩版可並行。</p>



<h3 class="wp-block-heading">警報門檻、監控視窗、取樣率要怎麼設？</h3>



<p class="wp-block-paragraph">門檻預設每個特徵 0.3，重要特徵設低（更敏感）、本來就會波動的設高（少誤報）。監控視窗預設 24 小時、最小 1 小時，短的反應快但樣本少噪音大。取樣率決定分析多少比例的請求，低省錢但小變化看不到；請求量大的模型取樣 10% 通常就夠。</p>



<h3 class="wp-block-heading">監控警報怎麼自動觸發重訓？</h3>



<p class="wp-block-paragraph">v1 的警報除了 email，可以寫 Cloud Logging、送 Cloud Monitoring 的通知管道（PagerDuty、Slack、Pub/Sub）。設 Cloud Logging 的篩選條件或直接用 Pub/Sub 管道，Cloud Run 函式訂閱後啟動重訓管線，這是第 19 篇講的架構。但收到警報先確認不是上游管線壞了，再決定重訓。</p>



<h3 class="wp-block-heading">影像或文字模型怎麼監控？</h3>



<p class="wp-block-paragraph">Model Monitoring v1 只支援表格模型。影像、文字模型可以用 v2（綁模型版本、不限端點）監控輸出分布和特徵歸因，或自己記錄預測和信心分數到 BigQuery、定期人工抽查、等真實標籤回來做持續評估。生成式 AI 則用 LLM-as-a-judge 打分、人工審核、使用者回饋。</p>



<h3 class="wp-block-heading">怎麼監控模型有沒有偏見？</h3>



<p class="wp-block-paragraph">兩招：分段評估，把各群體（城市、年齡、新舊會員）分開算指標，差太多就是警訊，TFX 的 TFMA 切片評估做這個；特徵歸因監控，用 v2 的 SHAP 值追蹤每個特徵的貢獻，敏感特徵的貢獻突然變大就要查。考試指南 6.1 把「監控偏見」列在負責任 AI 底下。</p>



<h3 class="wp-block-heading">Vertex Explainable AI 淘汰了，特徵歸因監控還能用嗎？</h3>



<p class="wp-block-paragraph">Vertex Explainable AI 在 2026 年 3 月 16 日淘汰、2027 年 3 月 16 日停用，官方建議改用 SHAP、LIME 等開源工具。Model Monitoring v2 的特徵歸因目標用的是 SHAP 值。第 21 篇可解釋 AI 會細講替代方案。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>四種變笨</strong>：<strong>偏差</strong>（上線 vs 訓練）、<strong>資料漂移</strong>（現在 vs 之前）、<strong>概念漂移</strong>（關係變了，輸入正常）、<strong>特徵歸因漂移</strong>（重要性變了）；另有<strong>預測漂移</strong>是結果</li>

<li><strong>偏差的第 1 種原因</strong>（處理不一致）監控抓不到，靠 TRANSFORM、TFT、Feature Store、共用程式碼防</li>

<li><strong>Model Monitoring</strong>：請求記到 BigQuery → 取樣 → 每個視窗算分布 → 跟基準比（偏差＝訓練資料、漂移＝過去上線）→ 距離（類別 <strong>L-infinity</strong>、數值 <strong>Jensen-Shannon</strong>）→ 超過門檻（預設 <strong>0.3</strong>）→ email、Cloud Logging、Pub/Sub</li>

<li><strong>算一次</strong>：城市分布差最大的那格 0.15 不警報、0.40 警報</li>

<li><strong>三個旋鈕</strong>：門檻（敏感 vs 誤報）、視窗（快 vs 噪音）、取樣率（省錢 vs 漏）</li>

<li><strong>概念漂移</strong>要<strong>持續評估</strong>（等真實標籤 JOIN 算指標）；生成式 AI 用 LLM-as-a-judge</li>

<li><strong>v1</strong> GA、端點、表格；<strong>v2</strong> 預覽、模型版本、批次與外部模型、輸出漂移與 SHAP 特徵歸因；Explainable AI 2027 年停用</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/20/types-of-machine-learning-supervised-unsupervised-reinforcement/">機器學習有哪幾種？監督式、非監督式、強化學習一次看懂</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/10/20/classification-vs-regression-mae-rmse/">分類和迴歸差在哪？一個例子搞懂，附 MAE、RMSE 計算</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">特徵、標籤、超參數是什麼？機器學習 5 個必懂名詞</a></li>

<li>第 4 篇：<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">訓練集、驗證集、測試集怎麼切？時間序列為什麼不能亂切</a></li>

<li>第 5 篇：<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">混淆矩陣是什麼？用快篩搞懂準確率、精確率、召回率、F1</a></li>

<li>第 6 篇：<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">ROC 曲線和 AUC 怎麼看？門檻怎麼調、AUC-PR 差在哪</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">過度擬合是什麼？正則化、Dropout、提前停止 3 招解決</a></li>

<li>第 8 篇：<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">資料洩漏是什麼？模型考試作弊的 3 種常見情況</a></li>

<li>第 9 篇：<a href="https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/">類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</a></li>

<li>第 10 篇：<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">資料前處理怎麼做？標準化、遺失值、高基數類別</a></li>

<li>第 11 篇：<a href="https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/">特徵工程是什麼？特徵交叉、詞嵌入、資料增強一次看懂</a></li>

<li>第 12 篇：<a href="https://dongdonggcp.com/2026/10/25/machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls/">機器學習的資料隱私怎麼保護？DLP、聯邦學習、VPC Service Controls</a></li>

<li>第 13 篇：<a href="https://dongdonggcp.com/2026/10/25/tfrecords-tf-data-prefetch-input-pipeline/">訓練資料讀太慢？TFRecords、tf.data 與 prefetch 加速</a></li>

<li>第 14 篇：<a href="https://dongdonggcp.com/2026/10/25/vertex-ai-automl-bigquery-ml-custom-training-how-to-choose/">Vertex AI AutoML、BigQuery ML、自訂訓練怎麼選？</a></li>

<li>第 15 篇：<a href="https://dongdonggcp.com/2026/10/25/bigquery-ml-tutorial-train-model-with-sql/">BigQuery ML 入門：只會 SQL 也能訓練模型</a></li>

<li>第 16 篇：<a href="https://dongdonggcp.com/2026/10/25/vertex-ai-custom-training-containers-distributed-gpu-tpu/">Vertex AI 自訂訓練：容器、分散式訓練、GPU 與 TPU</a></li>

<li>第 17 篇：<a href="https://dongdonggcp.com/2026/10/25/model-deployment-online-vs-batch-prediction-traffic-split/">模型部署怎麼選？線上預測 vs 批次預測、流量分割</a></li>

<li>第 18 篇：<a href="https://dongdonggcp.com/2026/10/25/what-is-mlops-vertex-ai-pipelines-kubeflow-tfx/">MLOps 是什麼？Vertex AI Pipelines、Kubeflow、TFX 介紹</a></li>

<li>上一篇：第 19 篇：<a href="https://dongdonggcp.com/2026/10/25/ml-ci-cd-continuous-training-auto-retrain/">機器學習的 CI/CD：程式改了、資料來了，模型自動重訓</a></li>

<li>下一篇：第 21 篇：<a href="https://dongdonggcp.com/2026/10/25/explainable-ai-shapley-integrated-gradients-xrai/">可解釋 AI 是什麼？Shapley、Integrated Gradients、XRAI</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/07/04/is-bigquery-a-database-what-is-the-usage/">BigQuery 是資料庫嗎？跟資料庫差在哪</a></li>

<li><a href="https://dongdonggcp.com/2025/04/14/vertex-ai-functions-agent-builder-model-builder-model-garden-introduction/">Vertex AI 核心功能 Agent Builder、Model Builder 和 Model Garden 介紹</a></li>

<li><a href="https://dongdonggcp.com/2024/03/18/gcp-9-security-threats-and-how-to-resolve/">GCP 9 大資訊安全威脅與因應方案</a></li>

<li><a href="https://dongdonggcp.com/2026/07/29/cloud-jobs-comparison/">雲端職缺大解析：雲端工程師、架構師、SRE、DevOps、資料工程師差在哪？</a></li>

<li><a href="https://dongdonggcp.com/2026/05/19/gcp-bill-explosion-prevention-guide/">GCP 帳單爆炸防護指南</a></li>

<li><a href="https://dongdonggcp.com/2025/04/27/gcp-learning-roadmap/">GCP 學習路徑 Roadmap</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">模型上線不是結束，是開始盯著它的第一天。如果你想有系統地從雲端基礎一路學到在 GCP 上動手做機器學習，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "模型上線後為什麼會變笨？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "模型是用過去的資料學出來的規則，世界一變規則就不準。四種變法：訓練／服務偏差（上線資料跟訓練資料不一樣）、資料漂移（上線後輸入分布隨時間變）、概念漂移（輸入沒變但輸入和答案的關係變了）、特徵歸因漂移（重要特徵的貢獻變了）。Google 的例子是客戶習慣改變後，當初訓練用的特徵不再適用。"
      }
    },
    {
      "@type": "Question",
      "name": "Training-serving skew 和 drift 差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "偏差是「上線 vs 訓練」的差異，基準是訓練資料的分布，所以要提供訓練資料；漂移是「現在 vs 之前」的差異，基準是過去在上線環境看到的分布，沒有訓練資料也能用。Google 的機器學習規則補充，偏差還有一種原因是訓練和服務的管線處理資料的方式不一樣，這種要在設計時用 TRANSFORM、Feature Store 防，監控抓不到。"
      }
    },
    {
      "@type": "Question",
      "name": "概念漂移是什麼？怎麼發現？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "輸入資料的分布沒變，但輸入和答案之間的關係變了，例如疫情後「兩週沒來」不再代表流失。因為輸入分布正常，Model Monitoring 的偏差和漂移偵測不會響，要靠持續評估：等真實答案回來，把預測和真實結果 JOIN 算 AUC、召回率，分數掉了才知道。難點是答案常常要等很久（延遲標籤）。"
      }
    },
    {
      "@type": "Question",
      "name": "Model Monitoring 怎麼算「差多少」？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "v1 用 TFDV 算分布：類別特徵數每個值的比例，數值特徵切成等寬區間數比例。然後算最新分布和基準分布的距離：類別特徵用 L-infinity 距離（每格比例差取最大），數值特徵用 Jensen-Shannon 散度，都是 0 到 1。超過你設的門檻（預設每個特徵 0.3）就判定為偏差或漂移並警報。"
      }
    },
    {
      "@type": "Question",
      "name": "Model Monitoring v1 和 v2 差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "v1 是正式版，綁在 Agent Platform 端點上，監控線上推論輸入特徵的偏差和漂移，只支援表格模型，警報寄 email、Cloud Logging、Cloud Monitoring 通知管道。v2 是預覽版，綁在模型版本上，多了輸出推論漂移和特徵歸因（SHAP），可以監控批次推論和不在 Agent Platform 上服務的模型，用一次性或排程的監控工作把指標畫成時間序列。v1 不用遷移，兩版可並行。"
      }
    },
    {
      "@type": "Question",
      "name": "警報門檻、監控視窗、取樣率要怎麼設？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "門檻預設每個特徵 0.3，重要特徵設低（更敏感）、本來就會波動的設高（少誤報）。監控視窗預設 24 小時、最小 1 小時，短的反應快但樣本少噪音大。取樣率決定分析多少比例的請求，低省錢但小變化看不到；請求量大的模型取樣 10% 通常就夠。"
      }
    },
    {
      "@type": "Question",
      "name": "監控警報怎麼自動觸發重訓？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "v1 的警報除了 email，可以寫 Cloud Logging、送 Cloud Monitoring 的通知管道（PagerDuty、Slack、Pub/Sub）。設 Cloud Logging 的篩選條件或直接用 Pub/Sub 管道，Cloud Run 函式訂閱後啟動重訓管線，這是第 19 篇講的架構。但收到警報先確認不是上游管線壞了，再決定重訓。"
      }
    },
    {
      "@type": "Question",
      "name": "影像或文字模型怎麼監控？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Model Monitoring v1 只支援表格模型。影像、文字模型可以用 v2（綁模型版本、不限端點）監控輸出分布和特徵歸因，或自己記錄預測和信心分數到 BigQuery、定期人工抽查、等真實標籤回來做持續評估。生成式 AI 則用 LLM-as-a-judge 打分、人工審核、使用者回饋。"
      }
    },
    {
      "@type": "Question",
      "name": "怎麼監控模型有沒有偏見？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "兩招：分段評估，把各群體（城市、年齡、新舊會員）分開算指標，差太多就是警訊，TFX 的 TFMA 切片評估做這個；特徵歸因監控，用 v2 的 SHAP 值追蹤每個特徵的貢獻，敏感特徵的貢獻突然變大就要查。考試指南 6.1 把「監控偏見」列在負責任 AI 底下。"
      }
    },
    {
      "@type": "Question",
      "name": "Vertex Explainable AI 淘汰了，特徵歸因監控還能用嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Vertex Explainable AI 在 2026 年 3 月 16 日淘汰、2027 年 3 月 16 日停用，官方建議改用 SHAP、LIME 等開源工具。Model Monitoring v2 的特徵歸因目標用的是 SHAP 值。第 21 篇可解釋 AI 會細講替代方案。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/10/25/model-monitoring-drift-training-serving-skew/">模型上線後會變笨？Drift 與 Training-Serving Skew 監控</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/10/25/model-monitoring-drift-training-serving-skew/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>BigQuery ML 入門：只會 SQL 也能訓練模型</title>
		<link>https://dongdonggcp.com/2026/10/25/bigquery-ml-tutorial-train-model-with-sql/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=bigquery-ml-tutorial-train-model-with-sql</link>
					<comments>https://dongdonggcp.com/2026/10/25/bigquery-ml-tutorial-train-model-with-sql/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 25 Oct 2026 05:42:00 +0000</pubDate>
				<category><![CDATA[AI 和機器學習]]></category>
		<category><![CDATA[證照考試]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[BigQuery]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[PMLE]]></category>
		<category><![CDATA[Vertex AI]]></category>
		<category><![CDATA[機器學習]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=12844</guid>

					<description><![CDATA[<p>BigQuery ML 入門：三句 SQL 做完會員流失預測。CREATE MODEL 訓練、ML.PREDICT 預測，自動前處理、TRANSFORM、資料切分規則、ARIMA_PLUS 與費用算一次，附 PMLE 考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/10/25/bigquery-ml-tutorial-train-model-with-sql/">BigQuery ML 入門：只會 SQL 也能訓練模型</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>BigQuery ML 入門只要三句 SQL：CREATE MODEL 訓練、ML.EVALUATE 評估、ML.PREDICT 預測。</strong></p>



<p class="wp-block-paragraph">上一篇說，資料已經在 BigQuery、團隊會 SQL，就用 BigQuery ML。這篇就把它從頭到尾做一遍：怎麼寫、它背後幫你做了什麼、資料怎麼切、超參數怎麼調、要花多少錢。</p>



<p class="wp-block-paragraph">一樣用有 2,000 間分店、50 萬名會員的連鎖飲料店當例子（教學假設），要做的是<strong>會員流失預測</strong>：哪些會員下個月不會再來？會員表和交易表都已經在 BigQuery 裡。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-01-three-steps.png" alt="BigQuery ML 入門三步驟：CREATE MODEL 用 SQL 訓練模型、ML.EVALUATE 看準確率召回率 AUC、ML.PREDICT 對整張表批次預測，資料全程留在 BigQuery" class="wp-image-12840" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-01-three-steps.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-01-three-steps-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-01-three-steps-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-01-three-steps-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>最低門檻的機器學習</strong>：Google 官方<a href="https://docs.cloud.google.com/bigquery/docs/bqml-introduction">簡介</a>說得很直接，以前做 ML 要會 Python 和 ML 框架，把「最懂資料的人」排除在外；BigQuery ML 讓會 SQL 的人也能做。官方的「需要什麼知識」那段寫著：用預設設定，<strong>沒什麼 ML 知識也能建模型</strong></li>

<li><strong>資料不用搬</strong>：幾 TB 的表搬去 Python 環境，光搬就要半天。BigQuery ML 把 ML 帶到資料旁邊</li>

<li><strong>前面 14 篇學的東西都用得上</strong>：資料切分（第 4 篇）、評估指標（第 5、6 篇）、過度擬合（第 7 篇）、類別不平衡（第 9 篇）、前處理（第 10 篇）、特徵工程（第 11 篇）在 BigQuery ML 裡都有對應的開關。這篇會一個一個對回去</li>

<li><strong>證照必考</strong>：PMLE 考試指南第 1.1 節整節都是它：用 BigQuery ML 建分類、迴歸、預測、分群模型；用 BigQuery ML 做特徵工程和特徵選擇；用 BigQuery ML 產生預測</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">先搞懂：BigQuery ML 是什麼</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>BigQuery ML</strong>：在 BigQuery 裡用 SQL 指令建立、訓練、使用機器學習模型。模型跟表格一樣存在 BigQuery 的資料集裡。</p>



<p class="wp-block-paragraph">幾個名詞先講：</p>


<ul class="wp-block-list">
<li><strong>BigQuery</strong>：Google 的資料倉儲，存大量表格資料、用 SQL 查，站上有<a href="https://dongdonggcp.com/2024/11/23/what-is-bigquery-functions-advantages/">BigQuery 是什麼</a></li>

<li><strong>SQL</strong>：查詢表格的語言。<code>SELECT 姓名 FROM 會員表 WHERE 年齡 &gt; 30</code> 這種句子</li>

<li><strong>資料集</strong>（dataset）：BigQuery 裡放表格的資料夾；<strong>表</strong>（table）就是一張表格；<strong>檢視</strong>（view）是存起來的查詢結果，看起來像表</li>

<li><strong>NULL</strong>：欄位裡的「空值」，代表沒填或不知道</li>
</ul>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">倉庫旁邊的廚房（上一篇的比喻）。這篇要講的是這間廚房的爐子怎麼開、菜單上有什麼、哪些調味是自動的、瓦斯費怎麼算。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">BigQuery ML 剛推出時只有線性迴歸和邏輯迴歸兩種，現在<a href="https://docs.cloud.google.com/bigquery/docs/e2e-journey">官方清單</a>已經有十幾種：監督式的線性／邏輯迴歸、DNN、Wide &amp; Deep、提升樹、隨機森林、AutoML；非監督式的 K-means、矩陣分解、自動編碼器、PCA；時間序列的 ARIMA_PLUS；還能匯入外面訓練的模型、遠端呼叫 Gemini。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">這是 Google Cloud 上<strong>最快能看到結果</strong>的機器學習方式。會 SQL 的人，一個下午就能從資料表做出第一個模型。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">1. 三句 SQL 做完一個模型</h2>



<h3 class="wp-block-heading">第 0 步：準備一張表</h3>



<p class="wp-block-paragraph">機器學習要的是「一列一個樣本、每欄一個特徵、其中一欄是答案」（第 3 篇）。先用 SQL 把會員表和交易表整理成這樣：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>member_id</th><th>visits_90d</th><th>avg_spend</th><th>days_since_last</th><th>member_months</th><th>city</th><th>churned</th></tr></thead><tbody><tr><td>M001</td><td>12</td><td>65</td><td>3</td><td>18</td><td>台北</td><td>0</td></tr><tr><td>M002</td><td>1</td><td>80</td><td>75</td><td>4</td><td>台中</td><td>1</td></tr><tr><td>…</td><td></td><td></td><td></td><td></td><td></td><td></td></tr></tbody></table></figure>


<ul class="wp-block-list">
<li><code>visits_90d</code>：最近 90 天來幾次；<code>avg_spend</code>：平均客單價；<code>days_since_last</code>：距離上次消費幾天；<code>member_months</code>：加入幾個月；<code>city</code>：城市</li>

<li><code>churned</code>：<strong>標籤</strong>，1 代表這位會員接下來一個月沒再來（流失），0 代表有來</li>
</ul>



<p class="wp-block-paragraph">答案欄怎麼來？用歷史資料「回頭看」：拿去年 6 月的會員狀態當特徵、7 月有沒有來當答案。這一步要小心<strong>資料洩漏</strong>（第 8 篇），特徵只能用 6 月以前知道的事。</p>



<h3 class="wp-block-heading">第 1 句：CREATE MODEL 訓練</h3>



<pre class="wp-block-code"><code>CREATE OR REPLACE MODEL `drink.churn_model`
OPTIONS (
  model_type = 'LOGISTIC_REG',
  input_label_cols = ['churned'],
  auto_class_weights = TRUE,
  enable_global_explain = TRUE
) AS
SELECT visits_90d, avg_spend, days_since_last, member_months, city, churned
FROM `drink.member_features`;</code></pre>



<p class="wp-block-paragraph">一行一行翻譯：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>這一行</th><th>白話</th></tr></thead><tbody><tr><td><code>CREATE OR REPLACE MODEL</code></td><td>建一個模型，已經有同名的就覆蓋</td></tr><tr><td><code>model_type = 'LOGISTIC_REG'</code></td><td>用<strong>邏輯迴歸</strong>（第 2 篇講的分類模型）。要做迴歸就改 <code>LINEAR_REG</code>，要用 XGBoost 改 <code>BOOSTED_TREE_CLASSIFIER</code></td></tr><tr><td><code>input_label_cols = ['churned']</code></td><td>哪一欄是<strong>答案</strong></td></tr><tr><td><code>auto_class_weights = TRUE</code></td><td>流失的會員比沒流失的少很多（第 9 篇的<strong>類別不平衡</strong>），這個開關會自動把少數類別加權。官方說明：依類別出現頻率的反比加權</td></tr><tr><td><code>enable_global_explain = TRUE</code></td><td>訓練完順便算「哪些特徵整體最重要」，後面 <code>ML.GLOBAL_EXPLAIN</code> 會用到</td></tr><tr><td><code>AS SELECT ...</code></td><td><strong>訓練資料就是這個查詢的結果</strong>。沒選進來的欄位不會被用到</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">注意 <code>member_id</code> 沒有被 SELECT 進去。會員編號對「會不會流失」沒有意義，放進去只會讓模型記答案（第 7 篇過度擬合）。</p>



<h3 class="wp-block-heading">第 2 句：ML.EVALUATE 評估</h3>



<pre class="wp-block-code"><code>SELECT * FROM ML.EVALUATE(MODEL `drink.churn_model`);</code></pre>



<p class="wp-block-paragraph">不給它資料，它會自動用訓練時<strong>切出來的評估資料</strong>算分數（切法下一節講）。分類模型會回傳一列：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>欄位</th><th>就是第 5、6 篇的</th></tr></thead><tbody><tr><td><code>precision</code></td><td>精確率</td></tr><tr><td><code>recall</code></td><td>召回率</td></tr><tr><td><code>accuracy</code></td><td>準確率</td></tr><tr><td><code>f1_score</code></td><td>F1</td></tr><tr><td><code>log_loss</code></td><td>對數損失（越小越好）</td></tr><tr><td><code>roc_auc</code></td><td>AUC-ROC</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">迴歸模型回傳的是 <code>mean_absolute_error</code>（MAE）、<code>mean_squared_error</code>、<code>r2_score</code> 這些（第 2 篇）。</p>



<p class="wp-block-paragraph">要用別的<strong>門檻</strong>（第 6 篇），加 <code>STRUCT(0.3 AS threshold)</code> 這個參數；預設是 0.5。想看整張混淆矩陣用 <code>ML.CONFUSION_MATRIX</code>，想畫 ROC 曲線用 <code>ML.ROC_CURVE</code>。</p>



<h3 class="wp-block-heading">第 3 句：ML.PREDICT 預測</h3>



<pre class="wp-block-code"><code>SELECT member_id, predicted_churned, predicted_churned_probs
FROM ML.PREDICT(
  MODEL `drink.churn_model`,
  TABLE `drink.member_features_today`,
  STRUCT(0.3 AS threshold)
);</code></pre>


<ul class="wp-block-list">
<li>輸入是今天的會員特徵表，<strong>欄位名稱要跟訓練時一樣</strong></li>

<li>輸出多兩欄：<code>predicted_churned</code>（預測的答案，0 或 1）和 <code>predicted_churned_probs</code>（每個類別的機率）。欄位名稱規則是 <code>predicted_</code> 加上標籤欄的名字</li>

<li><code>threshold</code> 設 0.3：機率超過 30% 就判定會流失。流失預測寧可多抓（第 5 篇講的「追召回率」），門檻就調低</li>
</ul>



<p class="wp-block-paragraph">這是<strong>批次預測</strong>：一次對整張表算完，結果就是一張新的表，可以直接拿去寄挽留優惠。要做「會員一打開 App 就即時算」的線上預測，要走 Model Registry，<a href="https://dongdonggcp.com/2026/10/25/model-deployment-online-vs-batch-prediction-traffic-split/">第 17 篇</a>講。</p>



<h3 class="wp-block-heading">加碼：ML.EXPLAIN_PREDICT 看為什麼</h3>



<pre class="wp-block-code"><code>SELECT * FROM ML.EXPLAIN_PREDICT(
  MODEL `drink.churn_model`,
  TABLE `drink.member_features_today`,
  STRUCT(3 AS top_k_features)
);</code></pre>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-explain-predict">官方說明</a>：它是 <code>ML.PREDICT</code> 的加強版，每一列多回傳「哪幾個特徵對這筆預測貢獻最大」，<code>top_k_features</code> 預設 5 個。例如 M002 被判會流失，是因為 <code>days_since_last = 75</code>（75 天沒來）貢獻最大。<a href="https://dongdonggcp.com/2026/10/25/explainable-ai-shapley-integrated-gradients-xrai/">第 21 篇</a>可解釋 AI 會細講。</p>



<p class="wp-block-paragraph"><strong>筆記裡寫的「BQML.PREDICT」「BQML.EXPLAIN_PREDICT」</strong>，正確名稱是 <code>ML.PREDICT</code> 和 <code>ML.EXPLAIN_PREDICT</code>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">2. 它幫你自動做了什麼：前處理</h2>



<p class="wp-block-paragraph">第 10 篇講的標準化、遺失值、One-hot，BigQuery ML 在 <code>CREATE MODEL</code> 時<strong>預設就自動做</strong>。<a href="https://docs.cloud.google.com/bigquery/docs/auto-preprocessing">官方自動前處理文件</a>：</p>



<h3 class="wp-block-heading">遺失值（NULL）怎麼補</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>欄位型態</th><th>自動補法</th></tr></thead><tbody><tr><td>數字</td><td>用該欄的<strong>平均值</strong>補（訓練和預測都一樣）</td></tr><tr><td>文字、布林（One-hot 過的）</td><td>當成一個<strong>額外的類別</strong>「NULL」；預測時遇到沒看過的值，權重給 0</td></tr><tr><td>時間戳記</td><td>混合用：Unix 時間用平均值，其他拆出來的部分歸到 NULL 類別</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">套回例子：某位會員 <code>avg_spend</code> 是 NULL（從沒消費過），自動補成所有會員的平均客單價。這不一定是你要的（沒消費過跟平均客單價差很多），要自己控制就用下面的 TRANSFORM。</p>



<h3 class="wp-block-heading">特徵怎麼轉換</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>輸入型態</th><th>自動轉換</th><th>例外</th></tr></thead><tbody><tr><td>數字（INT64、FLOAT64…）</td><td><strong>標準化</strong>（第 10 篇：<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">資料前處理怎麼做？標準化、遺失值、高基數類別</a></td><td>提升樹、隨機森林不做；K-means 由 <code>STANDARDIZE_FEATURES</code> 選項決定</td></tr><tr><td>文字、布林、日期</td><td><strong>One-hot 編碼</strong>（每個值一欄）</td><td>提升樹、隨機森林改用標籤編碼（每個值換一個數字）</td></tr><tr><td>陣列</td><td>Multi-hot 編碼（每個元素一欄）</td><td></td></tr><tr><td>時間戳記</td><td>拆成年、月、星期幾等，數字的標準化、類別的 One-hot</td><td></td></tr></tbody></table></figure>



<p class="wp-block-paragraph">所以 <code>city</code> 這種文字欄直接丟進去就好，它會自動變成「台北、台中、高雄…」各一欄。</p>



<h3 class="wp-block-heading">想自己控制：TRANSFORM 子句</h3>



<p class="wp-block-paragraph">第 11 篇講的特徵工程，用 <code>TRANSFORM</code> 寫在 <code>CREATE MODEL</code> 裡：</p>



<pre class="wp-block-code"><code>CREATE OR REPLACE MODEL `drink.churn_model_v2`
TRANSFORM (
  ML.QUANTILE_BUCKETIZE(avg_spend, 5) OVER () AS spend_bucket,
  ML.FEATURE_CROSS(STRUCT(city, spend_bucket)) AS city_x_spend,
  visits_90d, days_since_last, member_months, churned
)
OPTIONS (model_type = 'LOGISTIC_REG', input_label_cols = ['churned']) AS
SELECT * FROM `drink.member_features`;</code></pre>


<ul class="wp-block-list">
<li><code>ML.QUANTILE_BUCKETIZE(avg_spend, 5)</code>：客單價切成 5 個等人數的<strong>分桶</strong>（第 10 篇）</li>

<li><code>ML.FEATURE_CROSS</code>：城市 × 客單價桶的<strong>特徵交叉</strong>（第 11 篇）</li>

<li><a href="https://docs.cloud.google.com/bigquery/docs/manual-preprocessing">官方手動前處理文件</a>列的函數還有 <code>ML.STANDARD_SCALER</code>、<code>ML.MIN_MAX_SCALER</code>、<code>ML.BUCKETIZE</code>、<code>ML.IMPUTER</code>（自己決定遺失值怎麼補）、<code>ML.NGRAMS</code> 等</li>
</ul>



<p class="wp-block-paragraph"><strong>TRANSFORM 最大的好處</strong>：訓練時怎麼轉，<code>ML.PREDICT</code> 時<strong>自動用同樣的方式轉</strong>，連分桶的切點都沿用訓練時算的。這正是第 10 篇講的「訓練和上線前後不一致」（training-serving skew，<a href="https://dongdonggcp.com/2026/10/25/model-monitoring-drift-training-serving-skew/">第 20 篇</a>會再講）的解法。官方特別寫了一句：分析函數在 TRANSFORM 裡用，訓練時收集的統計值會自動套用到預測輸入。</p>



<p class="wp-block-paragraph">想把「轉換」和「訓練」分開管理，可以建一個<strong>只做轉換的模型</strong>（transform-only model），用 <code>ML.TRANSFORM</code> 看它轉出來的結果長什麼樣。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">3. 資料怎麼切：AUTO_SPLIT 的規則</h2>



<p class="wp-block-paragraph">第 4 篇講過訓練集、驗證集要分開。BigQuery ML 用 <code>DATA_SPLIT_METHOD</code> 選項控制，<a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-create-glm">官方說明</a>的預設值是 <code>AUTO_SPLIT</code>，規則是：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>輸入資料列數</th><th>怎麼切</th></tr></thead><tbody><tr><td><strong>少於 500 列</strong></td><td>全部拿來訓練，不切</td></tr><tr><td><strong>500 到 50,000 列</strong></td><td>隨機 <strong>20%</strong> 當評估資料、80% 訓練</td></tr><tr><td><strong>超過 50,000 列</strong></td><td>隨機抽 <strong>10,000 列</strong>當評估資料，其餘訓練</td></tr><tr><td>有開超參數調校（超過 500 列）</td><td>80% 訓練、10% 評估、10% 測試</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">算一次</h3>



<pre class="wp-block-code"><code>飲料店 50 萬名會員 → 超過 50,000 列
評估資料 = 10,000 列（固定）
訓練資料 = 500,000 − 10,000 = 490,000 列
評估比例 = 10,000 ÷ 500,000 = 2%</code></pre>



<p class="wp-block-paragraph">資料越多，評估比例越小，因為 10,000 列已經夠算出穩定的分數，多切只是浪費訓練資料。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-02-auto-split.png" alt="BigQuery ML 的 AUTO_SPLIT 資料切分規則：少於 500 列全部訓練、500 到 50,000 列切 20% 評估、超過 50,000 列固定抽 10,000 列評估、開超參數調校時 80 訓練 10 評估 10 測試，時間序列要用 SEQ" class="wp-image-12841" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-02-auto-split.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-02-auto-split-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-02-auto-split-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-02-auto-split-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">其他切法</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>選項</th><th>什麼時候用</th></tr></thead><tbody><tr><td><code>RANDOM</code></td><td>自己指定評估比例（<code>DATA_SPLIT_EVAL_FRACTION</code>）</td></tr><tr><td><code>SEQ</code></td><td><strong>依順序切</strong>，最後面的當評估資料。第 4 篇講的時間序列不能亂切，就用這個，搭配 <code>DATA_SPLIT_COL</code> 指定時間欄</td></tr><tr><td><code>CUSTOM</code></td><td>自己加一欄 TRUE／FALSE 標哪些是評估資料</td></tr><tr><td><code>NO_SPLIT</code></td><td>全部訓練，自己另外準備評估資料給 <code>ML.EVALUATE</code></td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/bigquery/docs/logistic-regression-prediction">官方邏輯迴歸教學</a>用的就是自己切：加一欄 <code>dataframe</code>，標 training、evaluation、prediction 三種，訓練時只選 training 的列，評估時把 evaluation 的列餵給 <code>ML.EVALUATE</code>。</p>



<p class="wp-block-paragraph">評估資料的用途，官方寫得很清楚：<strong>用提前停止來避免過度擬合</strong>（第 7 篇）。每一輪訓練完看評估資料的損失有沒有進步，進步幅度小於 <code>MIN_REL_PROGRESS</code> 就停，開關是 <code>EARLY_STOP</code>（預設開）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">4. 超參數怎麼調</h2>



<p class="wp-block-paragraph">第 3 篇說超參數是「訓練前自己決定的設定」，例如正則化強度 <code>L1_REG</code>、<code>L2_REG</code>（第 7 篇）、學習率。手動一個一個試很累，BigQuery ML 的<a href="https://docs.cloud.google.com/bigquery/docs/hp-tuning-overview">超參數調校</a>讓它自己試：</p>



<pre class="wp-block-code"><code>CREATE OR REPLACE MODEL `drink.churn_model_tuned`
OPTIONS (
  model_type = 'LOGISTIC_REG',
  input_label_cols = ['churned'],
  num_trials = 20,
  l1_reg = HPARAM_RANGE(0, 1),
  l2_reg = HPARAM_CANDIDATES([0, 0.1, 1, 10])
) AS
SELECT * FROM `drink.member_features`;</code></pre>


<ul class="wp-block-list">
<li><code>num_trials = 20</code>：試 20 組</li>

<li><code>HPARAM_RANGE(0, 1)</code>：在 0 到 1 之間找</li>

<li><code>HPARAM_CANDIDATES([...])</code>：從這幾個值裡挑</li>

<li>跑完用 <code>ML.TRIAL_INFO</code> 看每一組的分數，<code>ML.EVALUATE</code> 預設回傳最好的那組</li>
</ul>



<p class="wp-block-paragraph">支援調校的模型：線性／邏輯迴歸、K-means、矩陣分解、自動編碼器、提升樹、隨機森林、DNN、Wide &amp; Deep。AutoML 本來就內建自動調校；ARIMA_PLUS 用 <code>AUTO_ARIMA</code> 自動找趨勢參數。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">5. 不只分類：時間序列和分群</h2>



<h3 class="wp-block-heading">時間序列：ARIMA_PLUS</h3>



<p class="wp-block-paragraph">飲料店要預測每間分店未來 30 天的銷量，<a href="https://docs.cloud.google.com/bigquery/docs/arima-single-time-series-forecasting-tutorial">官方教學</a>的寫法：</p>



<pre class="wp-block-code"><code>CREATE OR REPLACE MODEL `drink.sales_forecast`
OPTIONS (
  model_type = 'ARIMA_PLUS',
  time_series_timestamp_col = 'sale_date',
  time_series_data_col = 'daily_sales',
  time_series_id_col = 'store_id',
  holiday_region = 'TW'
) AS
SELECT sale_date, daily_sales, store_id FROM `drink.daily_sales`;

SELECT * FROM ML.FORECAST(MODEL `drink.sales_forecast`,
  STRUCT(30 AS horizon, 0.8 AS confidence_level));</code></pre>


<ul class="wp-block-list">
<li><code>time_series_id_col</code>：一次幫 2,000 間分店各做一個模型</li>

<li><code>holiday_region</code>：把台灣的假日效應算進去（官方教學用美國假日舉例）</li>

<li><code>ML.FORECAST</code> 的 <code>horizon = 30</code> 是預測未來 30 天，<code>confidence_level = 0.8</code> 是給 80% 的預測區間（上下界）</li>

<li>官方簡介提到，ARIMA_PLUS 會<strong>自動處理異常值、季節性、假日</strong>；<code>ML.EXPLAIN_FORECAST</code> 可以把趨勢、季節性拆開看</li>
</ul>



<p class="wp-block-paragraph">不想管模型，官方簡介說可以用 <code>AI.FORECAST</code> 函數搭內建的 <strong>TimesFM</strong> 模型（預覽階段）直接預測。</p>



<h3 class="wp-block-heading">分群：K-means</h3>



<p class="wp-block-paragraph">不知道會員分幾種，想讓模型自己找（第 1 篇的非監督式學習）：<code>model_type = 'KMEANS'</code>，不用 <code>input_label_cols</code>，因為沒有答案。預測結果是每位會員屬於哪一群（<code>CENTROID_ID</code>），<code>ML.CENTROIDS</code> 看每一群的中心長什麼樣。</p>



<h3 class="wp-block-heading">推薦：矩陣分解</h3>



<p class="wp-block-paragraph">「猜你想點」：<code>model_type = 'MATRIX_FACTORIZATION'</code>，輸入是「誰買過什麼、評幾分」，<code>ML.RECOMMEND</code> 回傳每位會員對每種飲料的預測評分。官方定價頁註明矩陣分解只開放給 Editions 或有保留算力的客戶。</p>



<h3 class="wp-block-heading">要更強的模型</h3>



<p class="wp-block-paragraph"><code>BOOSTED_TREE_CLASSIFIER</code>（XGBoost）、<code>DNN_CLASSIFIER</code>、<code>AUTOML_CLASSIFIER</code> 這些寫法一樣是 SQL，但官方簡介說它們是「在 Agent Platform 訓練」：BigQuery 把工作送去 Agent Platform（原 Vertex AI）算完再拿回來。你感覺不到差別，只有費用算法不同（下一節）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">6. 要花多少錢：算一次</h2>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/bigquery/pricing">官方定價頁</a>的 BigQuery ML 段落，重點是：</p>


<ul class="wp-block-list">
<li><strong>按量計費</strong>（on-demand）時，依「操作類型」收費：建模型、評估、檢查、預測各有價格</li>

<li><strong>評估、檢查、預測</strong>跟一般查詢<strong>同價</strong>，而且算在每月 1 TiB 的免費額度裡</li>

<li><strong>建模型（CREATE MODEL）</strong>是另一個價格，依輸入查詢處理的資料量計算</li>

<li><strong>超參數調校</strong>：每一組試驗都是一次建模型，費用是所有試驗的總和</li>

<li><strong>時間序列開 auto-ARIMA</strong>：會試很多候選模型，處理的位元組數要乘上候選模型數（<code>AUTO_ARIMA_MAX_ORDER</code> 設 5 時最多 42 個）</li>

<li>迭代式模型<strong>最多跑 50 輪</strong>就停</li>

<li>用 <strong>Editions</strong>（買算力）的話，BigQuery ML 包含在裡面；外部訓練的模型（DNN、提升樹、AutoML）要另外用 <code>ML_EXTERNAL</code> 類型的保留算力</li>
</ul>



<p class="wp-block-paragraph">官方頁面有一個計算範例，美國多區域的建模型價格是每 TiB 312.5 美元。套到飲料店（台灣區域價格請看定價頁，這裡用官方範例的數字）：</p>



<pre class="wp-block-code"><code>會員特徵表 2 GB
建模型費用 = 2 ÷ 1,024 TiB × 312.5 美元 ≈ 0.61 美元

超參數調校 20 組試驗
= 20 × 0.61 ≈ 12.2 美元

ARIMA_PLUS 開 auto-ARIMA、AUTO_ARIMA_MAX_ORDER = 5
銷售表 500 MB × 42 個候選模型 = 21 GB 的處理量
≈ 21 ÷ 1,024 × 312.5 ≈ 6.4 美元</code></pre>



<p class="wp-block-paragraph"><strong>數字怎麼看</strong>：</p>


<ul class="wp-block-list">
<li>一個 2 GB 的表建模型不到 1 美元，這就是「最快看到結果」的代價，很便宜</li>

<li>超參數調校和 auto-ARIMA 是<strong>倍數</strong>在長，試驗組數和候選模型數決定費用</li>

<li><code>ML.PREDICT</code> 對 50 萬列預測，就是掃一次表的查詢費，通常在免費額度內</li>

<li>內建模型可以先 <strong>dry run</strong>（試跑不執行）估處理量；外部訓練的模型不能</li>
</ul>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-03-cost.png" alt="BigQuery ML 費用算一次：建模型依處理資料量計價，2 GB 的表用官方範例價格約 0.61 美元；超參數調校 20 組就乘 20；評估與預測跟一般查詢同價，算在每月 1 TiB 免費額度" class="wp-image-12842" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-03-cost.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-03-cost-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-03-cost-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-03-cost-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p class="wp-block-paragraph">站上有一篇 <a href="https://dongdonggcp.com/2026/03/27/bigquery-billing-guide/">BigQuery 計費方式</a>，按量和 Editions 的差別那篇講得更細。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">在 GCP 上怎麼做</h2>



<h3 class="wp-block-heading">1. 從哪裡下 SQL</h3>



<p class="wp-block-paragraph">官方簡介列的入口：Google Cloud 主控台的查詢編輯器、<code>bq</code> 命令列工具、REST API、BigQuery 裡的 Colab Enterprise 筆記本、外部工具（Jupyter、BI 平台）。會 Python 的人也可以用 <strong>BigQuery DataFrames</strong>（<code>bigframes</code>），官方教學每一步都有 SQL 和 DataFrames 兩種寫法。</p>



<h3 class="wp-block-heading">2. 資料先進 BigQuery</h3>



<p class="wp-block-paragraph">CSV、Cloud Storage、串流、其他資料庫都有辦法，站上有一篇<a href="https://dongdonggcp.com/2025/02/12/how-to-upload-data-to-bigquery/">把資料上傳到 BigQuery 的各種方法</a>。</p>



<h3 class="wp-block-heading">3. 要線上預測：註冊到 Model Registry</h3>



<p class="wp-block-paragraph"><code>ML.PREDICT</code> 是批次。要做「App 一打開就即時算流失機率」，<a href="https://docs.cloud.google.com/bigquery/docs/managing-models-vertex">官方文件</a>的做法是在 <code>CREATE MODEL</code> 加上：</p>



<pre class="wp-block-code"><code>OPTIONS (
  model_type = 'LOGISTIC_REG',
  input_label_cols = ['churned'],
  model_registry = 'VERTEX_AI',
  vertex_ai_model_id = 'churn_model'
)</code></pre>



<p class="wp-block-paragraph">模型會自動註冊到 Agent Platform 的 <strong>Model Registry</strong>，不用匯出、不用自己做服務容器，就能部署成端點做線上預測、管版本。需要 <code>roles/aiplatform.admin</code> 權限，而且要先開 Agent Platform API。部署的細節第 17 篇講。</p>



<h3 class="wp-block-heading">4. 改名對照</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>舊名稱</th><th>現在</th></tr></thead><tbody><tr><td>BQML、BigQuery ML</td><td>沒變</td></tr><tr><td>BQML.PREDICT（筆記寫法）</td><td><code>ML.PREDICT</code></td></tr><tr><td>Vertex AI Model Registry</td><td>Gemini Enterprise Agent Platform Model Registry（SQL 選項名稱仍是 <code>model_registry = 'VERTEX_AI'</code>）</td></tr><tr><td>「在 Vertex AI 訓練」的外部模型</td><td>在 Agent Platform 訓練，寫法不變</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">考試會怎麼考</h2>



<p class="wp-block-paragraph">Google Cloud <strong>Professional Machine Learning Engineer（PMLE，專業機器學習工程師）</strong> 證照，2026 年 6 月 1 日起的<a href="https://services.google.com/fh/files/misc/professional_machine_learning_engineer_exam_guide_english_new.pdf">官方考試指南</a>裡，這篇的內容對應到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考試區塊</th><th>跟這篇有關的項目</th></tr></thead><tbody><tr><td>第 1 區：設計低程式碼 AI 方案（約 13%）</td><td>1.1 <strong>用 BigQuery ML 建模型</strong>（分類、迴歸、預測、分群）；<strong>用 BigQuery ML 做特徵工程或特徵選擇</strong>；<strong>用 BigQuery ML 產生預測</strong>；用 BigQuery 微調 Gemini</td></tr><tr><td>第 3 區：把原型放大成 ML 模型（約 21%）</td><td>3.1 選模型類型（ARIMA、DNN…）、選產品（BigQuery ML…）</td></tr><tr><td>第 5 區：自動化與編排 ML 管線（約 18%）</td><td>5.1 <strong>確保訓練和服務的前處理一致</strong>（TRANSFORM 子句就是這個）</td></tr></tbody></table></figure>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-04-exam-keywords.png" alt="PMLE 考試關鍵字：只會 SQL 資料在 BigQuery 想到 BigQuery ML、類別不平衡想到 auto_class_weights、時間序列想到 ARIMA_PLUS 和 SEQ 切分、訓練和預測前處理要一致想到 TRANSFORM、每筆預測的原因想到 ML.EXPLAIN_PREDICT、線上預測想到 Model Registry" class="wp-image-12843" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-04-exam-keywords.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-04-exam-keywords-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-04-exam-keywords-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml15-04-exam-keywords-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目出現的關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「資料分析師」「只會 SQL」「資料在 BigQuery」「最快上線」</td><td><strong>BigQuery ML</strong></td></tr><tr><td>「是或不是」「會不會流失」</td><td><code>LOGISTIC_REG</code>（或 <code>BOOSTED_TREE_CLASSIFIER</code>）</td></tr><tr><td>「預測金額」「連續數值」</td><td><code>LINEAR_REG</code></td></tr><tr><td>「未來 N 天銷量」「季節性」「假日」</td><td><code>ARIMA_PLUS</code>＋<code>ML.FORECAST</code>；資料切分用 <code>SEQ</code></td></tr><tr><td>「會員分幾群」「沒有標籤」</td><td><code>KMEANS</code></td></tr><tr><td>「推薦商品」「誰買過什麼」</td><td><code>MATRIX_FACTORIZATION</code>＋<code>ML.RECOMMEND</code></td></tr><tr><td>「正例很少」「不平衡」</td><td><code>auto_class_weights = TRUE</code></td></tr><tr><td>「訓練和預測的前處理要一致」「避免 skew」</td><td><strong>TRANSFORM 子句</strong></td></tr><tr><td>「每一筆預測的原因」</td><td><code>ML.EXPLAIN_PREDICT</code>；整體重要性用 <code>ML.GLOBAL_EXPLAIN</code></td></tr><tr><td>「調整門檻」「寧可多抓」</td><td><code>ML.PREDICT</code> 或 <code>ML.EVALUATE</code> 的 <code>threshold</code> 參數</td></tr><tr><td>「自動找最佳正則化」</td><td><code>num_trials</code>＋<code>HPARAM_RANGE</code>／<code>HPARAM_CANDIDATES</code></td></tr><tr><td>「用 SQL 但要 AutoML 的效果」</td><td><code>AUTOML_CLASSIFIER</code>／<code>AUTOML_REGRESSOR</code></td></tr><tr><td>「即時預測」「線上端點」</td><td><code>model_registry = 'VERTEX_AI'</code> 註冊到 Model Registry，部署端點</td></tr><tr><td>「控制建模型的費用」</td><td>內建模型先 dry run；減少試驗組數；注意 auto-ARIMA 的候選數</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">六個常見陷阱</h3>


<ol class="wp-block-list">
<li><strong>把會員編號當特徵丟進去</strong>：模型會記答案，評估分數虛高、上線沒用</li>

<li><strong>時間序列用預設的 AUTO_SPLIT</strong>：預設是隨機切，未來的資料會混進訓練集（第 4、8 篇），要用 <code>SEQ</code></li>

<li><strong>訓練前自己在外面做標準化，預測時忘了做</strong>：訓練和上線不一致。放進 TRANSFORM 就不會忘</li>

<li><strong>不平衡資料忘了 <code>auto_class_weights</code></strong>：模型全猜「不流失」也有 95% 準確率，召回率卻是 0</li>

<li><strong>以為 ML.PREDICT 是即時的</strong>：它是批次，線上預測要走 Model Registry 部署端點</li>

<li><strong>超參數調校的費用當成一次</strong>：是試驗組數的倍數</li>
</ol>



<h3 class="wp-block-heading">練習情境（自己出的練習，不是真實考題）</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">飲料店的分析師要用 BigQuery 裡的會員資料預測流失，流失會員只佔 5%。她希望寧可多抓一些可能流失的人，也不要漏掉。應該怎麼設定？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「BigQuery 裡」「分析師」→ <strong>BigQuery ML</strong>，<code>LOGISTIC_REG</code></li>

<li>「只佔 5%」→ <code>auto_class_weights = TRUE</code></li>

<li>「寧可多抓」→ 追<strong>召回率</strong>，<code>ML.PREDICT</code> 的 <code>threshold</code> 調低（例如 0.3），用 <code>ML.EVALUATE</code> 加同樣的 threshold 確認召回率</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">同一家店要預測每間分店未來兩週的日銷量，資料是過去三年的每日銷售表。分析師直接用預設設定訓練，發現評估分數好得不像真的。問題出在哪？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「好得不像真的」→ 懷疑<strong>資料洩漏</strong>（第 8 篇）</li>

<li>「時間序列」「預設設定」→ AUTO_SPLIT 是隨機切，未來的資料跑進訓練集</li>

<li>解法：用 <code>ARIMA_PLUS</code> 這類時間序列模型，或一般模型改 <code>data_split_method = 'SEQ'</code> 依時間切</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">模型上線後，工程師發現預測結果跟訓練時差很多。追查發現訓練前分析師用 Python 把客單價做了分桶，但上線時的 SQL 沒有分桶。怎麼避免？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「訓練和上線的前處理不一樣」→ <strong>訓練／服務偏差</strong>（第 20 篇）</li>

<li>解法：把分桶寫進 <code>CREATE MODEL</code> 的 <strong>TRANSFORM 子句</strong>（<code>ML.QUANTILE_BUCKETIZE</code>），<code>ML.PREDICT</code> 會自動用訓練時的切點</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">BigQuery ML 怎麼入門？</h3>



<p class="wp-block-paragraph">三句 SQL：CREATE MODEL 指定模型類型和標籤欄、用 SELECT 給訓練資料；ML.EVALUATE 看精確率、召回率、AUC 這些分數；ML.PREDICT 對一張表批次預測，輸出多兩欄 predicted_標籤名 和機率。資料全程留在 BigQuery，不用寫 Python。官方的邏輯迴歸教學用美國人口普查資料走一遍，照著做一個下午就能完成。</p>



<h3 class="wp-block-heading">BigQuery ML 支援哪些模型？</h3>



<p class="wp-block-paragraph">內建的有線性迴歸、邏輯迴歸、K-means 分群、矩陣分解（推薦）、PCA、ARIMA_PLUS 時間序列、貢獻分析；透過 Agent Platform 訓練的有 DNN、Wide &amp; Deep、自動編碼器、提升樹（XGBoost）、隨機森林、AutoML；還能匯入 TensorFlow、ONNX、XGBoost 模型，或遠端呼叫 Gemini。寫法都是 CREATE MODEL 加 model_type。</p>



<h3 class="wp-block-heading">BigQuery ML 會自動做前處理嗎？</h3>



<p class="wp-block-paragraph">會。訓練時數字欄自動標準化（提升樹和隨機森林除外），文字、布林、日期欄自動 One-hot 編碼，時間戳記自動拆成年月星期等，NULL 數字補平均值、NULL 類別當成額外的類別。想自己控制就用 TRANSFORM 子句，裡面可以用 ML.STANDARD_SCALER、ML.BUCKETIZE、ML.FEATURE_CROSS、ML.IMPUTER 等函數，而且預測時會自動套用同樣的轉換。</p>



<h3 class="wp-block-heading">BigQuery ML 的資料怎麼切訓練集和評估集？</h3>



<p class="wp-block-paragraph">預設 AUTO_SPLIT：少於 500 列全部訓練；500 到 50,000 列隨機切 20% 評估；超過 50,000 列固定抽 10,000 列評估；有開超參數調校則 80% 訓練、10% 評估、10% 測試。時間序列資料要改用 SEQ 依順序切，否則未來的資料會混進訓練集。也可以用 CUSTOM 自己標，或 NO_SPLIT 另外準備評估資料。</p>



<h3 class="wp-block-heading">BigQuery ML 怎麼處理類別不平衡？</h3>



<p class="wp-block-paragraph">邏輯迴歸模型在 CREATE MODEL 加 auto_class_weights = TRUE，它會依每個類別出現頻率的反比加權，少數類別的每一筆都算比較重。另外在 ML.PREDICT 和 ML.EVALUATE 用 threshold 參數調門檻，流失預測這種寧可多抓的情境把門檻調低。</p>



<h3 class="wp-block-heading">ML.PREDICT 和 ML.EXPLAIN_PREDICT 差在哪？</h3>



<p class="wp-block-paragraph">ML.PREDICT 只給預測結果和機率；ML.EXPLAIN_PREDICT 是它的加強版，每一列多回傳貢獻最大的幾個特徵和貢獻值，top_k_features 預設 5 個。想看模型整體哪些特徵最重要，訓練時開 enable_global_explain，再用 ML.GLOBAL_EXPLAIN 查。筆記裡的 BQML.PREDICT、BQML.EXPLAIN_PREDICT 是舊寫法，正確名稱是 ML.PREDICT、ML.EXPLAIN_PREDICT。</p>



<h3 class="wp-block-heading">BigQuery ML 可以調超參數嗎？</h3>



<p class="wp-block-paragraph">可以。CREATE MODEL 設 num_trials 指定試幾組，超參數用 HPARAM_RANGE 給範圍或 HPARAM_CANDIDATES 給候選值，跑完用 ML.TRIAL_INFO 看每組分數。支援線性／邏輯迴歸、K-means、矩陣分解、自動編碼器、提升樹、隨機森林、DNN、Wide &amp; Deep。費用是每一組試驗的總和。</p>



<h3 class="wp-block-heading">BigQuery ML 能做時間序列預測嗎？</h3>



<p class="wp-block-paragraph">能。model_type 設 ARIMA_PLUS，指定時間欄和數值欄，用 time_series_id_col 可以一次對很多個序列（例如每間分店）各建一個模型，holiday_region 加入假日效應。預測用 ML.FORECAST 給 horizon（預測幾期）和 confidence_level（預測區間）。它會自動處理異常值、季節性、假日。不想管模型可以用 AI.FORECAST 搭內建的 TimesFM。</p>



<h3 class="wp-block-heading">BigQuery ML 要多少錢？</h3>



<p class="wp-block-paragraph">按量計費時，評估和預測跟一般查詢同價，算在每月 1 TiB 免費額度內；建模型另外計價，依輸入查詢處理的資料量算，官方範例美國多區域是每 TiB 312.5 美元，2 GB 的表約 0.61 美元。超參數調校是試驗組數的倍數，auto-ARIMA 是候選模型數的倍數。用 Editions 的話 BigQuery ML 包在裡面，外部訓練的模型要用 ML_EXTERNAL 保留算力。</p>



<h3 class="wp-block-heading">BigQuery ML 的預測是即時的嗎？</h3>



<p class="wp-block-paragraph">ML.PREDICT 是批次預測，一次對整張表算完。要做即時的線上預測，在 CREATE MODEL 加 model_registry = &#8216;VERTEX_AI&#8217; 把模型註冊到 Agent Platform 的 Model Registry，不用匯出、不用自己做服務容器，就能部署成端點。</p>



<h3 class="wp-block-heading">不會寫 SQL 能用 BigQuery ML 嗎？</h3>



<p class="wp-block-paragraph">官方簡介提到 Google Cloud 主控台有圖形介面可以操作模型（預覽階段），也可以用 BigQuery DataFrames 寫 Python。但 BigQuery ML 的設計初衷就是給會 SQL 的人，SQL 是它最完整的介面，建議至少學會 SELECT、WHERE、GROUP BY 這幾個基本句型。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>三句 SQL</strong>：<code>CREATE MODEL</code>（model_type＋input_label_cols＋AS SELECT）→ <code>ML.EVALUATE</code>（precision、recall、roc_auc…）→ <code>ML.PREDICT</code>（predicted_標籤名＋機率，threshold 可調）</li>

<li><strong>自動前處理</strong>：數字標準化、類別 One-hot、NULL 補平均值或當額外類別；要自己控制用 <strong>TRANSFORM</strong>，預測時自動套用同樣轉換，解決訓練／服務偏差</li>

<li><strong>資料切分</strong>：AUTO_SPLIT 預設 &lt; 500 全訓練、500～50,000 切 20%、&gt; 50,000 抽 10,000 列；<strong>時間序列用 SEQ</strong></li>

<li><strong>不平衡</strong>：<code>auto_class_weights = TRUE</code>；<strong>超參數</strong>：<code>num_trials</code>＋<code>HPARAM_RANGE</code>／<code>HPARAM_CANDIDATES</code></li>

<li><strong>其他模型</strong>：<code>ARIMA_PLUS</code>＋<code>ML.FORECAST</code>（時間序列）、<code>KMEANS</code>（分群）、<code>MATRIX_FACTORIZATION</code>（推薦）、<code>BOOSTED_TREE</code>／<code>DNN</code>／<code>AUTOML</code>（在 Agent Platform 訓練）</li>

<li><strong>費用</strong>：評估、預測同一般查詢價；建模型依處理量另計；調校和 auto-ARIMA 是倍數</li>

<li><strong>線上預測</strong>：<code>model_registry = 'VERTEX_AI'</code> 註冊到 Model Registry 再部署端點；函數名稱是 <code>ML.PREDICT</code> 不是 BQML.PREDICT</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/20/types-of-machine-learning-supervised-unsupervised-reinforcement/">機器學習有哪幾種？監督式、非監督式、強化學習一次看懂</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/10/20/classification-vs-regression-mae-rmse/">分類和迴歸差在哪？一個例子搞懂，附 MAE、RMSE 計算</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">特徵、標籤、超參數是什麼？機器學習 5 個必懂名詞</a></li>

<li>第 4 篇：<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">訓練集、驗證集、測試集怎麼切？時間序列為什麼不能亂切</a></li>

<li>第 5 篇：<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">混淆矩陣是什麼？用快篩搞懂準確率、精確率、召回率、F1</a></li>

<li>第 6 篇：<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">ROC 曲線和 AUC 怎麼看？門檻怎麼調、AUC-PR 差在哪</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">過度擬合是什麼？正則化、Dropout、提前停止 3 招解決</a></li>

<li>第 8 篇：<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">資料洩漏是什麼？模型考試作弊的 3 種常見情況</a></li>

<li>第 9 篇：<a href="https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/">類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</a></li>

<li>第 10 篇：<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">資料前處理怎麼做？標準化、遺失值、高基數類別</a></li>

<li>第 11 篇：<a href="https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/">特徵工程是什麼？特徵交叉、詞嵌入、資料增強一次看懂</a></li>

<li>第 12 篇：<a href="https://dongdonggcp.com/2026/10/25/machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls/">機器學習的資料隱私怎麼保護？DLP、聯邦學習、VPC Service Controls</a></li>

<li>第 13 篇：<a href="https://dongdonggcp.com/2026/10/25/tfrecords-tf-data-prefetch-input-pipeline/">訓練資料讀太慢？TFRecords、tf.data 與 prefetch 加速</a></li>

<li>上一篇：第 14 篇：<a href="https://dongdonggcp.com/2026/10/25/vertex-ai-automl-bigquery-ml-custom-training-how-to-choose/">Vertex AI AutoML、BigQuery ML、自訂訓練怎麼選？</a></li>

<li>下一篇：第 16 篇：<a href="https://dongdonggcp.com/2026/10/25/vertex-ai-custom-training-containers-distributed-gpu-tpu/">Vertex AI 自訂訓練：容器、分散式訓練、GPU 與 TPU</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2024/11/23/what-is-bigquery-functions-advantages/">BigQuery 是什麼？功能、組成元件、特色和優勢完整介紹</a></li>

<li><a href="https://dongdonggcp.com/2025/07/04/is-bigquery-a-database-what-is-the-usage/">BigQuery 是資料庫嗎？跟資料庫差在哪</a></li>

<li><a href="https://dongdonggcp.com/2025/02/12/how-to-upload-data-to-bigquery/">把資料上傳到 BigQuery 的各種方法和步驟</a></li>

<li><a href="https://dongdonggcp.com/2026/03/27/bigquery-billing-guide/">BigQuery 計費方式完整介紹</a></li>

<li><a href="https://dongdonggcp.com/2026/03/19/bigquery-case-study-home-depot/">BigQuery 成功案例：Home Depot 導入 GCP 的案例解析</a></li>

<li><a href="https://dongdonggcp.com/2024/10/01/how-to-pass-gcp-data-engineer-certification-test/">GCP 證照 Data Engineer 怎麼考？</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">會 SQL 就能做機器學習，這是最低門檻的起點。如果你想有系統地從雲端基礎一路學到在 GCP 上動手做機器學習，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "BigQuery ML 怎麼入門？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "三句 SQL：CREATE MODEL 指定模型類型和標籤欄、用 SELECT 給訓練資料；ML.EVALUATE 看精確率、召回率、AUC 這些分數；ML.PREDICT 對一張表批次預測，輸出多兩欄 predicted_標籤名 和機率。資料全程留在 BigQuery，不用寫 Python。官方的邏輯迴歸教學用美國人口普查資料走一遍，照著做一個下午就能完成。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 支援哪些模型？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "內建的有線性迴歸、邏輯迴歸、K-means 分群、矩陣分解（推薦）、PCA、ARIMA_PLUS 時間序列、貢獻分析；透過 Agent Platform 訓練的有 DNN、Wide & Deep、自動編碼器、提升樹（XGBoost）、隨機森林、AutoML；還能匯入 TensorFlow、ONNX、XGBoost 模型，或遠端呼叫 Gemini。寫法都是 CREATE MODEL 加 model_type。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 會自動做前處理嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "會。訓練時數字欄自動標準化（提升樹和隨機森林除外），文字、布林、日期欄自動 One-hot 編碼，時間戳記自動拆成年月星期等，NULL 數字補平均值、NULL 類別當成額外的類別。想自己控制就用 TRANSFORM 子句，裡面可以用 ML.STANDARD_SCALER、ML.BUCKETIZE、ML.FEATURE_CROSS、ML.IMPUTER 等函數，而且預測時會自動套用同樣的轉換。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 的資料怎麼切訓練集和評估集？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "預設 AUTO_SPLIT：少於 500 列全部訓練；500 到 50,000 列隨機切 20% 評估；超過 50,000 列固定抽 10,000 列評估；有開超參數調校則 80% 訓練、10% 評估、10% 測試。時間序列資料要改用 SEQ 依順序切，否則未來的資料會混進訓練集。也可以用 CUSTOM 自己標，或 NO_SPLIT 另外準備評估資料。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 怎麼處理類別不平衡？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "邏輯迴歸模型在 CREATE MODEL 加 auto_class_weights = TRUE，它會依每個類別出現頻率的反比加權，少數類別的每一筆都算比較重。另外在 ML.PREDICT 和 ML.EVALUATE 用 threshold 參數調門檻，流失預測這種寧可多抓的情境把門檻調低。"
      }
    },
    {
      "@type": "Question",
      "name": "ML.PREDICT 和 ML.EXPLAIN_PREDICT 差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "ML.PREDICT 只給預測結果和機率；ML.EXPLAIN_PREDICT 是它的加強版，每一列多回傳貢獻最大的幾個特徵和貢獻值，top_k_features 預設 5 個。想看模型整體哪些特徵最重要，訓練時開 enable_global_explain，再用 ML.GLOBAL_EXPLAIN 查。筆記裡的 BQML.PREDICT、BQML.EXPLAIN_PREDICT 是舊寫法，正確名稱是 ML.PREDICT、ML.EXPLAIN_PREDICT。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 可以調超參數嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "可以。CREATE MODEL 設 num_trials 指定試幾組，超參數用 HPARAM_RANGE 給範圍或 HPARAM_CANDIDATES 給候選值，跑完用 ML.TRIAL_INFO 看每組分數。支援線性／邏輯迴歸、K-means、矩陣分解、自動編碼器、提升樹、隨機森林、DNN、Wide & Deep。費用是每一組試驗的總和。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 能做時間序列預測嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "能。model_type 設 ARIMA_PLUS，指定時間欄和數值欄，用 time_series_id_col 可以一次對很多個序列（例如每間分店）各建一個模型，holiday_region 加入假日效應。預測用 ML.FORECAST 給 horizon（預測幾期）和 confidence_level（預測區間）。它會自動處理異常值、季節性、假日。不想管模型可以用 AI.FORECAST 搭內建的 TimesFM。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 要多少錢？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "按量計費時，評估和預測跟一般查詢同價，算在每月 1 TiB 免費額度內；建模型另外計價，依輸入查詢處理的資料量算，官方範例美國多區域是每 TiB 312.5 美元，2 GB 的表約 0.61 美元。超參數調校是試驗組數的倍數，auto-ARIMA 是候選模型數的倍數。用 Editions 的話 BigQuery ML 包在裡面，外部訓練的模型要用 ML_EXTERNAL 保留算力。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 的預測是即時的嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "ML.PREDICT 是批次預測，一次對整張表算完。要做即時的線上預測，在 CREATE MODEL 加 model_registry = 'VERTEX_AI' 把模型註冊到 Agent Platform 的 Model Registry，不用匯出、不用自己做服務容器，就能部署成端點。"
      }
    },
    {
      "@type": "Question",
      "name": "不會寫 SQL 能用 BigQuery ML 嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "官方簡介提到 Google Cloud 主控台有圖形介面可以操作模型（預覽階段），也可以用 BigQuery DataFrames 寫 Python。但 BigQuery ML 的設計初衷就是給會 SQL 的人，SQL 是它最完整的介面，建議至少學會 SELECT、WHERE、GROUP BY 這幾個基本句型。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/10/25/bigquery-ml-tutorial-train-model-with-sql/">BigQuery ML 入門：只會 SQL 也能訓練模型</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/10/25/bigquery-ml-tutorial-train-model-with-sql/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Vertex AI AutoML、BigQuery ML、自訂訓練怎麼選？</title>
		<link>https://dongdonggcp.com/2026/10/25/vertex-ai-automl-bigquery-ml-custom-training-how-to-choose/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=vertex-ai-automl-bigquery-ml-custom-training-how-to-choose</link>
					<comments>https://dongdonggcp.com/2026/10/25/vertex-ai-automl-bigquery-ml-custom-training-how-to-choose/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 25 Oct 2026 05:41:30 +0000</pubDate>
				<category><![CDATA[AI 和機器學習]]></category>
		<category><![CDATA[證照考試]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[BigQuery]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[PMLE]]></category>
		<category><![CDATA[Vertex AI]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[生成式 AI]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=12839</guid>

					<description><![CDATA[<p>AutoML、BigQuery ML、自訂訓練怎麼選？用飲料店四個需求走一遍：資料在 BigQuery 用 SQL 訓練、照片檢查用 AutoML、PyTorch 模型走自訂訓練、文字分類改用 Gemini，附比較表與 PMLE 考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/10/25/vertex-ai-automl-bigquery-ml-custom-training-how-to-choose/">Vertex AI AutoML、BigQuery ML、自訂訓練怎麼選？</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>AutoML、BigQuery ML、自訂訓練怎麼選？會 SQL 選 BigQuery ML，免寫程式選 AutoML，要完全控制才選自訂訓練。</strong></p>



<p class="wp-block-paragraph">前面 13 篇把資料整理好、也知道怎麼餵進模型了。接下來的問題是：<strong>在 Google Cloud 上，到底要用哪個服務來訓練？</strong> 選項不只一個，選錯的代價是工程師寫了兩個月的東西，其實一行 SQL 就做得到；或是用了免寫程式的工具，做到一半發現它根本做不到你要的目標。</p>



<p class="wp-block-paragraph">一樣用有 2,000 間分店的連鎖飲料店當例子（教學假設），這次一口氣有四個需求：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>需求</th><th>資料長什麼樣</th></tr></thead><tbody><tr><td>A. 預測哪些會員下個月會流失</td><td>會員表、交易表，都已經在 BigQuery 裡</td></tr><tr><td>B. 封膜照片檢查（封膜有沒有歪）</td><td>200 萬張照片，放在 Cloud Storage</td></tr><tr><td>C. 客服留言自動分類（抱怨、詢問、稱讚）</td><td>文字</td></tr><tr><td>D. 自己設計的「猜你想點」推薦模型，研究團隊用 PyTorch 寫好了</td><td>程式碼＋交易表</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">這篇結束時，你會知道四個需求各該走哪條路，以及為什麼。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-01-spectrum.png" alt="Vertex AI AutoML、BigQuery ML、自訂訓練怎麼選：一條從全自動到全手工的光譜，預訓練 API 和 Gemini 像外送、AutoML 像料理包、BigQuery ML 像在倉庫旁邊開廚房、自訂訓練像自己從頭煮" class="wp-image-12835" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-01-spectrum.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-01-spectrum-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-01-spectrum-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-01-spectrum-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>選項比你想的多</strong>：Google 的<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/start/training-methods">訓練方式文件</a>列了五條路：AutoML、無伺服器訓練、訓練叢集、Ray、BigQuery ML。再加上「根本不用訓練」的 Gemini 和預訓練 API，有六七種。沒有判斷標準，每次都用自己最熟的那一種，常常是最貴或最慢的</li>

<li><strong>選錯很難回頭</strong>：用 AutoML 做到一半，發現要自訂損失函數，整個重來；用自訂訓練做一個 BigQuery ML 五分鐘能做完的事，白燒兩個月人力</li>

<li><strong>證照必考</strong>：PMLE 考試指南第 1.1 節直接寫「用 BigQuery ML 或 AutoML 開發模型」，第 3.1 節寫「<strong>選擇產品</strong>（例如 Agent Platform AutoML、BigQuery ML、Agent Platform Pipelines）」。這是整張考卷最常出現的判斷題型</li>

<li><strong>筆記裡的名稱很多已經過時</strong>：AutoML Tables、AutoML Natural Language、AutoML Vision Edge 這些名字舊題庫一直在用，現在有的改名、有的已經停用，這篇一併整理</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">先搞懂：一條從「全自動」到「全手工」的光譜</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph">Google Cloud 的訓練服務不是三個各自獨立的東西，而是<strong>一條光譜</strong>：一端是你什麼都不用做、Google 全包；另一端是你什麼都自己來、Google 只出機器。</p>



<p class="wp-block-paragraph">官方文件的說法：Agent Platform「提供一系列訓練方式，從全自動到全自訂」。</p>



<h3 class="wp-block-heading">比喻：晚餐怎麼解決</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>做法</th><th>對應的服務</th><th>你要做什麼</th><th>能吃到什麼</th></tr></thead><tbody><tr><td><strong>叫外送、買便利商店</strong></td><td>預訓練 API、Gemini、Model Garden 的現成模型</td><td>點餐</td><td>菜單上有的</td></tr><tr><td><strong>買料理包回家加熱</strong></td><td><strong>AutoML</strong></td><td>準備食材（資料）、按下開始</td><td>料理包有的那幾道</td></tr><tr><td><strong>倉庫旁邊就有廚房</strong></td><td><strong>BigQuery ML</strong></td><td>食材在哪就在哪煮，寫 SQL</td><td>廚房配備的那些菜色</td></tr><tr><td><strong>自己從頭煮</strong></td><td><strong>自訂訓練</strong></td><td>買菜、備料、掌廚，Google 只出爐子</td><td>什麼都行</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">越往下，自由度越高、要會的事也越多。</p>



<h3 class="wp-block-heading">來龍去脈：為什麼會變成一條光譜</h3>



<p class="wp-block-paragraph">早期 Google Cloud 的機器學習服務是一個一個分開的產品：AutoML Vision 管圖片、AutoML Tables 管表格、AutoML Natural Language 管文字、AI Platform 管自己寫的程式。2021 年 Google 把它們整合進 <strong>Vertex AI</strong>，變成同一個平台上的不同「訓練方式」。</p>



<p class="wp-block-paragraph"><strong>2026 年 4 月，Vertex AI 又改名為 Gemini Enterprise Agent Platform</strong>（簡稱 Agent Platform）。這篇標題保留 Vertex AI，是因為大家還是用這個名字在搜尋；內文用新名稱，文末有對照表。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">考題不會問你「AutoML 是什麼」，而是給一個情境，問你「應該用哪個」。沒有這條光譜在腦子裡，每題都要猜。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">第 0 步：先問「要不要自己訓練？」</h2>



<p class="wp-block-paragraph">在三個訓練選項之前，官方考試指南第 1.2 節還有一條更前面的路：<strong>用現成的</strong>。</p>


<ul class="wp-block-list">
<li><strong>預訓練 API</strong>：Google 已經訓練好、直接呼叫的服務。例如 Vision API 認圖片裡的文字、Document AI 讀發票、Translation API 翻譯。<strong>API</strong> 是「應用程式介面」，可以想成一個服務窗口，你把資料遞進去，它把結果遞出來。這些在<a href="https://dongdonggcp.com/2026/10/25/gcp-data-services-for-ml-bigquery-cloud-storage-feature-store-bigtable/">第 23 篇</a>會比較</li>

<li><strong>Gemini 和 Model Garden</strong>：Gemini 是 Google 的大型語言模型，Model Garden 是 Agent Platform 上的模型超市，有 Google 自家的和開源的模型可以直接用或微調</li>
</ul>



<p class="wp-block-paragraph">套回飲料店的需求 <strong>C（客服留言分類）</strong>：這題以前的標準答案是 AutoML Natural Language，<strong>現在不是了</strong>。Google 在 2024 年 6 月<a href="https://docs.cloud.google.com/vertex-ai/docs/core-release-notes">公告</a>，2024 年 9 月 15 日起 AutoML 的文字分類、實體擷取、情感分析不再開放訓練，既有模型到 2025 年 6 月 15 日停用，改用 <strong>Gemini 的提示詞和調校</strong>。</p>



<p class="wp-block-paragraph">也就是說，留言分類這種事，現在先試「把留言丟給 Gemini，用提示詞請它分類」，不夠準再做調校。這是舊題庫和新考試差最多的地方之一。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">1. BigQuery ML：資料在哪，就在哪訓練</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>BigQuery ML</strong> 讓你用 <strong>SQL</strong> 在 BigQuery 裡面直接建模型、訓練、預測，資料不用搬出去。</p>



<p class="wp-block-paragraph">先補兩個名詞：</p>


<ul class="wp-block-list">
<li><strong>BigQuery</strong> 是 Google 的資料倉儲，專門存大量表格資料、用 SQL 查詢，站上有一篇<a href="https://dongdonggcp.com/2025/07/04/is-bigquery-a-database-what-is-the-usage/">BigQuery 跟資料庫差在哪</a></li>

<li><strong>SQL</strong> 是查詢表格資料的語言，資料分析師幾乎都會，像「把去年買超過 10 次的會員列出來」這種句子</li>
</ul>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">倉庫旁邊直接蓋一間廚房。食材（資料）本來就堆在這裡，不用叫貨車載去別的地方煮，煮完的菜也直接放回倉庫。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">官方<a href="https://docs.cloud.google.com/bigquery/docs/bqml-introduction">簡介</a>講得很直白：以前做機器學習要會程式、會 ML 框架，這把一間公司裡「最懂資料的人」（資料分析師）排除在外。BigQuery ML 的目的是讓會 SQL 的人也能做，而且<strong>把 ML 帶到資料旁邊</strong>，不用把幾 TB 的資料搬去 Python 環境。</p>



<h3 class="wp-block-heading">能做哪些模型</h3>



<p class="wp-block-paragraph">官方文件把 BigQuery ML 的模型分成四類：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>類別</th><th>模型</th><th>白話</th></tr></thead><tbody><tr><td><strong>BigQuery 內建訓練</strong></td><td>線性迴歸、邏輯迴歸（第 2 篇）、K-means 分群、矩陣分解（推薦）、PCA（降維）、ARIMA_PLUS 時間序列預測、貢獻分析</td><td>最常用的那幾種，BigQuery 自己算</td></tr><tr><td><strong>交給 Agent Platform 訓練</strong>（寫法還是 SQL）</td><td>深度神經網路（DNN）、Wide &amp; Deep、自動編碼器、提升樹（XGBoost）、隨機森林、<strong>AutoML</strong></td><td>SQL 下指令，背後用 Agent Platform 的資源算</td></tr><tr><td><strong>匯入外面訓練好的模型</strong></td><td>TensorFlow、TensorFlow Lite、ONNX（PyTorch、scikit-learn 可轉成這個格式）、XGBoost</td><td>別處練好的模型，拿進 BigQuery 做預測</td></tr><tr><td><strong>遠端模型</strong></td><td>已部署在 Agent Platform 的模型、Gemini 這類大型語言模型</td><td>SQL 裡直接呼叫，例如用 AI.GENERATE 讓 Gemini 幫每一列產生文字</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">時間序列預測還多了一個選項：不想自己管模型，可以用 <code>AI.FORECAST</code> 函數搭配內建的 <strong>TimesFM</strong> 模型（預覽階段）直接預測。</p>



<h3 class="wp-block-heading">長什麼樣：三句 SQL</h3>



<p class="wp-block-paragraph">需求 <strong>A（會員流失預測）</strong>，資料已經在 BigQuery，就是 BigQuery ML 的主場：</p>



<pre class="wp-block-code"><code>-- 1. 訓練：用邏輯迴歸預測 churned 欄位
CREATE MODEL `drink.churn_model`
OPTIONS (model_type = 'LOGISTIC_REG', input_label_cols = ['churned']) AS
SELECT visits_90d, avg_spend, days_since_last, member_months, churned
FROM `drink.member_features`;

-- 2. 評估：看準確率、精確率、召回率、AUC
SELECT * FROM ML.EVALUATE(MODEL `drink.churn_model`);

-- 3. 預測：對所有現有會員算流失機率
SELECT member_id, predicted_churned, predicted_churned_probs
FROM ML.PREDICT(MODEL `drink.churn_model`, TABLE `drink.member_features_today`);</code></pre>



<p class="wp-block-paragraph">第 5、6 篇講的混淆矩陣、ROC 曲線，BigQuery ML 也有對應的函數：<code>ML.CONFUSION_MATRIX</code>、<code>ML.ROC_CURVE</code>。要知道「每個特徵對這筆預測的貢獻」，用 <code>ML.EXPLAIN_PREDICT</code>（<a href="https://dongdonggcp.com/2026/10/25/explainable-ai-shapley-integrated-gradients-xrai/">第 21 篇</a>講可解釋 AI 時會再提）。</p>



<p class="wp-block-paragraph"><strong>筆記裡寫的「BQML.PREDICT」「BQML.EXPLAIN_PREDICT」</strong>，正確的函數名稱是 <code>ML.PREDICT</code> 和 <code>ML.EXPLAIN_PREDICT</code>，BQML 只是產品的簡稱。</p>



<h3 class="wp-block-heading">它的限制</h3>



<p class="wp-block-paragraph">官方比較表裡 BigQuery ML 有兩個「有限制」：</p>


<ul class="wp-block-list">
<li><strong>目標有限制</strong>：只能做它支援的那些模型，想自訂神經網路架構或損失函數做不到</li>

<li><strong>資料量有配額</strong>：每個專案有 BigQuery ML 的配額上限</li>
</ul>



<p class="wp-block-paragraph">另外它的預測主要是<strong>批次</strong>（一次算一整張表）。要做即時的線上預測，可以把模型註冊到 Agent Platform 的 Model Registry 再部署成端點，<a href="https://dongdonggcp.com/2026/10/25/model-deployment-online-vs-batch-prediction-traffic-split/">第 17 篇</a>會講。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">考題只要出現「資料分析師」「只會 SQL」「資料已經在 BigQuery」「不想搬資料」，答案幾乎都是 BigQuery ML。這是 PMLE 第 1.1 節的核心。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">2. AutoML：給資料，Google 幫你選模型、調參數</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>AutoML</strong>（自動化機器學習）：你只要準備好標了答案的資料，它自動幫你做資料準備、挑模型、調超參數、部署。官方<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/training-overview">訓練總覽</a>的說法是「<strong>免寫程式</strong>（code-free）建立模型」。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">料理包。食材你準備（資料要自己收集、標好），但火候、調味、步驟全部包好了，加熱就能吃。好處是不用會煮；限制是只有料理包清單上的那幾道菜。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">AutoML 原本是一串獨立產品，筆記裡列的 AutoML Tables、AutoML Natural Language、AutoML Vision、AutoML Vision Edge、AutoML Forecasting 就是那個時代的名字。它們先被整合進 Vertex AI，現在叫 <strong>AutoML on Gemini Enterprise Agent Platform</strong>。</p>



<p class="wp-block-paragraph">整合之後有兩個大變化：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>舊產品</th><th>現在</th></tr></thead><tbody><tr><td>AutoML Tables</td><td>AutoML <strong>表格</strong>（分類、迴歸）＋ <strong>Tabular Workflows</strong>（可控版，下面講）</td></tr><tr><td>AutoML Forecasting</td><td>AutoML 表格的<strong>預測</strong>目標，另有 Tabular Workflow for Forecasting、BigQuery ML ARIMA_PLUS</td></tr><tr><td>AutoML Vision</td><td>AutoML <strong>影像</strong>（分類、物件偵測）</td></tr><tr><td>AutoML Vision Edge</td><td>AutoML 影像的 <strong>Edge 模型</strong>，訓練完可匯出到裝置上跑</td></tr><tr><td>AutoML Natural Language</td><td><strong>已停用</strong>（2024 年 9 月停止訓練、2025 年 6 月停用），改用 Gemini 提示詞和調校</td></tr><tr><td>AutoML Video</td><td><strong>已停用</strong>（<a href="https://docs.cloud.google.com/vertex-ai/docs/deprecations">淘汰清單</a>：2024 年 7 月淘汰、2025 年 7 月停用），改用 Gemini 的影片調校</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">現在能做什麼</h3>



<p class="wp-block-paragraph">官方訓練總覽列出的 AutoML 支援範圍：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>資料類型</th><th>能做的目標</th></tr></thead><tbody><tr><td><strong>影像</strong></td><td>分類、物件偵測</td></tr><tr><td><strong>表格</strong></td><td>分類、迴歸、預測（時間序列）</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">表格的四種目標，<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/tabular-data/overview">官方表格資料文件</a>用零售商的例子說明：</p>


<ul class="wp-block-list">
<li><strong>二元分類</strong>：是或不是（會不會買訂閱）</li>

<li><strong>多類別分類</strong>：三種以上分一類（客戶屬於哪個人物誌）</li>

<li><strong>迴歸</strong>：一個數字（下個月會花多少錢）</li>

<li><strong>預測</strong>：一串數字（未來 3 個月每天的需求量）</li>
</ul>



<h3 class="wp-block-heading">要多少資料：算一次</h3>



<p class="wp-block-paragraph">AutoML 不用寫程式，但<strong>資料量有最低要求</strong>。<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/beginner/beginners-guide">官方初學者指南</a>給了經驗法則：</p>



<p class="wp-block-paragraph"><strong>影像</strong>：每個類別<strong>至少 100 張</strong>，目標 <strong>1,000 張</strong>；最少的類別要有最多類別的 10% 以上。</p>



<pre class="wp-block-code"><code>需求 B 封膜檢查，2 個類別（正常、有問題）
最低：100 × 2 = 200 張
建議：1,000 × 2 = 2,000 張
手上有 200 萬張 → 遠遠超過，沒問題
但如果「有問題」的照片只有 500 張、「正常」的有 199 萬張
500 ÷ 1,990,000 ≈ 0.03%，遠低於 10% → 要處理類別不平衡（第 9 篇）</code></pre>



<p class="wp-block-paragraph"><strong>表格</strong>（列數 × 特徵數的倍數）：</p>


<ul class="wp-block-list">
<li>分類：<strong>50 × 特徵數</strong></li>

<li>迴歸：<strong>200 × 特徵數</strong></li>

<li>預測：<strong>5,000 × 特徵數</strong>，而且時間序列識別欄至少要有 10 個不同的值</li>
</ul>



<pre class="wp-block-code"><code>需求 A 會員流失，用 20 個特徵做分類
最低列數 = 50 × 20 = 1,000 列
50 萬名會員 → 綽綽有餘</code></pre>



<p class="wp-block-paragraph"><strong>數字怎麼看</strong>：分類要的資料最少，迴歸要 4 倍，預測要 100 倍。因為預測要學的是「一整段時間的走勢」，資料不夠它看不出季節性。</p>



<h3 class="wp-block-heading">訓練預算：節點小時</h3>



<p class="wp-block-paragraph">AutoML 影像訓練要先設<strong>預算</strong>，單位是<strong>節點小時</strong>（node hour）：一台訓練機器跑一小時算一個節點小時。<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/image-data/classification/train-model">官方影像訓練文件</a>寫的是「毫節點小時」（milli node hour，千分之一節點小時），雲端模型的範圍是 <strong>8,000 到 800,000 毫節點小時</strong>：</p>



<pre class="wp-block-code"><code>8,000 毫節點小時 = 8 節點小時（最低）
800,000 毫節點小時 = 800 節點小時（最高）</code></pre>



<p class="wp-block-paragraph">實際花費「等於或低於」這個預算，訓練提早收斂就提早停。這是 AutoML 少數能控制的東西之一：官方比較表說你能控制的只有「訓練小時預算」和「提前停止」。</p>



<h3 class="wp-block-heading">Edge 模型：訓練完帶走</h3>



<p class="wp-block-paragraph">需求 B 如果要在每間分店的機器上即時判斷、不連網路，AutoML 影像可以訓練 <strong>Edge 模型</strong>，然後<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/export/export-edge-model">匯出</a>成：</p>


<ul class="wp-block-list">
<li><strong>TF Lite</strong>：在手機、小型裝置上跑</li>

<li><strong>Edge TPU TF Lite</strong>：給 Google 的 Edge TPU 晶片</li>

<li><strong>Core ML</strong>：iPhone、Mac</li>

<li><strong>TensorFlow.js</strong>：在瀏覽器裡跑</li>

<li><strong>容器</strong>：TF SavedModel 包成 Docker 容器</li>
</ul>



<p class="wp-block-paragraph">官方特別提醒：<strong>Edge 模型不能在 Agent Platform 上提供預測</strong>，一定要部署到外部裝置。舊題庫的「AutoML Vision Edge」就是這個，現在的關鍵字是「Edge 模型」「匯出 TF Lite」。</p>



<h3 class="wp-block-heading">想多控制一點：Tabular Workflows</h3>



<p class="wp-block-paragraph">表格資料還有一個「進階版 AutoML」叫 <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/tabular-data/tabular-workflows/overview">Tabular Workflows</a>。它把 AutoML 拆成一條管線（資料切分、特徵工程、架構搜尋、訓練、集成、蒸餾），<strong>每一步都能自己決定要控制還是交給它</strong>。官方列的好處：支援多 TB、最多 1,000 欄的資料集，可以跳過架構搜尋來省時間，可以自己選硬體。</p>



<p class="wp-block-paragraph">這是 AutoML 和自訂訓練之間的中間地帶，考題出現「想用 AutoML 但資料很大、想控制某些步驟」就是它。</p>



<h3 class="wp-block-heading">它的限制</h3>



<p class="wp-block-paragraph">官方比較表裡 AutoML 的三個「有限制」：</p>


<ul class="wp-block-list">
<li><strong>目標有限制</strong>：只能做它預先定義的那幾種</li>

<li><strong>超參數不能自己調</strong>：它有自動調，但你改不了數值</li>

<li><strong>資料量有限制</strong>：依資料類型不同</li>
</ul>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">AutoML 是「快速原型」的工具，官方文件說可以用它「在投入開發前快速探索新資料集，例如找出哪些特徵最有用」。考題看到「最少的工程投入」「團隊沒有 ML 專業」「快速驗證」，就是它。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">3. 自訂訓練：你寫程式，Google 出機器</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>自訂訓練</strong>（custom training）：你自己寫訓練程式（用任何框架），打包成容器，交給 Agent Platform 跑。它負責開機器、裝 GPU、跑完關機。</p>



<p class="wp-block-paragraph"><strong>容器</strong>（container）是把程式和它需要的所有東西打包成一個標準箱子，到哪台機器都能跑，站上有一篇<a href="https://dongdonggcp.com/2026/07/29/what-is-container-technology-docker-guide/">容器是什麼</a>。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">自己從頭煮。想做什麼菜都行、想怎麼調味都行，但你要會煮。Google 只負責爐子（機器、GPU、TPU），而且用完才收錢。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">AutoML 和 BigQuery ML 再方便，總有做不到的事：研究團隊設計的新架構、特殊的損失函數、要用 PyTorch、要幾十張 GPU 一起訓練。官方文件的說法：「如果 AutoML 不符合需求，你可以提供自己的訓練程式碼，在 Agent Platform 的代管基礎設施上執行，對模型架構和訓練邏輯有<strong>完全的控制</strong>。」</p>



<p class="wp-block-paragraph">需求 <strong>D（研究團隊的 PyTorch 推薦模型）</strong>就是典型：程式已經寫好了，只缺機器。</p>



<h3 class="wp-block-heading">兩種跑法</h3>



<p class="wp-block-paragraph">官方訓練總覽把自訂訓練分成兩種模式：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th><strong>無伺服器訓練</strong>（Serverless Training）</th><th><strong>訓練叢集</strong>（Training Clusters）</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>自己指定機型、GPU</td><td>可保留 A100、H100 這類高階 GPU</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>無伺服器</strong>（serverless）不是沒有伺服器，是「伺服器你看不到、不用管」。</p>



<p class="wp-block-paragraph">另外還有 <strong>Ray on Agent Platform</strong>：用開源的 Ray 框架做分散式運算，適合本來就用 Ray 的團隊。</p>



<p class="wp-block-paragraph">自訂訓練的細節（預建容器、分散式訓練、GPU 和 TPU 怎麼選）<a href="https://dongdonggcp.com/2026/10/25/vertex-ai-custom-training-containers-distributed-gpu-tpu/">第 16 篇</a>專門講。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">考題看到「自訂損失函數」「PyTorch」「研究團隊已經寫好程式」「需要完全控制」「分散式訓練」，就是自訂訓練。這是 PMLE 第 3.2 節的主軸。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">四個問題，決定走哪條路</h2>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-02-decision.png" alt="怎麼選的決策流程：先問有沒有現成模型能做，再問資料是不是在 BigQuery 的表格而且團隊會 SQL，再問是不是影像或表格而且不想寫程式，最後才是需要自訂架構、損失函數或框架就走自訂訓練" class="wp-image-12836" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-02-decision.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-02-decision-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-02-decision-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-02-decision-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>問題</th><th>答「是」就走</th><th>飲料店的例子</th></tr></thead><tbody><tr><td><strong>Q1. 有現成的 API 或 Gemini 能直接做嗎？</strong></td><td>預訓練 API、Gemini、Model Garden，<strong>不用訓練</strong></td><td>需求 C 客服留言分類 → Gemini 提示詞</td></tr><tr><td><strong>Q2. 資料是表格、已經在 BigQuery、團隊會 SQL？</strong></td><td><strong>BigQuery ML</strong></td><td>需求 A 會員流失</td></tr><tr><td><strong>Q3. 資料是影像或表格、目標在 AutoML 清單內、不想寫程式？</strong></td><td><strong>AutoML</strong></td><td>需求 B 封膜檢查</td></tr><tr><td><strong>Q4. 需要自訂架構、損失函數、特定框架、分散式？</strong></td><td><strong>自訂訓練</strong></td><td>需求 D PyTorch 推薦模型</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">兩個補充：</p>


<ul class="wp-block-list">
<li><strong>問題有順序</strong>：Q1 排第一，是因為新版考試指南把「用現成模型」放在第 1 區。能不訓練就不訓練，最省</li>

<li><strong>中間地帶很多</strong>：BigQuery ML 裡可以用 SQL 叫 AutoML（<code>model_type = 'AUTOML_CLASSIFIER'</code>），也可以匯入 TensorFlow 模型；Tabular Workflows 是可控的 AutoML。考題有時會出這種「混搭」</li>
</ul>



<h3 class="wp-block-heading">官方比較表（翻成白話）</h3>



<p class="wp-block-paragraph">Google 的訓練方式文件有一張比較表，整理成這樣：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>AutoML</th><th>BigQuery ML</th><th>自訂訓練（無伺服器）</th></tr></thead><tbody><tr><td>需要 ML 專業？</td><td>不用</td><td>不用</td><td>要，自己寫訓練程式、處理資料</td></tr><tr><td>需要寫程式？</td><td>不用</td><td>要（SQL）</td><td>要（Python 等）</td></tr><tr><td>訓練時間</td><td>短，不用開發</td><td>短，用 BigQuery 的算力</td><td>長，要寫程式＋等機器</td></tr><tr><td>目標有限制？</td><td>有，只能選預定義的</td><td>有</td><td>沒有</td></tr><tr><td>能自己調超參數？</td><td>不能</td><td>能</td><td>能</td></tr><tr><td>能控制訓練環境？</td><td>很少（預算、提前停止）</td><td>不能</td><td>能（機型、硬碟、容器）</td></tr><tr><td>資料量限制？</td><td>有</td><td>有配額</td><td>沒有</td></tr></tbody></table></figure>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-03-compare.png" alt="AutoML、BigQuery ML、自訂訓練三種方式比較表：要不要 ML 專業、要不要寫程式、訓練時間、目標限制、超參數、環境控制、資料量限制" class="wp-image-12837" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-03-compare.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-03-compare-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-03-compare-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-03-compare-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">在 GCP 上怎麼做</h2>



<h3 class="wp-block-heading">1. BigQuery ML 的流程</h3>


<ol class="wp-block-list">
<li>資料整理成一張表（特徵欄＋標籤欄），第 10、11 篇的前處理和特徵工程可以直接用 SQL 或 <code>TRANSFORM</code> 子句做</li>

<li><code>CREATE MODEL</code> 訓練，<code>ML.EVALUATE</code> 看分數，<code>ML.PREDICT</code> 批次預測</li>

<li>要線上預測，把模型註冊到 Agent Platform <strong>Model Registry</strong>，部署成端點（第 17 篇）</li>
</ol>



<p class="wp-block-paragraph">收費是 BigQuery 的算力費用；呼叫遠端模型（例如 Gemini）另外算 Agent Platform 的費用。站上有一篇 <a href="https://dongdonggcp.com/2026/03/27/bigquery-billing-guide/">BigQuery 計費方式</a>。</p>



<h3 class="wp-block-heading">2. AutoML 的流程</h3>


<ol class="wp-block-list">
<li>在 Agent Platform 建<strong>資料集</strong>：影像從 Cloud Storage 匯入（CSV 或 JSON Lines 列出檔案和標籤），沒標的可以在主控台上標；表格從 BigQuery 或 CSV 匯入</li>

<li>選目標（分類、迴歸、預測、物件偵測）、設訓練預算、按開始</li>

<li>看評估指標（第 5、6 篇那些），部署成端點，或匯出 Edge 模型</li>
</ol>



<h3 class="wp-block-heading">3. 自訂訓練的流程</h3>


<ol class="wp-block-list">
<li>寫訓練程式，用預建容器（支援 PyTorch、TensorFlow、scikit-learn、XGBoost）或自己做容器</li>

<li>建 <strong>CustomJob</strong>：指定機型、GPU、資料路徑（第 13 篇講的 <code>/gcs/</code>）</li>

<li>模型存到 Cloud Storage，註冊到 Model Registry</li>
</ol>



<p class="wp-block-paragraph">第 16 篇會把每一步展開。</p>



<h3 class="wp-block-heading">4. 改名對照</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>舊名稱（筆記、舊題庫）</th><th>現在的名稱</th></tr></thead><tbody><tr><td>Vertex AI</td><td>Gemini Enterprise Agent Platform（Agent Platform）</td></tr><tr><td>Vertex AI AutoML</td><td>AutoML on Gemini Enterprise Agent Platform</td></tr><tr><td>AutoML Tables、Vision、Natural Language（獨立產品）</td><td>整合進 AutoML；文字已停用改 Gemini</td></tr><tr><td>Vertex AI Training、custom training</td><td>Gemini Enterprise Agent Platform <strong>Managed Training</strong>；無伺服器的叫 <strong>Serverless Training</strong></td></tr><tr><td>Vertex AI Model Registry</td><td>Gemini Enterprise Agent Platform Model Registry</td></tr><tr><td>BigQuery ML、BQML</td><td>名稱沒變</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">考試會怎麼考</h2>



<p class="wp-block-paragraph">Google Cloud <strong>Professional Machine Learning Engineer（PMLE，專業機器學習工程師）</strong> 證照，2026 年 6 月 1 日起的<a href="https://services.google.com/fh/files/misc/professional_machine_learning_engineer_exam_guide_english_new.pdf">官方考試指南</a>裡，這篇的內容對應到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考試區塊</th><th>跟這篇有關的項目</th></tr></thead><tbody><tr><td>第 1 區：設計低程式碼 AI 方案（約 13%）</td><td>1.1 <strong>用 BigQuery ML 或 Agent Platform AutoML 開發模型</strong>（分類、迴歸、預測、分群）；用 BigQuery ML 做特徵工程、產生預測；用 AutoML 訓練。1.2 用 <strong>Google Cloud AI API 或基礎模型</strong>建方案：從 Model Garden 選模型、用產業 API（Document AI、Vision API、Translate API）</td></tr><tr><td>第 3 區：把原型放大成 ML 模型（約 21%）</td><td>3.1 依成本、複雜度、延遲、擴展性建模型：<strong>選產品</strong>（Agent Platform AutoML、BigQuery ML、Agent Platform Pipelines）。3.2 用不同 SDK 訓練（Agent Platform 自訂訓練、GKE 上的 Kubeflow、AutoML、Tabular Workflows）</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">注意 3.2 直接點名 <strong>Tabular Workflows</strong>，新版考試把它當成一個獨立選項。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-04-exam-keywords.png" alt="PMLE 考試關鍵字：只會 SQL 或資料在 BigQuery 想到 BigQuery ML、沒有 ML 專業要最少程式想到 AutoML、自訂損失函數或 PyTorch 想到自訂訓練、文字分類想到 Gemini 不是 AutoML、裝置上離線判斷想到 Edge 模型匯出 TF Lite、表格資料多 TB 想控制步驟想到 Tabular Workflows" class="wp-image-12838" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-04-exam-keywords.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-04-exam-keywords-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-04-exam-keywords-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml14-04-exam-keywords-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目出現的關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「資料分析師」「只會 SQL」「資料已在 BigQuery」「不想搬資料」</td><td><strong>BigQuery ML</strong></td></tr><tr><td>「時間序列預測」＋「SQL」</td><td>BigQuery ML <strong>ARIMA_PLUS</strong>（或 AI.FORECAST 搭 TimesFM）</td></tr><tr><td>「沒有 ML 專業」「最少的程式」「快速原型」「找出重要特徵」</td><td><strong>AutoML</strong></td></tr><tr><td>「圖片分類」「物件偵測」「不想寫程式」</td><td><strong>AutoML 影像</strong></td></tr><tr><td>「裝置上判斷」「離線」「低延遲」「手機」</td><td>AutoML <strong>Edge 模型</strong>，匯出 <strong>TF Lite</strong></td></tr><tr><td>「文字分類」「情感分析」「實體擷取」</td><td><strong>Gemini</strong> 提示詞或調校（AutoML 文字已停用）</td></tr><tr><td>「OCR」「翻譯」「發票辨識」</td><td><strong>預訓練 API</strong>，不用訓練</td></tr><tr><td>「自訂損失函數」「自訂架構」「PyTorch」「研究團隊寫好程式」「完全控制」</td><td><strong>自訂訓練</strong></td></tr><tr><td>「幾十張 GPU」「分散式」「保證有機器」「H100」</td><td>自訂訓練的<strong>訓練叢集</strong></td></tr><tr><td>「表格資料多 TB」「1,000 欄」「想控制 AutoML 的某些步驟」</td><td><strong>Tabular Workflows</strong></td></tr><tr><td>「用 SQL 但想要 AutoML 的效果」</td><td>BigQuery ML 的 <strong>AUTOML_CLASSIFIER／REGRESSOR</strong></td></tr></tbody></table></figure>



<h3 class="wp-block-heading">六個常見陷阱</h3>


<ol class="wp-block-list">
<li><strong>文字分類選 AutoML Natural Language</strong>：2025 年 6 月已停用，現在是 Gemini</li>

<li><strong>只會 SQL 的團隊選自訂訓練</strong>：題目強調團隊能力時，答案跟著能力走</li>

<li><strong>需要自訂損失函數還選 AutoML</strong>：AutoML 連超參數都不能改，更別說損失函數</li>

<li><strong>Edge 模型拿去 Agent Platform 部署</strong>：官方明寫不行，Edge 模型只能部署到外部裝置</li>

<li><strong>資料量不夠硬用 AutoML</strong>：影像每類至少 100 張，表格分類至少 50 × 特徵數列</li>

<li><strong>直接跳到訓練，沒先問有沒有現成的</strong>：新版考試第 1.2 節就是在考「能不能不訓練」</li>
</ol>



<h3 class="wp-block-heading">練習情境（自己出的練習，不是真實考題）</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">飲料店的資料團隊有三位資料分析師，都很熟 SQL，沒有人寫過 Python。會員和交易資料都在 BigQuery。老闆要在兩週內看到「哪些會員會流失」的預測結果。應該怎麼做？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「只會 SQL」「資料在 BigQuery」「兩週」→ <strong>BigQuery ML</strong></li>

<li>流失是「會或不會」→ 二元分類，<code>LOGISTIC_REG</code>（或 <code>BOOSTED_TREE_CLASSIFIER</code>）</li>

<li>用 <code>ML.EVALUATE</code> 看召回率（第 5 篇），<code>ML.PREDICT</code> 批次算出名單</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">同一家店想用封膜照片訓練瑕疵偵測模型，團隊沒有電腦視覺經驗，但有 5 萬張標好的照片。模型要裝在每間分店的機器上，沒有網路也要能判斷。應該怎麼做？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「沒有電腦視覺經驗」「照片已標好」→ <strong>AutoML 影像</strong></li>

<li>「裝在分店機器上」「沒有網路」→ 訓練 <strong>Edge 模型</strong>，匯出 <strong>TF Lite</strong>（或容器）</li>

<li>5 萬張 ÷ 2 類 = 每類 2.5 萬張，遠超過建議的 1,000 張</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">研究團隊用 PyTorch 設計了一個新的推薦模型，有自訂的損失函數，需要 8 張 GPU 平行訓練，而且這是每週都要重訓的正式工作，不能排隊等機器。應該怎麼做？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「PyTorch」「自訂損失函數」→ <strong>自訂訓練</strong></li>

<li>「8 張 GPU」→ 分散式訓練（第 16 篇）</li>

<li>「正式工作、不能排隊」→ <strong>訓練叢集</strong>（保留機器），不是無伺服器訓練</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">Vertex AI AutoML、BigQuery ML、自訂訓練怎麼選？</h3>



<p class="wp-block-paragraph">先問有沒有現成的 API 或 Gemini 能直接做，有就不用訓練。要訓練的話：資料是表格、已經在 BigQuery、團隊會 SQL，用 BigQuery ML；資料是影像或表格、目標在 AutoML 支援清單內、不想寫程式，用 AutoML；需要自訂模型架構、損失函數、特定框架或分散式訓練，用自訂訓練。官方的訓練方式文件有一張比較表，差別在需不需要 ML 專業、要不要寫程式、目標有沒有限制、能不能調超參數。</p>



<h3 class="wp-block-heading">BigQuery ML 是什麼？能做哪些模型？</h3>



<p class="wp-block-paragraph">BigQuery ML 讓你用 SQL 在 BigQuery 裡直接訓練和使用模型，資料不用搬出去。內建的有線性迴歸、邏輯迴歸、K-means、矩陣分解、PCA、ARIMA_PLUS 時間序列；透過 Agent Platform 訓練的有 DNN、Wide &amp; Deep、提升樹、隨機森林、AutoML；也能匯入 TensorFlow、ONNX、XGBoost 模型，或遠端呼叫 Gemini。預測用 ML.PREDICT，評估用 ML.EVALUATE，解釋用 ML.EXPLAIN_PREDICT。</p>



<h3 class="wp-block-heading">AutoML 是什麼？現在支援哪些資料？</h3>



<p class="wp-block-paragraph">AutoML 是免寫程式的機器學習：你提供標好的資料，它自動做資料準備、選模型、調超參數、部署。目前官方訓練總覽列的支援範圍是影像（分類、物件偵測）和表格（分類、迴歸、預測）兩種資料類型。舊題庫的 AutoML Tables、AutoML Vision 都已整合進來，AutoML Natural Language 和 AutoML Video 都已停用，改用 Gemini。</p>



<h3 class="wp-block-heading">AutoML Natural Language 還能用嗎？</h3>



<p class="wp-block-paragraph">不能。Google 在 2024 年 6 月公告，2024 年 9 月 15 日起 AutoML 的文字分類、實體擷取、情感分析不再開放訓練，既有模型到 2025 年 6 月 15 日停用，改用 Gemini 的提示詞和模型調校。舊題庫看到文字分類選 AutoML Natural Language，現在的答案是 Gemini。</p>



<h3 class="wp-block-heading">AutoML Vision Edge 是什麼？</h3>



<p class="wp-block-paragraph">舊名稱，現在叫 AutoML 影像的 Edge 模型。訓練時選 Edge 類型，訓練完可以匯出成 TF Lite、Edge TPU TF Lite、Core ML、TensorFlow.js 或容器，部署到手機、工廠機台這類裝置上，離線也能判斷。官方特別提醒 Edge 模型不能在 Agent Platform 上提供預測，一定要部署到外部裝置。</p>



<h3 class="wp-block-heading">AutoML 要多少資料？</h3>



<p class="wp-block-paragraph">官方初學者指南的經驗法則：影像每個類別至少 100 張，目標 1,000 張，最少的類別要有最多類別的 10% 以上；表格分類至少 50 乘以特徵數的列數，迴歸 200 乘以特徵數，預測 5,000 乘以特徵數，而且時間序列識別欄至少 10 個不同的值。例如 20 個特徵的分類模型至少要 1,000 列。</p>



<h3 class="wp-block-heading">什麼時候一定要用自訂訓練？</h3>



<p class="wp-block-paragraph">AutoML 和 BigQuery ML 做不到的時候：需要自訂的模型架構或損失函數、要用特定框架（PyTorch、JAX）、研究團隊已經寫好程式、需要多台機器或多張 GPU 分散式訓練、需要完全控制訓練環境。官方比較表裡自訂訓練在「目標限制」和「資料量限制」兩項都是「沒有」。</p>



<h3 class="wp-block-heading">AutoML 和自訂訓練可以混用嗎？</h3>



<p class="wp-block-paragraph">可以，中間地帶不少。Tabular Workflows 是可控的 AutoML，把流程拆成資料切分、特徵工程、架構搜尋、訓練等步驟，每步可以自己決定要控制還是交給它，支援多 TB、1,000 欄的資料。BigQuery ML 裡也能用 SQL 叫 AutoML（model_type 設 AUTOML_CLASSIFIER），或匯入自己訓練的 TensorFlow 模型做預測。</p>



<h3 class="wp-block-heading">無伺服器訓練和訓練叢集差在哪？</h3>



<p class="wp-block-paragraph">都是自訂訓練。無伺服器訓練是要用才開機器、跑完就收、用多少付多少，適合實驗和不需要保證馬上有機器的工作；訓練叢集是先保留一批專屬的高階 GPU（例如 A100、H100），隨時可用不用排隊，適合大規模、長時間、不能等的關鍵訓練。Google 兩種都幫你管硬體維護和作業系統更新。</p>



<h3 class="wp-block-heading">一定要訓練模型嗎？</h3>



<p class="wp-block-paragraph">不一定，而且新版考試把「不訓練」排在第一區。Google 有預訓練 API（Vision API 認圖、Document AI 讀文件、Translation API 翻譯）和 Gemini 這類基礎模型，很多任務直接呼叫就能做。考試指南第 1.2 節就是「用 Google Cloud AI API 或基礎模型建方案」。先確認現成的做不到，再考慮訓練。</p>



<h3 class="wp-block-heading">Vertex AI AutoML 改名了嗎？</h3>



<p class="wp-block-paragraph">是。Vertex AI 在 2026 年 4 月改名為 Gemini Enterprise Agent Platform，AutoML 現在叫 AutoML on Gemini Enterprise Agent Platform，Vertex AI Training 改叫 Agent Platform Managed Training，Model Registry 改叫 Agent Platform Model Registry。BigQuery ML 名稱沒變。舊題庫的名稱對應到現在的服務，功能基本一樣。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>一條光譜</strong>：預訓練 API／Gemini（外送）→ AutoML（料理包）→ BigQuery ML（倉庫旁的廚房）→ 自訂訓練（自己煮）。越往後自由度越高、要會的越多</li>

<li><strong>先問要不要訓練</strong>：Gemini、Model Garden、預訓練 API 能做就不訓練，新版考試第 1.2 節</li>

<li><strong>BigQuery ML</strong>：資料在 BigQuery、團隊會 SQL；內建迴歸、分群、時間序列，也能叫 AutoML、匯入 TF／ONNX、遠端呼叫 Gemini；函數是 <code>ML.PREDICT</code> 不是 BQML.PREDICT</li>

<li><strong>AutoML</strong>：免寫程式；現在只有<strong>影像</strong>（分類、物件偵測）和<strong>表格</strong>（分類、迴歸、預測）；<strong>文字、影片已停用改 Gemini</strong>；資料最低量影像每類 100 張、表格分類 50 × 特徵數；Edge 模型匯出 TF Lite 到裝置上跑</li>

<li><strong>自訂訓練</strong>：自訂架構、損失函數、框架、分散式；無伺服器訓練（叫計程車）vs 訓練叢集（包月租車）</li>

<li><strong>中間地帶</strong>：Tabular Workflows（可控的 AutoML）、BigQuery ML 叫 AutoML</li>

<li><strong>Vertex AI 已改名 Gemini Enterprise Agent Platform</strong>，AutoML Tables／Vision／NL 這些獨立產品名都已成為歷史</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/20/types-of-machine-learning-supervised-unsupervised-reinforcement/">機器學習有哪幾種？監督式、非監督式、強化學習一次看懂</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/10/20/classification-vs-regression-mae-rmse/">分類和迴歸差在哪？一個例子搞懂，附 MAE、RMSE 計算</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">特徵、標籤、超參數是什麼？機器學習 5 個必懂名詞</a></li>

<li>第 4 篇：<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">訓練集、驗證集、測試集怎麼切？時間序列為什麼不能亂切</a></li>

<li>第 5 篇：<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">混淆矩陣是什麼？用快篩搞懂準確率、精確率、召回率、F1</a></li>

<li>第 6 篇：<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">ROC 曲線和 AUC 怎麼看？門檻怎麼調、AUC-PR 差在哪</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">過度擬合是什麼？正則化、Dropout、提前停止 3 招解決</a></li>

<li>第 8 篇：<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">資料洩漏是什麼？模型考試作弊的 3 種常見情況</a></li>

<li>第 9 篇：<a href="https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/">類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</a></li>

<li>第 10 篇：<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">資料前處理怎麼做？標準化、遺失值、高基數類別</a></li>

<li>第 11 篇：<a href="https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/">特徵工程是什麼？特徵交叉、詞嵌入、資料增強一次看懂</a></li>

<li>第 12 篇：<a href="https://dongdonggcp.com/2026/10/25/machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls/">機器學習的資料隱私怎麼保護？DLP、聯邦學習、VPC Service Controls</a></li>

<li>上一篇：第 13 篇：<a href="https://dongdonggcp.com/2026/10/25/tfrecords-tf-data-prefetch-input-pipeline/">訓練資料讀太慢？TFRecords、tf.data 與 prefetch 加速</a></li>

<li>下一篇：第 15 篇：<a href="https://dongdonggcp.com/2026/10/25/bigquery-ml-tutorial-train-model-with-sql/">BigQuery ML 入門：只會 SQL 也能訓練模型</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/04/14/vertex-ai-functions-agent-builder-model-builder-model-garden-introduction/">Vertex AI 核心功能 Agent Builder、Model Builder 和 Model Garden 介紹</a></li>

<li><a href="https://dongdonggcp.com/2025/07/04/is-bigquery-a-database-what-is-the-usage/">BigQuery 是資料庫嗎？跟資料庫差在哪</a></li>

<li><a href="https://dongdonggcp.com/2026/03/27/bigquery-billing-guide/">BigQuery 計費方式完整介紹</a></li>

<li><a href="https://dongdonggcp.com/2026/07/29/what-is-container-technology-docker-guide/">容器技術是什麼？從零開始看懂 Docker 與容器化應用</a></li>

<li><a href="https://dongdonggcp.com/2025/08/04/cloud-architect-without-coding/">不會寫程式，可以轉職雲端架構師嗎？</a></li>

<li><a href="https://dongdonggcp.com/2025/04/27/gcp-learning-roadmap/">GCP 學習路徑 Roadmap</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">知道該用哪個工具，才不會拿大砲打蚊子。如果你想有系統地從雲端基礎一路學到在 GCP 上動手做機器學習，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "Vertex AI AutoML、BigQuery ML、自訂訓練怎麼選？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "先問有沒有現成的 API 或 Gemini 能直接做，有就不用訓練。要訓練的話：資料是表格、已經在 BigQuery、團隊會 SQL，用 BigQuery ML；資料是影像或表格、目標在 AutoML 支援清單內、不想寫程式，用 AutoML；需要自訂模型架構、損失函數、特定框架或分散式訓練，用自訂訓練。官方的訓練方式文件有一張比較表，差別在需不需要 ML 專業、要不要寫程式、目標有沒有限制、能不能調超參數。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 是什麼？能做哪些模型？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "BigQuery ML 讓你用 SQL 在 BigQuery 裡直接訓練和使用模型，資料不用搬出去。內建的有線性迴歸、邏輯迴歸、K-means、矩陣分解、PCA、ARIMA_PLUS 時間序列；透過 Agent Platform 訓練的有 DNN、Wide & Deep、提升樹、隨機森林、AutoML；也能匯入 TensorFlow、ONNX、XGBoost 模型，或遠端呼叫 Gemini。預測用 ML.PREDICT，評估用 ML.EVALUATE，解釋用 ML.EXPLAIN_PREDICT。"
      }
    },
    {
      "@type": "Question",
      "name": "AutoML 是什麼？現在支援哪些資料？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "AutoML 是免寫程式的機器學習：你提供標好的資料，它自動做資料準備、選模型、調超參數、部署。目前官方訓練總覽列的支援範圍是影像（分類、物件偵測）和表格（分類、迴歸、預測）兩種資料類型。舊題庫的 AutoML Tables、AutoML Vision 都已整合進來，AutoML Natural Language 和 AutoML Video 都已停用，改用 Gemini。"
      }
    },
    {
      "@type": "Question",
      "name": "AutoML Natural Language 還能用嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不能。Google 在 2024 年 6 月公告，2024 年 9 月 15 日起 AutoML 的文字分類、實體擷取、情感分析不再開放訓練，既有模型到 2025 年 6 月 15 日停用，改用 Gemini 的提示詞和模型調校。舊題庫看到文字分類選 AutoML Natural Language，現在的答案是 Gemini。"
      }
    },
    {
      "@type": "Question",
      "name": "AutoML Vision Edge 是什麼？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "舊名稱，現在叫 AutoML 影像的 Edge 模型。訓練時選 Edge 類型，訓練完可以匯出成 TF Lite、Edge TPU TF Lite、Core ML、TensorFlow.js 或容器，部署到手機、工廠機台這類裝置上，離線也能判斷。官方特別提醒 Edge 模型不能在 Agent Platform 上提供預測，一定要部署到外部裝置。"
      }
    },
    {
      "@type": "Question",
      "name": "AutoML 要多少資料？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "官方初學者指南的經驗法則：影像每個類別至少 100 張，目標 1,000 張，最少的類別要有最多類別的 10% 以上；表格分類至少 50 乘以特徵數的列數，迴歸 200 乘以特徵數，預測 5,000 乘以特徵數，而且時間序列識別欄至少 10 個不同的值。例如 20 個特徵的分類模型至少要 1,000 列。"
      }
    },
    {
      "@type": "Question",
      "name": "什麼時候一定要用自訂訓練？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "AutoML 和 BigQuery ML 做不到的時候：需要自訂的模型架構或損失函數、要用特定框架（PyTorch、JAX）、研究團隊已經寫好程式、需要多台機器或多張 GPU 分散式訓練、需要完全控制訓練環境。官方比較表裡自訂訓練在「目標限制」和「資料量限制」兩項都是「沒有」。"
      }
    },
    {
      "@type": "Question",
      "name": "AutoML 和自訂訓練可以混用嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "可以，中間地帶不少。Tabular Workflows 是可控的 AutoML，把流程拆成資料切分、特徵工程、架構搜尋、訓練等步驟，每步可以自己決定要控制還是交給它，支援多 TB、1,000 欄的資料。BigQuery ML 裡也能用 SQL 叫 AutoML（model_type 設 AUTOML_CLASSIFIER），或匯入自己訓練的 TensorFlow 模型做預測。"
      }
    },
    {
      "@type": "Question",
      "name": "無伺服器訓練和訓練叢集差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "都是自訂訓練。無伺服器訓練是要用才開機器、跑完就收、用多少付多少，適合實驗和不需要保證馬上有機器的工作；訓練叢集是先保留一批專屬的高階 GPU（例如 A100、H100），隨時可用不用排隊，適合大規模、長時間、不能等的關鍵訓練。Google 兩種都幫你管硬體維護和作業系統更新。"
      }
    },
    {
      "@type": "Question",
      "name": "一定要訓練模型嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不一定，而且新版考試把「不訓練」排在第一區。Google 有預訓練 API（Vision API 認圖、Document AI 讀文件、Translation API 翻譯）和 Gemini 這類基礎模型，很多任務直接呼叫就能做。考試指南第 1.2 節就是「用 Google Cloud AI API 或基礎模型建方案」。先確認現成的做不到，再考慮訓練。"
      }
    },
    {
      "@type": "Question",
      "name": "Vertex AI AutoML 改名了嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "是。Vertex AI 在 2026 年 4 月改名為 Gemini Enterprise Agent Platform，AutoML 現在叫 AutoML on Gemini Enterprise Agent Platform，Vertex AI Training 改叫 Agent Platform Managed Training，Model Registry 改叫 Agent Platform Model Registry。BigQuery ML 名稱沒變。舊題庫的名稱對應到現在的服務，功能基本一樣。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/10/25/vertex-ai-automl-bigquery-ml-custom-training-how-to-choose/">Vertex AI AutoML、BigQuery ML、自訂訓練怎麼選？</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/10/25/vertex-ai-automl-bigquery-ml-custom-training-how-to-choose/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>機器學習的資料隱私怎麼保護？DLP、聯邦學習、VPC Service Controls</title>
		<link>https://dongdonggcp.com/2026/10/25/machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls</link>
					<comments>https://dongdonggcp.com/2026/10/25/machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 25 Oct 2026 05:40:30 +0000</pubDate>
				<category><![CDATA[AI 和機器學習]]></category>
		<category><![CDATA[證照考試]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[BigQuery]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[PMLE]]></category>
		<category><![CDATA[Vertex AI]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[生成式 AI]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=12816</guid>

					<description><![CDATA[<p>機器學習的資料隱私怎麼保護？用連鎖飲料店的會員資料算給你看：DLP 把手機和卡號遮掉、k-匿名算出被認出的機率、聯邦學習讓資料留在手機、VPC Service Controls 防外洩，附 PMLE 考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/10/25/machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls/">機器學習的資料隱私怎麼保護？DLP、聯邦學習、VPC Service Controls</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>機器學習的資料隱私怎麼保護？DLP 找出並遮掉個資、聯邦學習讓資料留在手機、VPC Service Controls 防止外洩。</strong></p>



<p class="wp-block-paragraph">前幾篇都在教你怎麼把資料整理好、加工好，讓模型學得更準。這篇要處理另一件一樣重要的事：<strong>資料裡面有「人」</strong>。</p>



<p class="wp-block-paragraph">一樣用有 2,000 間分店、50 萬名會員的連鎖飲料店當例子（教學假設），一次處理三個問題：</p>


<ul class="wp-block-list">
<li>會員資料要拿去訓練「誰下個月不會再來」的模型，但不想讓資料團隊看到誰是誰 → <strong>DLP 去識別化</strong></li>

<li>App 想學客人在手機上的使用習慣，但這些紀錄不想、也不該上傳 → <strong>聯邦學習</strong></li>

<li>資料和模型都放在雲端，要確保沒有人能把它們搬走 → <strong>VPC Service Controls</strong></li>
</ul>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-01-overview.png" alt="機器學習的資料隱私怎麼保護：DLP 先把手機和卡號遮掉，聯邦學習讓資料留在手機只上傳學到的數字，VPC Service Controls 在雲端畫一道圍牆防止資料被搬出去" class="wp-image-12811" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-01-overview.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-01-overview-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-01-overview-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-01-overview-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>模型會「記住」資料</strong>：訓練資料裡有個資，模型可能把它記下來。Google Cloud 的<a href="https://docs.cloud.google.com/architecture/cross-silo-cross-device-federated-learning-google-cloud">聯邦學習架構文件</a>就特別提到，要用額外的技術，確保最後的模型不會記住任何一位使用者的資料</li>

<li><strong>生成式 AI 風險更大</strong>：聊天機器人可能在回答裡說出看過的敏感資料，客人也可能把卡號直接打進對話框，所以 Google 另外做了 Model Armor 來把關（後面會講）</li>

<li><strong>法律有規定</strong>：台灣有《個人資料保護法》，歐盟有 GDPR。Google 的<a href="https://docs.cloud.google.com/sensitive-data-protection/docs/sensitive-data-protection-overview">官方文件</a>也把 GDPR、HIPAA（美國醫療資料法規）、PCI DSS（信用卡資料安全標準）列為常見的使用情境</li>

<li><strong>證照必考</strong>：PMLE 考試指南第 2.1 節明列「確保資料隱私、處理敏感資訊（例如個資）」，第 6.1 節要你會防止「資料外洩、惡意提示詞、把敏感資料分享給大型語言模型」</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">先搞懂：什麼是個資？</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>個資</strong>（個人資料）：能認出「這是誰」的資料。英文常寫成 <strong>PII</strong>（Personally Identifiable Information，可識別個人的資訊）。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>包裹上的收件人標籤</strong>：姓名、電話、地址，任何人看一眼就知道這是誰的包裹。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">台灣《個人資料保護法》<a href="https://law.moj.gov.tw/LawClass/LawAll.aspx?pcode=I0050021">第 2 條</a>列了一長串：姓名、出生年月日、身分證字號、指紋、聯絡方式、財務情況……最後還有一句很關鍵：「其他得以直接或間接方式識別該個人之資料」。</p>



<p class="wp-block-paragraph">「<strong>間接</strong>」兩個字是重點：有些資料單獨看認不出是誰，<strong>組合起來就認得出來</strong>。</p>



<h3 class="wp-block-heading">直接識別 vs 間接識別</h3>



<p class="wp-block-paragraph">Google 的<a href="https://docs.cloud.google.com/sensitive-data-protection/docs/concepts-risk-analysis">風險分析文件</a>把會認出人的資料分成兩種：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>直接識別資料（Identifier）</th><th>準識別資料（Quasi-identifier）</th></tr></thead><tbody><tr><td>白話</td><td>一看就知道是誰</td><td>單獨看不知道，組合起來就知道</td></tr><tr><td>飲料店會員表裡</td><td>姓名、手機、身分證字號、Email、信用卡號</td><td>年齡、居住的行政區、性別</td></tr><tr><td>怎麼處理</td><td>刪掉、遮掉、換成代號</td><td>切粗一點（例如年齡改成年齡區間），再檢查還認不認得出來</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">美國學者 Latanya Sweeney 在 2000 年的<a href="https://dataprivacylab.org/projects/identifiability/paper1.pdf">研究</a>估計，光靠「郵遞區號＋性別＋出生日期」三個欄位，就能認出約 87% 的美國人。</p>



<p class="wp-block-paragraph">所以<strong>只刪掉姓名，遠遠不夠</strong>。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">機器學習要大量資料，而最有價值的資料（消費、醫療、金融）幾乎都跟人有關。先分清楚哪些欄位會認出人，後面三招才知道要保護什麼。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">1. DLP 去識別化：資料進模型前，先把個資遮掉</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>DLP</strong>（Data Loss Prevention，資料外洩防護）在 Google Cloud 上是一組 API：自動<strong>找出</strong>資料裡的個資，再把它<strong>去識別化</strong>（De-identification），也就是改成認不出是誰的樣子。</p>



<p class="wp-block-paragraph"><strong>API</strong> 是程式跟服務溝通的窗口，像點餐櫃台：你照格式把需求遞進去，它把結果遞出來。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像新聞畫面<strong>打馬賽克</strong>：事情的經過還看得懂，只是認不出是誰。</p>



<p class="wp-block-paragraph">對模型來說也一樣。「客人抱怨被重複扣款」這件事要留著讓模型學，但客人的卡號是幾號，模型根本不需要知道。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">DLP 原本是資安業界的說法，指<strong>防止機密資料流出公司</strong>的工具，例如擋下夾帶客戶名單的 Email。</p>



<p class="wp-block-paragraph">Google Cloud 的這套服務原本就叫 Cloud DLP，2023 年起歸到 <strong>Sensitive Data Protection</strong>（敏感資料保護）這個產品底下。<a href="https://docs.cloud.google.com/sensitive-data-protection/docs/sensitive-data-protection-overview">官方總覽</a>現在的寫法是「Sensitive Data Protection 的 Cloud Data Loss Prevention API（DLP API）」。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>舊題庫可能還會看到 Cloud DLP、DLP API，現在的產品名稱是 Sensitive Data Protection。</strong><br>API 的名字沒變，還是叫 Cloud Data Loss Prevention API，網址也還是 <code>dlp.googleapis.com</code>。看到 DLP 和 Sensitive Data Protection，指的是同一套東西。</p>
</blockquote>



<h3 class="wp-block-heading">它怎麼找到個資：infoType</h3>



<p class="wp-block-paragraph">DLP 用一個個「偵測器」來找個資，每一種偵測器叫一個 <strong>infoType</strong>（資訊類型）。依照<a href="https://docs.cloud.google.com/sensitive-data-protection/docs/infotypes-reference">官方 infoType 清單</a>，內建的就有這些：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>infoType</th><th>找什麼</th></tr></thead><tbody><tr><td><code>PHONE_NUMBER</code></td><td>電話號碼</td></tr><tr><td><code>EMAIL_ADDRESS</code></td><td>Email</td></tr><tr><td><code>CREDIT_CARD_NUMBER</code></td><td>信用卡號</td></tr><tr><td><code>TAIWAN_ID_NUMBER</code></td><td>台灣身分證字號</td></tr><tr><td><code>TAIWAN_PASSPORT</code></td><td>台灣護照號碼</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">找到之後，下一步就是「要怎麼遮」。</p>



<h3 class="wp-block-heading">去識別化的方法，套在會員表上</h3>



<p class="wp-block-paragraph"><a href="https://docs.cloud.google.com/sensitive-data-protection/docs/transformations-reference">官方的方法清單</a>分成七大類。套到飲料店的會員表（教學用的資料）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>欄位</th><th>原始資料</th><th>方法</th><th>處理後</th><th>還原得回來嗎</th></tr></thead><tbody><tr><td>姓名</td><td>王小明</td><td><strong>刪除</strong>（Redaction）</td><td>（空白）</td><td>不能</td></tr><tr><td>手機</td><td>0912-345-678</td><td><strong>遮罩</strong>（Masking）</td><td><code>####-###-678</code></td><td>不能</td></tr><tr><td>會員編號</td><td>M0012345</td><td><strong>加密令牌化</strong>（Crypto-based tokenization）</td><td>一串代號，例如 <code>AWttmG…</code></td><td>有金鑰才能</td></tr><tr><td>年齡</td><td>27</td><td><strong>分桶</strong>（Bucketing）</td><td>20～29 歲</td><td>不能</td></tr><tr><td>加入日期</td><td>2024-03-15</td><td><strong>日期偏移</strong>（Date shifting）</td><td>2024-04-02</td><td>不能</td></tr><tr><td>客服留言</td><td>卡號 4111 1111 1111 1111 被重複扣款</td><td><strong>取代</strong>（Replacement）成類型名稱</td><td>卡號 [CREDIT_CARD_NUMBER] 被重複扣款</td><td>不能</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">第七類是<strong>時間擷取</strong>（Time extraction），例如只留下年份。</p>



<p class="wp-block-paragraph"><strong>日期偏移</strong>是把日期往前或往後隨機挪幾天。同一位會員的所有日期可以設定成挪一樣多，所以「加入多久之後才第一次消費」這種<strong>間隔</strong>還在，模型照樣學得到。</p>



<p class="wp-block-paragraph"><strong>最安全的做法，是模型用不到的欄位就不要給。</strong> 姓名、手機對「預測誰會流失」幾乎沒有幫助，直接刪掉就好；需要串資料、之後還要找回本人的欄位，才用令牌化。</p>



<h3 class="wp-block-heading">令牌化（Tokenization）：換成號碼牌</h3>



<p class="wp-block-paragraph"><strong>白話</strong>：把真正的值換成一個<strong>代號</strong>，代號本身看不出原本是什麼。</p>



<p class="wp-block-paragraph"><strong>比喻</strong>：像<strong>衣帽間的號碼牌</strong>。你把外套交出去，拿到一張 37 號的牌子。別人撿到這張牌，也不知道外套是誰的；只有櫃台對得回去。</p>



<p class="wp-block-paragraph"><strong>來龍去脈</strong>：token 原意是代幣、憑證。<a href="https://docs.cloud.google.com/sensitive-data-protection/docs/pseudonymization">官方文件</a>說，這個做法也叫<strong>假名化</strong>（Pseudonymization），像作家用筆名發表作品，讀者不知道本名。</p>



<p class="wp-block-paragraph">DLP 的令牌化是用<strong>加密</strong>做的。加密就是用一把<strong>金鑰</strong>把資料鎖成亂碼，有同一把金鑰才解得開。官方建議把金鑰放在 <strong>Cloud KMS</strong>（Key Management Service，金鑰管理服務），就是 Google 雲端上專門保管金鑰的保險箱。</p>



<p class="wp-block-paragraph"><strong>為什麼要學</strong>：機器學習最常遇到兩個需求，令牌化剛好都能滿足：</p>


<ol class="wp-block-list">
<li><strong>還要能串資料</strong>：會員表和訂單表都有會員編號。換成代號之後，同一個人在兩張表的代號一樣，照樣可以合併（JOIN，把兩張表依同一欄對起來）</li>

<li><strong>之後要找回本人</strong>：模型預測「代號 <code>AWttmG…</code> 下個月可能不會再來」，行銷要發優惠券給他，有權限的系統用金鑰還原成會員編號就好</li>
</ol>



<h3 class="wp-block-heading">三種令牌化，差在哪</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>確定性加密（AES-SIV）</th><th>格式保留加密（FPE）</th><th>加密雜湊（HMAC-SHA-256）</th></tr></thead><tbody><tr><td>白話</td><td>同一個值，每次都換成同一串代號</td><td>加密後「長得跟原本一樣」</td><td>單向絞碎，變不回來</td></tr><tr><td>16 碼的卡號會變成</td><td>一串長度不同的亂碼代號</td><td>另一組 16 位數字</td><td>一串固定長度的亂碼</td></tr><tr><td>能還原嗎</td><td>能（要有金鑰）</td><td>能（要有金鑰）</td><td><strong>不能</strong></td></tr><tr><td>同一個值，代號一樣嗎</td><td>一樣</td><td>一樣</td><td>一樣</td></tr><tr><td>適合</td><td>大部分情況的首選</td><td>舊系統規定格式、長度不能變</td><td>不需要還原，只要能串資料、能計數</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">三種都會讓「同一個值換成同一個代號」，所以都能串資料。差別在<strong>能不能還原</strong>、<strong>格式會不會變</strong>。</p>



<p class="wp-block-paragraph">名字怎麼來：AES（Advanced Encryption Standard，進階加密標準）是現在最常見的加密標準，SIV 這種用法讓同樣的輸入每次都得到同樣的結果，所以叫「確定性」加密。SHA-256 是常見的雜湊公式，HMAC 是「再加上一把金鑰」的做法。</p>



<p class="wp-block-paragraph"><strong>加密雜湊</strong>像把水果丟進果汁機：打成汁就變不回原樣，但同樣的水果每次打出來都一樣。<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">第 10 篇</a>的雜湊分桶也是「固定公式換成號碼」，這裡多加了一把金鑰，別人就算知道公式，沒有金鑰也算不出同樣的結果。</p>



<h3 class="wp-block-heading">筆記裡的 FPE：官方現在不建議預設就用</h3>



<p class="wp-block-paragraph"><strong>格式保留加密</strong>（Format-Preserving Encryption，FPE）：加密之後<strong>字元種類和長度都不變</strong>。例如把一組手機號碼，換成另一組「看起來也像手機號碼」的數字。</p>



<p class="wp-block-paragraph">它是為了<strong>舊系統</strong>而生的：很多舊系統規定卡號一定要是 16 位數字，換成英數字代號就會出錯。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>舊題庫、舊筆記常寫「用 FPE 做令牌化」，現在官方文件特別提醒：除非一定要保留原本的字元和長度，否則不要用 FPE。</strong><br><a href="https://docs.cloud.google.com/sensitive-data-protection/docs/transformations-reference">官方的方法清單</a>說，FPE 可能跑得很慢，對字元種類和長度也有限制；確定性加密（AES-SIV）沒有這些限制，速度也快得多。<a href="https://docs.cloud.google.com/sensitive-data-protection/docs/pseudonymization">假名化文件</a>也提到，FPE 的安全保證比 AES-SIV 少。</p>
</blockquote>



<p class="wp-block-paragraph">考試的判斷很簡單：題目強調「<strong>格式、長度不能變</strong>」才選 FPE，其他要還原的情況選 AES-SIV。</p>



<h3 class="wp-block-heading">去識別化之後就安全了嗎？算一次 k-匿名</h3>



<p class="wp-block-paragraph"><strong>白話</strong>：<strong>k-匿名</strong>（k-anonymity）是一種檢查方式：表裡每個人，<strong>至少要跟另外 k−1 個人的準識別資料一模一樣</strong>。k 越大，越難把人挑出來。</p>



<p class="wp-block-paragraph"><strong>比喻</strong>：<strong>躲在人群裡</strong>。你只知道對方是「穿制服的高二男生」，全班有 20 個人符合，你認不出是哪一個；如果全校只有一個人符合，一下就被認出來了。</p>



<p class="wp-block-paragraph"><strong>來龍去脈</strong>：1998 年由 Samarati 和 Sweeney 提出。<a href="https://docs.cloud.google.com/sensitive-data-protection/docs/concepts-risk-analysis">官方文件</a>說，它是為了「量化資料有多容易被認出來」，同時在<strong>隱私</strong>和<strong>資料還有沒有用</strong>之間取得平衡。</p>



<p class="wp-block-paragraph"><strong>為什麼要學</strong>：去識別化不是「做了就好」，要<strong>量</strong>才知道夠不夠。Sensitive Data Protection 的<strong>風險分析</strong>（Risk analysis）可以直接幫你算 BigQuery 資料表的 k 值。</p>



<h4 class="wp-block-heading">公式</h4>



<pre class="wp-block-code"><code>k = 準識別資料完全一樣的每一組裡，人數最少的那一組有幾個人
被認出來的機率最多 = 1 ÷ k</code></pre>



<p class="wp-block-paragraph">準識別資料完全一樣的一群人，官方文件叫<strong>等價類別</strong>（Equivalence class），下面簡稱「一組」。</p>



<h4 class="wp-block-heading">帶數字算一次</h4>



<p class="wp-block-paragraph">假設（教學用的數字）會員表已經刪掉姓名、手機，只剩<strong>年齡</strong>和<strong>行政區</strong>兩個準識別資料：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>會員</th><th>A</th><th>B</th><th>C</th><th>D</th><th>E</th><th>F</th><th>G</th><th>H</th></tr></thead><tbody><tr><td>年齡</td><td>23</td><td>27</td><td>25</td><td>29</td><td>34</td><td>38</td><td>31</td><td>46</td></tr><tr><td>行政區</td><td>大安</td><td>大安</td><td>大安</td><td>大安</td><td>信義</td><td>信義</td><td>信義</td><td>信義</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>第 1 步：直接用原本的年齡</strong></p>



<p class="wp-block-paragraph">每個人的「年齡＋行政區」都不一樣，每一組只有 1 個人：</p>



<pre class="wp-block-code"><code>k = 1
被認出來的機率最多 = 1 ÷ 1 = 100%</code></pre>



<p class="wp-block-paragraph">你只要知道同事「34 歲、住信義區」，就能在表裡找到他整份消費紀錄。</p>



<p class="wp-block-paragraph"><strong>第 2 步：年齡每 10 歲切一段（分桶）</strong></p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>組別</th><th>成員</th><th>人數</th></tr></thead><tbody><tr><td>20～29 歲、大安區</td><td>A、B、C、D</td><td>4</td></tr><tr><td>30～39 歲、信義區</td><td>E、F、G</td><td>3</td></tr><tr><td>40～49 歲、信義區</td><td>H</td><td><strong>1</strong></td></tr></tbody></table></figure>



<pre class="wp-block-code"><code>k = 最小的那一組 = min(4, 3, 1) = 1</code></pre>



<p class="wp-block-paragraph">大部分人都藏好了，但 H 是全表唯一 40 幾歲的，還是一眼被認出來。</p>



<p class="wp-block-paragraph"><strong>第 3 步：把 30 歲以上合成一段</strong></p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>組別</th><th>成員</th><th>人數</th></tr></thead><tbody><tr><td>20～29 歲、大安區</td><td>A、B、C、D</td><td>4</td></tr><tr><td>30 歲以上、信義區</td><td>E、F、G、H</td><td>4</td></tr></tbody></table></figure>



<pre class="wp-block-code"><code>k = min(4, 4) = 4
被認出來的機率最多 = 1 ÷ 4 = 25%</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-02-k-anonymity.png" alt="k-匿名怎麼算：年齡每 10 歲切一段時，全表唯一 46 歲的會員自成一組，k 等於 1、被認出機率 100%；改成 30 歲以上合成一段，k 等於 4、機率降到 25%" class="wp-image-12812" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-02-k-anonymity.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-02-k-anonymity-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-02-k-anonymity-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-02-k-anonymity-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h4 class="wp-block-heading">數字怎麼看</h4>


<ul class="wp-block-list">
<li><strong>k = 1</strong>：至少有一個人是「獨一無二」的，知道他的年齡和住哪就認得出來</li>

<li><strong>k 越大越安全</strong>：k = 4 代表就算鎖定了那一組，猜對是誰的機會最多 25%</li>

<li><strong>但 k 越大，資料越模糊</strong>：「30 歲以上」把 31 歲和 46 歲混在一起，模型就學不到這兩個年紀的人口味不一樣。這就是隱私和模型準確度之間的取捨</li>

<li><strong>一個人就能拉低整張表</strong>：k 看的是最小的那一組，只要有一個特別的人，k 就掉到 1。除了把區間切粗，也可以把這種很少見的資料拿掉</li>

<li><strong>要多大才夠</strong>：沒有標準答案，要看資料多敏感，跟公司的資安、法務一起決定</li>
</ul>



<p class="wp-block-paragraph">k-匿名還有一個漏洞：如果同一組的 4 個人，模型全都標成「會流失」，就算認不出是誰，也知道「住信義區、30 歲以上的會員都會流失」。所以官方文件還有 <strong>l-多樣性</strong>（l-diversity），檢查同一組裡的敏感資訊夠不夠多樣。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">PMLE 第 2.1 節直接考「處理個資」。題目看到「PII」「信用卡號」「去識別化」，答案幾乎都是 Sensitive Data Protection，再依「要不要還原」「格式能不能變」挑方法。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">2. 聯邦學習：資料不離開手機，只交出「學到的東西」</h2>



<h3 class="wp-block-heading">先看問題：資料一定要集中嗎？</h3>



<p class="wp-block-paragraph">傳統的機器學習，要把資料<strong>全部集中</strong>到一台機器或一個資料中心，再來訓練。Google 研究團隊 2017 年的<a href="https://research.google/blog/federated-learning-collaborative-machine-learning-without-centralized-training-data/">文章</a>第一段就這樣寫。</p>



<p class="wp-block-paragraph">飲料店的 App 想做「猜你想點」。最有用的線索，是客人在手機上<strong>滑了哪些飲料、看了多久、最後沒點的是哪幾杯</strong>。</p>



<p class="wp-block-paragraph">但要把每個人的滑動紀錄都上傳到<strong>伺服器</strong>（負責接收資料、跑程式的那台電腦），客人會不舒服，法務也會擔心。</p>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>聯邦學習</strong>（Federated Learning）：資料留在每個人自己的手機上，<strong>讓模型跑去資料那裡學</strong>。手機只把「學到的東西」交回來，伺服器再把大家的成果合起來，變成一個更好的共用模型。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像連鎖店的<strong>店長心得</strong>。總部想改進 SOP（標準作業流程），但不想把 2,000 間分店的帳本都收上來。</p>



<p class="wp-block-paragraph">於是每位店長看完自己店的帳，寫一張「心得小抄」交給總部；總部把所有小抄整理成新版 SOP，再發回各店。<strong>帳本從頭到尾沒離開過分店。</strong></p>



<h3 class="wp-block-heading">來龍去脈</h3>


<ul class="wp-block-list">
<li><strong>名字的由來</strong>：Google 研究人員在<a href="https://arxiv.org/abs/1602.05629">論文</a>裡說，這種學習是由一群「鬆散結盟」（federation）的裝置一起完成，再由中央伺服器協調。就像聯邦國家，各州自己管自己，但一起組成一個國家</li>

<li><strong>實際的例子</strong>：2017 年 Google 在 Android 的 Gboard 鍵盤上測試。手機在本機記下「跳出來的搜尋建議，你有沒有點」，再用這些紀錄改進下一版的建議模型</li>

<li><strong>不影響手機使用</strong>：訓練只在手機<strong>閒置、正在充電、連著免費 Wi-Fi</strong> 的時候進行</li>

<li><strong>省網路</strong>：他們提出的<strong>聯邦平均</strong>（Federated Averaging）演算法，跟直接搬用傳統做法比，網路傳輸量可以少 10～100 倍</li>
</ul>



<h3 class="wp-block-heading">四個步驟</h3>


<ol class="wp-block-list">
<li>伺服器把目前的模型<strong>發給</strong>手機</li>

<li>每支手機用<strong>自己的資料</strong>，在手機上訓練</li>

<li>手機只把「<strong>模型更新</strong>」加密傳回去</li>

<li>伺服器把大家的更新<strong>平均</strong>成新版模型，再回到第 1 步</li>
</ol>



<p class="wp-block-paragraph"><strong>模型更新</strong>是什麼？<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">第 3 篇</a>說過，模型裡有很多<strong>權重</strong>（代表每個線索有多重要的數字）。手機訓練完，這些數字會變，傳回去的就是新的數字，不是點餐紀錄本身。</p>



<h3 class="wp-block-heading">算一次給你看：聯邦平均</h3>



<p class="wp-block-paragraph">假設（教學用的數字）模型裡有一個權重，代表「<strong>下雨天推薦熱飲</strong>」這個線索有多重要。伺服器發下去的版本是 0.50，三支手機各自用自己的紀錄訓練：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>手機</th><th>這支手機上的點餐紀錄</th><th>訓練後的權重</th></tr></thead><tbody><tr><td>A</td><td>120 筆（下雨天幾乎都點熱飲）</td><td>0.80</td></tr><tr><td>B</td><td>60 筆</td><td>0.40</td></tr><tr><td>C</td><td>20 筆（點飲料不太看天氣）</td><td>0.10</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><a href="https://arxiv.org/abs/1602.05629">聯邦平均</a>會依照每支手機的<strong>資料筆數</strong>加權：</p>



<pre class="wp-block-code"><code>新權重 = (n₁ × w₁ + n₂ × w₂ + n₃ × w₃) ÷ (n₁ + n₂ + n₃)

n = 這支手機有幾筆資料
w = 這支手機訓練出來的權重</code></pre>



<p class="wp-block-paragraph">代入：</p>



<pre class="wp-block-code"><code>新權重 = (120 × 0.80 + 60 × 0.40 + 20 × 0.10) ÷ (120 + 60 + 20)
      = (96 + 24 + 2) ÷ 200
      = 122 ÷ 200
      = 0.61</code></pre>



<p class="wp-block-paragraph">如果不管筆數、直接平均：</p>



<pre class="wp-block-code"><code>(0.80 + 0.40 + 0.10) ÷ 3 = 1.30 ÷ 3 ≈ 0.43</code></pre>



<h3 class="wp-block-heading">數字怎麼看</h3>


<ul class="wp-block-list">
<li><strong>0.61 比原本的 0.50 大</strong>：整體來說，「下雨天推熱飲」這個線索變得更重要，下一版模型在下雨天會更常推熱飲</li>

<li><strong>資料越多，份量越重</strong>：手機 A 有 120 筆，份量是手機 C 的 6 倍。只有 20 筆的手機，練出來的結果比較不穩，給它小一點的份量很合理</li>

<li><strong>跟直接平均差很多</strong>：0.61 和 0.43 差了快 0.2。這也是 TensorFlow Federated 的函數叫 <code>build_weighted_fed_avg</code>（加權聯邦平均）的原因，後面會看到</li>

<li><strong>伺服器從頭到尾只拿到 6 個數字</strong>：三個筆數、三個權重，200 筆點餐紀錄一筆都沒有上傳</li>

<li><strong>真實的模型</strong>有幾百萬個權重，每一個都這樣平均，而且會一輪一輪重複很多次</li>
</ul>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-03-federated-averaging.png" alt="聯邦學習怎麼算：三支手機各有 120、60、20 筆紀錄，訓練出 0.80、0.40、0.10，依筆數加權平均得到 0.61，直接平均只有 0.43；上傳的是數字，不是點餐紀錄" class="wp-image-12813" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-03-federated-averaging.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-03-federated-averaging-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-03-federated-averaging-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-03-federated-averaging-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">聯邦學習也不是百分之百安全</h3>



<p class="wp-block-paragraph">「資料沒有上傳」不等於「什麼都沒洩漏」。模型更新多少還帶著資料的影子，所以通常會再加兩道保護：</p>


<ul class="wp-block-list">
<li><strong>安全聚合</strong>（Secure Aggregation）：用加密技術，讓伺服器<strong>只解得開所有人的平均</strong>。<a href="https://research.google/blog/federated-learning-collaborative-machine-learning-without-centralized-training-data/">Google 的設計</a>是要有幾百、幾千支手機參與才解得開，看不到任何一支手機自己的更新</li>

<li><strong>差分隱私</strong>（Differential Privacy）：在結果裡加一點刻意的雜訊，讓最後的模型<strong>不會記住任何一個人的資料</strong></li>
</ul>



<p class="wp-block-paragraph">差分隱私的比喻，<a href="https://docs.cloud.google.com/bigquery/docs/differential-privacy">BigQuery 官方文件</a>講得很好懂：一家小餐廳半夜 1 點本來沒人，如果人潮統計圖上突然多出一位，大家就知道「有個客人半夜 1 點來過」。差分隱私就是讓統計結果看不出任何一個人有沒有在裡面。</p>



<h3 class="wp-block-heading">兩種聯邦學習</h3>



<p class="wp-block-paragraph">Google Cloud 的<a href="https://docs.cloud.google.com/architecture/cross-silo-cross-device-federated-learning-google-cloud">架構文件</a>把它分成兩種：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>跨裝置（Cross-device）</th><th>跨機構（Cross-silo）</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></tbody></table></figure>



<p class="wp-block-paragraph">silo 是「穀倉」的意思：每家機構的資料，就像一座一座分開的穀倉，彼此不互通。</p>



<h3 class="wp-block-heading">什麼時候不適合</h3>



<p class="wp-block-paragraph"><a href="https://research.google/blog/federated-learning-collaborative-machine-learning-without-centralized-training-data/">Google 的文章</a>也說，聯邦學習不能解決所有問題：</p>


<ul class="wp-block-list">
<li><strong>資料本來就在雲端</strong>：Google 舉的例子是 Gmail 的垃圾信過濾。換成飲料店，<strong>訂單</strong>本來就存在公司的資料庫，直接集中訓練就好，不用繞一圈</li>

<li><strong>需要人工仔細標答案</strong>：例如辨認狗的品種，要有人一張一張標好，這種資料不會自然出現在手機上</li>

<li><strong>工程師看不到原始資料</strong>：檢查資料品質、找錯誤都變難，網路傳輸量也是限制</li>
</ul>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">舊題庫的經典情境：「<strong>指紋</strong>」「臉部」「鍵盤輸入」這類資料<strong>不能離開裝置</strong>，答案就是聯邦學習。新版考試指南沒有直接點名它，但「資料不能集中時怎麼訓練」，一樣是第 2.1 節「確保資料隱私」會用到的判斷。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">3. VPC Service Controls：在雲端服務外面，畫一道圍牆</h2>



<h3 class="wp-block-heading">先看問題：權限設好了，還不夠嗎？</h3>



<p class="wp-block-paragraph">在 Google Cloud 上，誰能讀哪份資料，是由 <strong>IAM</strong>（Identity and Access Management，身分與存取權管理）決定的。它像<strong>員工識別證</strong>：刷卡才進得了特定房間。</p>



<p class="wp-block-paragraph">但識別證有兩種情況擋不住：</p>


<ul class="wp-block-list">
<li><strong>識別證被偷</strong>：程式用的<strong>服務帳戶</strong>（Service Account，給程式用的帳號）有一把<strong>金鑰</strong>（一個檔案，等於這個帳號的密碼）。金鑰不小心傳到網路上，駭客在自己家裡就能用它讀你的資料</li>

<li><strong>有權限的人亂搬</strong>：資料科學家本來就能讀會員表，他把整張表複製到自己的私人<strong>專案</strong>（Project，Google Cloud 上裝資源的單位，像一本獨立的帳本），IAM 不會攔</li>
</ul>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>VPC Service Controls</strong>：在 Google Cloud 的服務（例如 BigQuery、Cloud Storage、Agent Platform）外面，畫一道<strong>服務邊界</strong>（Service perimeter）。邊界裡面可以自由使用，但：</p>


<ul class="wp-block-list">
<li>從邊界<strong>外面</strong>來的請求，就算帶著真的金鑰，也會被擋下</li>

<li>資料<strong>不能被複製</strong>到邊界外面</li>
</ul>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>銀行金庫大樓的保全大門</strong>。識別證（IAM）決定你能進哪個房間；保全大門決定「外面的人進不進得來」「東西能不能帶出大樓」。</p>



<p class="wp-block-paragraph">就算有人撿到員工識別證，人在大樓外面也刷不進來。</p>



<h3 class="wp-block-heading">來龍去脈</h3>


<ul class="wp-block-list">
<li><strong>名字拆開看</strong>：VPC 是 Virtual Private Cloud（虛擬私有雲），就是你在 Google Cloud 上的<strong>私人網路</strong>；Service Controls 是「<strong>對服務做管制</strong>」</li>

<li><strong>為什麼需要它</strong>：以前資料放在公司自己的機房，外面有實體圍牆和防火牆。上雲之後，BigQuery、Cloud Storage 這些是 <strong>Google 代管</strong>的服務，大家透過網路上的 API 使用，原本那套網路圍牆管不到它們。<a href="https://docs.cloud.google.com/vpc-service-controls/docs/overview">官方文件</a>說，很多公司從機房搬上雲時，想在雲端重現原本「以網路為界」的保護方式，VPC Service Controls 就是在做這件事</li>

<li><strong>它是 IAM 之外獨立的一層</strong>：官方建議兩個一起用，這叫<strong>縱深防禦</strong>（Defense in depth）：一層被突破，還有下一層</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>別跟第 8 篇搞混：資料外洩（data exfiltration）不是資料洩漏（data leakage）。</strong><br><a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">第 8 篇</a>的資料洩漏，是<strong>答案不小心混進訓練資料</strong>，讓模型「考試作弊」、分數虛高；這篇的資料外洩，是<strong>資料被搬出公司</strong>，是資安事件。中文只差一個字，英文完全不同。</p>
</blockquote>



<h3 class="wp-block-heading">要認識的四個名詞</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>名詞</th><th>白話</th><th>金庫大樓比喻</th></tr></thead><tbody><tr><td>服務邊界（Service perimeter）</td><td>被保護的專案和服務的範圍</td><td>大樓的外牆</td></tr><tr><td>存取層級（Access level）</td><td>放行的條件，例如「從公司的 IP 位址來」</td><td>訪客名單</td></tr><tr><td>輸入／輸出規則（Ingress／Egress rules）</td><td>允許特定的人或資料「進來」或「出去」的例外</td><td>事先申請好的搬貨單</td></tr><tr><td>模擬測試模式（Dry run mode）</td><td>違規的請求只記錄、不阻擋，用來先試設定</td><td>保全先站崗觀察一週，只記錄不攔人</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>IP 位址</strong>是網路上的門牌號碼，每台連上網路的電腦都有一個。</p>



<h3 class="wp-block-heading">五個情境：哪些會被擋？</h3>



<p class="wp-block-paragraph">假設（教學用的情境）飲料店把會員資料（BigQuery）、訓練資料（Cloud Storage）、模型（Agent Platform）都放在專案 <code>ml-prod</code>，並把它放進服務邊界：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>情境</th><th>IAM 權限</th><th>VPC Service Controls</th></tr></thead><tbody><tr><td>1. 資料科學家從公司網路，用 Agent Platform 讀 BigQuery 會員表訓練模型</td><td>有</td><td>✅ 放行</td></tr><tr><td>2. 服務帳戶金鑰外流，駭客從自己的電腦讀會員表</td><td>有（金鑰是真的）</td><td>❌ 擋下：請求來自邊界外</td></tr><tr><td>3. 員工用 <code>bq</code> 指令（BigQuery 的指令列工具）把會員表複製到自己的私人專案</td><td>有</td><td>❌ 擋下：資料不能複製到邊界外</td></tr><tr><td>4. IAM 設錯，不小心把資料開放給所有人</td><td>設錯了</td><td>❌ 擋下：邊界外的人還是讀不到</td></tr><tr><td>5. 要把訓練好的模型交給合作的外送平台</td><td>有</td><td>預設擋下；寫一條<strong>輸出規則</strong>明確放行這一件</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">第 2～4 種，都是<a href="https://docs.cloud.google.com/vpc-service-controls/docs/overview">官方文件</a>列出的風險：偷來的憑證、內部人員或被入侵的程式搬資料、IAM 設定錯誤。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-04-vpc-service-controls.png" alt="VPC Service Controls 五個情境：邊界內用 Agent Platform 讀 BigQuery 放行；金鑰外流從外部存取、複製到私人專案、IAM 設錯都會被擋下；要交給合作夥伴就寫輸出規則" class="wp-image-12814" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-04-vpc-service-controls.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-04-vpc-service-controls-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-04-vpc-service-controls-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-04-vpc-service-controls-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">跟 IAM、防火牆差在哪</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>IAM</th><th>VPC Service Controls</th><th>防火牆規則</th></tr></thead><tbody><tr><td>管什麼</td><td>你是誰、能做什麼</td><td>從哪裡來、資料能往哪裡去</td><td>網路流量能不能進出虛擬機器</td></tr><tr><td>保護對象</td><td>所有 Google Cloud 資源</td><td>Google 代管的服務（BigQuery、Cloud Storage、Agent Platform……）</td><td>你網路裡的虛擬機器</td></tr><tr><td>比喻</td><td>員工識別證</td><td>大樓保全大門</td><td>每間辦公室門口的門禁</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>虛擬機器</strong>（VM）是在雲端上租來的一台電腦。防火牆怎麼設，可以看站上的<a href="https://dongdonggcp.com/2026/03/25/gcp-firewall-rules-how-to-setup/">防火牆規則教學</a>。</p>



<h3 class="wp-block-heading">兩個限制</h3>


<ul class="wp-block-list">
<li><strong>要有「組織」才能用</strong>：VPC Service Controls 的設定是掛在 Google Cloud 的<strong>組織</strong>（Organization，公司層級的最上層，底下才是資料夾和專案）底下。用個人 Gmail 開的帳號沒有組織，就沒辦法設。組織是什麼，可以看<a href="https://dongdonggcp.com/2026/04/22/gcp-organization-policy-introduction/">Organization Policy 那篇</a></li>

<li><strong>主要管「資料」，不保證管住「中繼資料」</strong>：<a href="https://docs.cloud.google.com/vpc-service-controls/docs/overview">官方文件</a>說，它不是設計來全面控管<strong>中繼資料</strong>（描述資料的資料，例如 Cloud Storage 值區的名稱）的移動，這部分要靠 IAM</li>
</ul>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">PMLE 第 6.1 節明寫要防止「<strong>資料外洩</strong>」（data exfiltration）。題目出現「防止資料被複製到專案外」「憑證外流也不能讓資料被讀走」，答案幾乎都是 VPC Service Controls。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">三招一張表比完</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>DLP 去識別化</th><th>聯邦學習</th><th>VPC Service Controls</th></tr></thead><tbody><tr><td>保護什麼</td><td>資料<strong>內容</strong>裡的個資</td><td>資料的<strong>位置</strong>：不集中</td><td>資料的<strong>出口</strong>：不外流</td></tr><tr><td>一句話比喻</td><td>打馬賽克</td><td>店長交心得、不交帳本</td><td>大樓保全大門</td></tr><tr><td>什麼時候用</td><td>訓練資料裡有個資</td><td>資料不能或不想集中</td><td>雲端上的資料、模型怕被搬走</td></tr><tr><td>要小心</td><td>準識別資料組合起來還是認得出人</td><td>更新也可能洩漏，要搭配安全聚合、差分隱私</td><td>不能取代 IAM、要有組織</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">三招不是三選一。實務上常常一起用：先用 DLP 把訓練資料遮好，再把整個專案放進服務邊界。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">在 GCP 上怎麼做</h2>



<p class="wp-block-paragraph"><strong>GCP（Google Cloud Platform）</strong> 是 Google 的雲端服務，白話說就是<strong>租用 Google 機房裡的電腦和工具</strong>。</p>



<h3 class="wp-block-heading">1. Sensitive Data Protection：先找、再遮、再量</h3>



<p class="wp-block-paragraph">依照<a href="https://docs.cloud.google.com/sensitive-data-protection/docs/sensitive-data-protection-overview">官方總覽</a>，它有四種服務：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>服務</th><th>白話</th><th>適合</th></tr></thead><tbody><tr><td>探索（Discovery）</td><td>定期掃整個組織、資料夾或專案，產生「資料剖析」，告訴你哪些表、哪些欄位有個資</td><td>不知道個資藏在哪</td></tr><tr><td>檢查（Inspection）</td><td>對單一資料表或值區做深度掃描，列出每一筆個資的確切位置</td><td>客服留言這種「偶爾夾帶個資」的文字</td></tr><tr><td>去識別化（De-identification）</td><td>用前面那些方法把個資遮掉</td><td>訓練前的處理</td></tr><tr><td>風險分析（Risk analysis）</td><td>算 BigQuery 資料表的 k 值等指標</td><td>確認遮得夠不夠</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>值區</strong>（Bucket）是 Cloud Storage 裡裝檔案的容器，像雲端上的一個資料夾。</p>



<p class="wp-block-paragraph">放到機器學習的流程裡，順序是這樣：</p>


<ol class="wp-block-list">
<li><strong>探索</strong>：找出哪些 BigQuery 資料表有個資</li>

<li><strong>鎖住原始資料</strong>：用 IAM 只讓少數人讀原始資料表</li>

<li><strong>去識別化</strong>：產生一份遮好的訓練用資料</li>

<li><strong>風險分析</strong>：算 k 值，太小就把區間切粗，或拿掉太少見的資料</li>

<li><strong>訓練</strong>：資料團隊只用遮好的那一份，在 BigQuery ML（用 SQL 在 BigQuery 裡訓練模型）或 Agent Platform 上訓練</li>
</ol>



<p class="wp-block-paragraph">不想寫程式的話，<a href="https://docs.cloud.google.com/bigquery/docs/scan-with-dlp">BigQuery 的網頁主控台</a>也可以直接對單一資料表發起檢查。</p>



<h4 class="wp-block-heading">用 DLP API 遮掉客服留言裡的個資</h4>



<p class="wp-block-paragraph">依照<a href="https://docs.cloud.google.com/sensitive-data-protection/docs/deidentify-sensitive-data">去識別化文件</a>的格式，先把要求寫成一個 <code>request.json</code> 檔（教學用的範例）：</p>



<pre class="wp-block-code"><code>{
  "item": {
    "value": "我的手機是 0912-345-678，卡號 4111 1111 1111 1111 被重複扣款"
  },
  "inspectConfig": {
    "infoTypes": [
      {"name": "PHONE_NUMBER"},
      {"name": "CREDIT_CARD_NUMBER"},
      {"name": "TAIWAN_ID_NUMBER"}
    ]
  },
  "deidentifyConfig": {
    "infoTypeTransformations": {
      "transformations": [
        {"primitiveTransformation": {"replaceWithInfoTypeConfig": {}}}
      ]
    }
  }
}</code></pre>



<p class="wp-block-paragraph">再用一行指令送出去：</p>



<pre class="wp-block-code"><code>curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json; charset=utf-8" \
  -d @request.json \
  "https://dlp.googleapis.com/v2/projects/PROJECT_ID/content:deidentify"</code></pre>



<p class="wp-block-paragraph">逐行翻成白話：</p>


<ul class="wp-block-list">
<li><code>item.value</code>：要檢查的文字，這裡是一則客服留言</li>

<li><code>inspectConfig.infoTypes</code>：要找哪幾種個資。官方文件提醒<strong>要明確列出來</strong>，沒寫的話會用一組預設的類型去掃，可能多花時間</li>

<li><code>replaceWithInfoTypeConfig</code>：找到的個資，換成它的類型名稱</li>

<li><code>content:deidentify</code>：DLP API 的「去識別化」功能</li>

<li><code>curl</code>：在終端機（打指令的視窗）送出網路請求的工具</li>

<li><code>gcloud auth print-access-token</code>：gcloud 是 Google Cloud 的指令列工具，這段是用你登入的身分，拿一張臨時的通行證</li>

<li><code>PROJECT_ID</code>：換成你的專案 ID</li>
</ul>



<p class="wp-block-paragraph">偵測到的話，回傳的文字會變成：</p>



<pre class="wp-block-code"><code>我的手機是 [PHONE_NUMBER]，卡號 [CREDIT_CARD_NUMBER] 被重複扣款</code></pre>



<p class="wp-block-paragraph">模型照樣學得到「客人留了電話、在抱怨重複扣款」，但學不到任何一個真的號碼。</p>



<h3 class="wp-block-heading">2. 聯邦學習：在 GKE 上用 TensorFlow Federated</h3>



<p class="wp-block-paragraph">Google Cloud 架構中心有一份<a href="https://docs.cloud.google.com/architecture/cross-silo-cross-device-federated-learning-google-cloud">參考架構</a>，教你自己搭聯邦學習平台，主要用到兩個東西：</p>


<ul class="wp-block-list">
<li><strong>GKE</strong>（Google Kubernetes Engine）：Google 代管的 Kubernetes（一套管理大量容器的開源系統），用來大量執行<strong>容器</strong>（把程式和它需要的環境打包在一起的小箱子）。不熟的話可以先看<a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼</a></li>

<li><strong>TensorFlow Federated（TFF）</strong>：Google 開源的聯邦學習程式工具包</li>
</ul>



<p class="wp-block-paragraph">跨裝置的情境，架構裡還要加上 <strong>FCP</strong>（Federated Compute Platform）的服務，負責協調每一輪由哪些手機參與。</p>



<p class="wp-block-paragraph">TFF 的寫法長這樣（依照 <a href="https://www.tensorflow.org/federated">TFF 官方範例</a>簡化）：</p>



<pre class="wp-block-code"><code>import tensorflow_federated as tff

# 建立「加權聯邦平均」的訓練流程
trainer = tff.learning.algorithms.build_weighted_fed_avg(
    model_fn,
    client_optimizer_fn=tff.learning.optimizers.build_sgdm(learning_rate=0.02))

state = trainer.initialize()                  # 伺服器準備第 1 版模型
for i in range(10):                           # 跑 10 輪
    result = trainer.next(state, phone_data)  # 發下去、各自訓練、加權平均
    state = result.state                      # 換成新版模型</code></pre>



<p class="wp-block-paragraph">逐行翻成白話：</p>


<ul class="wp-block-list">
<li><code>build_weighted_fed_avg</code>：weighted 是「加權」，fed_avg 是「聯邦平均」，就是前面算過的那個公式</li>

<li><code>model_fn</code>：告訴它模型長什麼樣子</li>

<li><code>client_optimizer_fn</code>：每支手機在自己身上怎麼訓練；<code>learning_rate</code>（學習率，第 3 篇的超參數）是每次調整權重的幅度</li>

<li><code>trainer.next(...)</code>：跑一輪前面說的四個步驟</li>

<li><code>phone_data</code>：各支手機的資料。練習的時候，是用程式在一台電腦上模擬很多支手機</li>
</ul>



<h3 class="wp-block-heading">3. VPC Service Controls：先模擬、再上鎖</h3>



<p class="wp-block-paragraph">要保護機器學習的專案，邊界裡通常會放這三個服務：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>服務名稱</th><th>是什麼</th></tr></thead><tbody><tr><td><code>bigquery.googleapis.com</code></td><td>BigQuery</td></tr><tr><td><code>storage.googleapis.com</code></td><td>Cloud Storage</td></tr><tr><td><code>aiplatform.googleapis.com</code></td><td>Agent Platform（API 名稱沿用舊的 aiplatform）</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">設定指令（教學用的範例，依照 <a href="https://docs.cloud.google.com/sdk/gcloud/reference/access-context-manager/perimeters/dry-run/create">gcloud 官方說明</a>）：</p>



<pre class="wp-block-code"><code># 第 1 步：先用模擬測試模式建立邊界（違規只記錄、不阻擋）
gcloud access-context-manager perimeters dry-run create ml_perimeter \
  --perimeter-title="ml-perimeter" \
  --perimeter-type="regular" \
  --perimeter-resources="projects/123456789012" \
  --perimeter-restricted-services="bigquery.googleapis.com,storage.googleapis.com,aiplatform.googleapis.com" \
  --policy=POLICY_ID

# 第 2 步：看過記錄、確定不會擋到正常工作，再正式生效
gcloud access-context-manager perimeters dry-run enforce ml_perimeter \
  --policy=POLICY_ID</code></pre>



<p class="wp-block-paragraph">逐行翻成白話：</p>


<ul class="wp-block-list">
<li><code>access-context-manager</code>：Access Context Manager（存取情境管理員），管理服務邊界和存取層級的工具</li>

<li><code>dry-run create</code>：用<strong>模擬測試模式</strong>建立一道新的邊界</li>

<li><code>--perimeter-resources</code>：要放進邊界的專案。要填專案「編號」（一串數字），不是專案名稱</li>

<li><code>--perimeter-restricted-services</code>：要保護的服務，就是上面那張表</li>

<li><code>--policy</code>：組織的存取政策編號</li>

<li><code>dry-run enforce</code>：把模擬的設定轉成<strong>正式生效</strong></li>
</ul>



<p class="wp-block-paragraph">依照 <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/general/vpc-service-controls">Agent Platform 的官方文件</a>，放進邊界之後，這些東西都不能離開邊界：</p>


<ul class="wp-block-list">
<li>AutoML（自動幫你挑模型的功能）或自訂模型的訓練資料</li>

<li>你建立的模型</li>

<li>線上推論（即時一筆一筆預測）的請求、批次推論（一次預測一大批）的結果</li>

<li>Gemini 模型</li>
</ul>



<p class="wp-block-paragraph">同一份文件也提醒：把 Agent Platform 放進邊界後，<strong>從網際網路存取（包括用網頁主控台）預設都會被擋</strong>，除非列進允許的名單。Pipelines、自訂訓練、私人端點（只在內部網路開放的預測網址）這幾個功能，還要多做網路設定。這就是為什麼一定要<strong>先模擬、再上鎖</strong>。</p>



<h3 class="wp-block-heading">4. 生成式 AI 的新考點：Model Armor</h3>



<p class="wp-block-paragraph"><strong>Model Armor</strong> 是大型語言模型（LLM，例如 Gemini）的<strong>安檢門</strong>。依照<a href="https://docs.cloud.google.com/model-armor/overview">官方文件</a>，它在提示詞（使用者打進去的問題）送進模型前檢查一次，模型的回答送出去前再檢查一次。</p>



<p class="wp-block-paragraph">它能做的事：</p>


<ul class="wp-block-list">
<li>用 Sensitive Data Protection <strong>找出並遮掉</strong>提示詞和回答裡的個資</li>

<li>擋下<strong>提示詞注入</strong>（Prompt injection，故意寫一段話騙模型不守規矩）</li>

<li>過濾仇恨、騷擾這類有害內容</li>
</ul>



<p class="wp-block-paragraph">飲料店的客服機器人就用得到：客人打「我的卡號是 4111…，幫我查扣款」，Model Armor 先把卡號遮掉，才交給 Gemini。</p>



<h3 class="wp-block-heading">Agent Platform 改名了</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>舊題庫可能還會看到 Vertex AI，現在叫 Gemini Enterprise Agent Platform（簡稱 Agent Platform）。</strong><br>Google Cloud 在 2026 年 4 月 22 日正式改名（<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/vertex-ai-name-changes">官方對照表</a>），2026 年 6 月 1 日起的 PMLE 考試指南也全面用新名稱。</p>
</blockquote>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>舊名稱（舊題庫常見）</th><th>現在的名稱</th><th>跟這篇的關係</th></tr></thead><tbody><tr><td>Cloud DLP（DLP API）</td><td>Sensitive Data Protection（API 仍叫 Cloud Data Loss Prevention API）</td><td>找出、遮掉個資</td></tr><tr><td>Vertex AI</td><td>Gemini Enterprise Agent Platform</td><td>訓練、部署模型的平台，可以放進服務邊界</td></tr><tr><td>Vertex AI Workbench</td><td>Gemini Enterprise Agent Platform Workbench</td><td>網頁版的程式筆記本，考試指南 2.2 要你會做安全設定</td></tr><tr><td>Vertex AI Pipelines</td><td>Gemini Enterprise Agent Platform Pipelines</td><td>放進服務邊界要多做網路設定</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">考試會怎麼考</h2>



<p class="wp-block-paragraph">Google Cloud <strong>Professional Machine Learning Engineer（PMLE，專業機器學習工程師）</strong> 證照，2026 年 6 月 1 日起的<a href="https://services.google.com/fh/files/misc/professional_machine_learning_engineer_exam_guide_english_new.pdf">官方考試指南</a>裡，這篇的內容對應到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考試區塊</th><th>跟這篇有關的項目</th></tr></thead><tbody><tr><td>第 2 區：跨團隊管理資料與模型（約 16%）</td><td>2.1 <strong>確保資料隱私、處理敏感資訊</strong>（例如個資）；2.2 設定和使用筆記本環境時，套用<strong>協作與安全的最佳做法</strong></td></tr><tr><td>第 6 區：監控 AI 方案（約 13%）</td><td>6.1 防止資料或模型被<strong>無意間利用或外洩</strong>（例如資料外洩、惡意提示詞、把敏感資料分享給 LLM），並選用 Regex、安全過濾器、<strong>Model Armor</strong> 等工具</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>Regex</strong>（正規表示式）是用規則比對文字的方法，例如「連續 16 位數字」就可能是卡號。</p>



<p class="wp-block-paragraph">2.2 的<strong>筆記本</strong>（Notebook）是在網頁上邊寫程式、邊看結果的工具，例如 Agent Platform Workbench。它也可以放進服務邊界，跟這篇的 VPC Service Controls 是同一套做法。</p>



<p class="wp-block-paragraph">聯邦學習在新版指南裡沒有被點名，但在舊題庫很常見，看到「資料不能離開裝置」還是要認得出來。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-05-exam-keywords.png" alt="PMLE 考試關鍵字：個資要遮掉想到 Sensitive Data Protection，之後要還原想到 AES-SIV，格式不能變想到 FPE，資料不能離開手機想到聯邦學習，防止資料被複製出去想到 VPC Service Controls，提示詞有個資想到 Model Armor" class="wp-image-12815" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-05-exam-keywords.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-05-exam-keywords-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-05-exam-keywords-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml12-05-exam-keywords-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目出現的關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「PII」「個資」「信用卡號」「身分證」「去識別化」</td><td><strong>Sensitive Data Protection</strong>（DLP API）</td></tr><tr><td>「之後要還原」「要能 JOIN」「同一個人代號要一樣」</td><td><strong>確定性加密（AES-SIV）</strong>令牌化</td></tr><tr><td>「舊系統」「格式、長度不能變」</td><td><strong>FPE</strong>（格式保留加密）</td></tr><tr><td>「不需要還原」</td><td><strong>加密雜湊</strong>，或直接刪除</td></tr><tr><td>「生日、郵遞區號組合起來認得出人」「重新識別風險」</td><td><strong>分桶</strong>＋<strong>k-匿名風險分析</strong></td></tr><tr><td>「資料不能離開裝置」「指紋」「鍵盤」「醫院之間不能交換資料」</td><td><strong>聯邦學習</strong></td></tr><tr><td>「防止資料被複製到專案外」「金鑰外流」「data exfiltration」</td><td><strong>VPC Service Controls</strong></td></tr><tr><td>「先確認不會影響現有服務」</td><td>VPC Service Controls 的<strong>模擬測試模式</strong>（dry run）</td></tr><tr><td>「提示詞或回答裡有個資」「提示詞注入」</td><td><strong>Model Armor</strong></td></tr><tr><td>「誰可以讀這份資料」</td><td><strong>IAM</strong>（VPC Service Controls 不能取代它）</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">六個常見陷阱</h3>


<ol class="wp-block-list">
<li><strong>以為 IAM 設好就夠了</strong>：IAM 管「你是誰」，金鑰外流、有權限的人亂搬，要靠 VPC Service Controls 再加一層</li>

<li><strong>只刪姓名就說去識別化完成</strong>：年齡、行政區這類準識別資料組合起來，還是認得出人，要做風險分析</li>

<li><strong>預設就選 FPE</strong>：官方建議沒有格式需求時，用 AES-SIV</li>

<li><strong>雜湊之後還想還原</strong>：雜湊是單向的，要還原只能選可逆的加密</li>

<li><strong>以為聯邦學習什麼都不會洩漏</strong>：模型更新也可能透露資訊，要搭配安全聚合、差分隱私</li>

<li><strong>把資料外洩當成資料洩漏</strong>：exfiltration 是資料被搬走（資安），leakage 是答案混進訓練資料（第 8 篇）</li>
</ol>



<h3 class="wp-block-heading">練習情境（自己出的練習，不是真實考題）</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">一家連鎖飲料店想用客服留言訓練「客訴分類」模型。留言存在 BigQuery，裡面偶爾有客人自己打的手機號碼和信用卡號。模型只需要知道客訴的類型，不需要知道是誰。應該怎麼做？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「留言裡偶爾有個資」→ 用 Sensitive Data Protection <strong>檢查</strong>，再<strong>去識別化</strong></li>

<li>「不需要知道是誰」→ 不用還原，直接<strong>取代成類型名稱</strong>就好，不必用令牌化</li>

<li>原始留言表用 IAM 限制只有少數人能讀，資料團隊只拿遮好的那一份</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">同一家店的 App 想做「猜你想點」，最有用的是客人在手機上滑菜單的紀錄，但法務要求這些紀錄不能離開手機。App 有幾十萬名使用者，同一時間只有一部分在線上。應該怎麼做？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「紀錄不能離開手機」→ <strong>聯邦學習</strong></li>

<li>「幾十萬名使用者、只有一部分在線上」→ <strong>跨裝置</strong>聯邦學習，要有服務負責挑每一輪參與的手機（GKE＋TFF＋FCP）</li>

<li>再加上<strong>安全聚合</strong>或<strong>差分隱私</strong>，避免從模型更新反推回個人</li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">資料科學團隊在 Agent Platform 上用 BigQuery 的會員表訓練模型。資安團隊擔心有人把會員表複製到公司以外的專案，也擔心服務帳戶金鑰外流。但資料團隊不希望設定一上線，工作就被突然擋住。應該怎麼做？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「複製到公司以外」「金鑰外流」→ <strong>VPC Service Controls</strong>，把專案放進服務邊界，保護 <code>bigquery</code>、<code>storage</code>、<code>aiplatform</code> 三個服務</li>

<li>「不希望突然被擋住」→ 先用<strong>模擬測試模式</strong>看記錄，確定沒問題再正式生效</li>

<li>IAM 照樣要設好，只給每個人需要的權限</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">機器學習的資料隱私要注意哪些事？</h3>



<p class="wp-block-paragraph">主要有三件事：訓練資料裡的個資要先找出來遮掉（DLP 去識別化）；資料不能集中時，讓模型到資料那裡學（聯邦學習）；雲端上的資料和模型，要防止被搬到外面（VPC Service Controls）。另外，只刪姓名不夠，年齡、行政區這類資料組合起來還是可能認出人，要做風險分析。</p>



<h3 class="wp-block-heading">DLP 是什麼？跟 Sensitive Data Protection 一樣嗎？</h3>



<p class="wp-block-paragraph">DLP 是 Data Loss Prevention（資料外洩防護）的縮寫，在 Google Cloud 上是一組能自動找出並遮掉個資的 API。Cloud DLP 從 2023 年起歸到 Sensitive Data Protection 這個產品底下，API 名稱仍叫 Cloud Data Loss Prevention API。舊題庫寫 Cloud DLP、新文件寫 Sensitive Data Protection，指的是同一套東西。</p>



<h3 class="wp-block-heading">去識別化、遮罩、令牌化、加密差在哪？</h3>



<p class="wp-block-paragraph">去識別化是總稱，指把資料改成認不出是誰。遮罩是把部分字元換成 # 或 * 這類符號，例如手機只留末三碼；令牌化是把真正的值換成一個代號，像衣帽間的號碼牌；加密是用金鑰把資料鎖成亂碼。DLP 的令牌化就是用加密做的，所以有金鑰的人可以還原，遮罩和刪除則還原不回來。</p>



<h3 class="wp-block-heading">FPE 格式保留加密是什麼？什麼時候該用？</h3>



<p class="wp-block-paragraph">FPE 是加密後字元種類和長度都不變的加密方式，例如 16 位數的卡號加密後還是 16 位數字，主要是給規定格式不能變的舊系統用。官方文件提醒，除非一定要保留格式和長度，否則不要用 FPE，因為它可能很慢、限制多，安全保證也比確定性加密（AES-SIV）少。</p>



<h3 class="wp-block-heading">去識別化之後就安全了嗎？k-匿名是什麼？</h3>



<p class="wp-block-paragraph">不一定。年齡、行政區這類準識別資料組合起來，還是可能認出人。k-匿名是一種檢查方式：準識別資料完全一樣的每一組裡，人數最少的那組有 k 個人，被認出來的機率最多就是 1 除以 k。例如 k 等於 4，最多 25%。k 越大越安全，但資料也越模糊。</p>



<h3 class="wp-block-heading">聯邦學習是什麼？資料真的不會離開手機嗎？</h3>



<p class="wp-block-paragraph">聯邦學習是讓模型到每支手機上用本機資料訓練，手機只把模型更新（學完之後變動的數字）加密傳回伺服器，伺服器再依資料筆數加權平均成新版模型。原始資料不會上傳，但更新仍可能透露一點資訊，所以通常會搭配安全聚合和差分隱私，讓伺服器只看得到平均、模型也不會記住個人。</p>



<h3 class="wp-block-heading">聯邦學習和分散式訓練差在哪？</h3>



<p class="wp-block-paragraph">分散式訓練是把已經集中在資料中心的資料，分給很多台機器一起算，目的是算得更快，資料都在你的掌控之下。聯邦學習的資料從頭到尾留在使用者的手機或各機構裡，目的是保護隱私，裝置數量多、網路慢、而且不一定隨時在線上，所以需要聯邦平均這類特別的演算法。</p>



<h3 class="wp-block-heading">VPC Service Controls 是什麼？跟 IAM、防火牆差在哪？</h3>



<p class="wp-block-paragraph">VPC Service Controls 是在 BigQuery、Cloud Storage、Agent Platform 這些 Google 代管服務外面畫一道服務邊界，邊界外的請求會被擋下，資料也不能被複製到邊界外。IAM 管的是「你是誰、能做什麼」，防火牆管的是虛擬機器的網路流量，VPC Service Controls 管的是「從哪裡來、資料往哪裡去」。官方建議跟 IAM 一起用。</p>



<h3 class="wp-block-heading">個人 Gmail 帳號可以用 VPC Service Controls 嗎？</h3>



<p class="wp-block-paragraph">不行。VPC Service Controls 的設定要掛在 Google Cloud 的組織（Organization）底下，組織是公司層級的最上層資源。用個人 Gmail 開的 Google Cloud 帳號沒有組織，所以沒辦法建立服務邊界。</p>



<h3 class="wp-block-heading">資料外洩和資料洩漏一樣嗎？</h3>



<p class="wp-block-paragraph">不一樣。資料外洩（data exfiltration）是資料被搬出公司，是資安事件，用 VPC Service Controls 這類工具防範。資料洩漏（data leakage）是機器學習的問題，指答案不小心混進訓練資料，讓模型分數虛高。中文只差一個字，考試的英文用字完全不同。</p>



<h3 class="wp-block-heading">Model Armor 是什麼？跟 DLP 有什麼關係？</h3>



<p class="wp-block-paragraph">Model Armor 是大型語言模型的安檢門，在提示詞送進模型前、模型回答送出去前各檢查一次。它會用 Sensitive Data Protection（也就是 DLP）找出並遮掉個資，也能擋下提示詞注入、過濾有害內容。PMLE 新版考試指南第 6.1 節有直接點名 Model Armor。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>個資不只姓名</strong>：準識別資料（年齡、行政區）組合起來也能認出人；台灣個資法也寫「直接或間接」識別</li>

<li><strong>DLP 去識別化</strong>：Cloud DLP 現在叫 <strong>Sensitive Data Protection</strong>；刪除、遮罩、令牌化、分桶擇一；要還原選 <strong>AES-SIV</strong>，格式不能變才用 FPE；用 <strong>k-匿名</strong>量化被認出的風險</li>

<li><strong>聯邦學習</strong>：資料留在手機，只傳模型更新，伺服器依筆數<strong>加權平均</strong>；要再搭配安全聚合、差分隱私</li>

<li><strong>VPC Service Controls</strong>：在 Google 代管服務外畫<strong>服務邊界</strong>，擋外部存取和資料外洩；先用<strong>模擬測試模式</strong>，不能取代 IAM，要有組織才能用</li>

<li>GCP 上：<strong>Vertex AI 已改名為 Gemini Enterprise Agent Platform</strong>；生成式 AI 的提示詞用 <strong>Model Armor</strong> 把關</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/20/types-of-machine-learning-supervised-unsupervised-reinforcement/">機器學習有哪幾種？監督式、非監督式、強化學習一次看懂</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/10/20/classification-vs-regression-mae-rmse/">分類和迴歸差在哪？一個例子搞懂，附 MAE、RMSE 計算</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">特徵、標籤、超參數是什麼？機器學習 5 個必懂名詞</a></li>

<li>第 4 篇：<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">訓練集、驗證集、測試集怎麼切？時間序列為什麼不能亂切</a></li>

<li>第 5 篇：<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">混淆矩陣是什麼？用快篩搞懂準確率、精確率、召回率、F1</a></li>

<li>第 6 篇：<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">ROC 曲線和 AUC 怎麼看？門檻怎麼調、AUC-PR 差在哪</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">過度擬合是什麼？正則化、Dropout、提前停止 3 招解決</a></li>

<li>第 8 篇：<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">資料洩漏是什麼？模型考試作弊的 3 種常見情況</a></li>

<li>第 9 篇：<a href="https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/">類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</a></li>

<li>第 10 篇：<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">資料前處理怎麼做？標準化、遺失值、高基數類別</a></li>

<li>上一篇：第 11 篇：<a href="https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/">特徵工程是什麼？特徵交叉、詞嵌入、資料增強一次看懂</a></li>

<li>下一篇：第 13 篇：<a href="https://dongdonggcp.com/2026/10/25/tfrecords-tf-data-prefetch-input-pipeline/">訓練資料讀太慢？TFRecords、tf.data 與 prefetch 加速</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2024/07/17/gcp-common-security-service/">雲端的資訊安全防禦縱深，常用 GCP 資安服務介紹</a></li>

<li><a href="https://dongdonggcp.com/2025/04/14/tips-when-developing-with-gcp-service-account/">使用 GCP Service Account 開發程式的小技巧和注意事項</a></li>

<li><a href="https://dongdonggcp.com/2026/04/22/gcp-organization-policy-introduction/">GCP Organization Policy 完全攻略：Google Cloud 安全工程師必備知識</a></li>

<li><a href="https://dongdonggcp.com/2024/03/18/gcp-9-security-threats-and-how-to-resolve/">GCP 9 大資訊安全威脅與因應方案</a></li>

<li><a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼？白話解釋 + 判斷你是否真的需要它</a></li>

<li><a href="https://dongdonggcp.com/2026/03/25/gcp-firewall-rules-how-to-setup/">GCP 防火牆規則如何設定？5 步驟完整攻略與實戰技巧</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">資料整理好、加工好，也要保護好，模型才能放心上線。如果你想有系統地從雲端基礎一路學到在 GCP 上動手做機器學習，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "機器學習的資料隱私要注意哪些事？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "主要有三件事：訓練資料裡的個資要先找出來遮掉（DLP 去識別化）；資料不能集中時，讓模型到資料那裡學（聯邦學習）；雲端上的資料和模型，要防止被搬到外面（VPC Service Controls）。另外，只刪姓名不夠，年齡、行政區這類資料組合起來還是可能認出人，要做風險分析。"
      }
    },
    {
      "@type": "Question",
      "name": "DLP 是什麼？跟 Sensitive Data Protection 一樣嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "DLP 是 Data Loss Prevention（資料外洩防護）的縮寫，在 Google Cloud 上是一組能自動找出並遮掉個資的 API。Cloud DLP 從 2023 年起歸到 Sensitive Data Protection 這個產品底下，API 名稱仍叫 Cloud Data Loss Prevention API。舊題庫寫 Cloud DLP、新文件寫 Sensitive Data Protection，指的是同一套東西。"
      }
    },
    {
      "@type": "Question",
      "name": "去識別化、遮罩、令牌化、加密差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "去識別化是總稱，指把資料改成認不出是誰。遮罩是把部分字元換成 # 或 * 這類符號，例如手機只留末三碼；令牌化是把真正的值換成一個代號，像衣帽間的號碼牌；加密是用金鑰把資料鎖成亂碼。DLP 的令牌化就是用加密做的，所以有金鑰的人可以還原，遮罩和刪除則還原不回來。"
      }
    },
    {
      "@type": "Question",
      "name": "FPE 格式保留加密是什麼？什麼時候該用？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "FPE 是加密後字元種類和長度都不變的加密方式，例如 16 位數的卡號加密後還是 16 位數字，主要是給規定格式不能變的舊系統用。官方文件提醒，除非一定要保留格式和長度，否則不要用 FPE，因為它可能很慢、限制多，安全保證也比確定性加密（AES-SIV）少。"
      }
    },
    {
      "@type": "Question",
      "name": "去識別化之後就安全了嗎？k-匿名是什麼？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不一定。年齡、行政區這類準識別資料組合起來，還是可能認出人。k-匿名是一種檢查方式：準識別資料完全一樣的每一組裡，人數最少的那組有 k 個人，被認出來的機率最多就是 1 除以 k。例如 k 等於 4，最多 25%。k 越大越安全，但資料也越模糊。"
      }
    },
    {
      "@type": "Question",
      "name": "聯邦學習是什麼？資料真的不會離開手機嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "聯邦學習是讓模型到每支手機上用本機資料訓練，手機只把模型更新（學完之後變動的數字）加密傳回伺服器，伺服器再依資料筆數加權平均成新版模型。原始資料不會上傳，但更新仍可能透露一點資訊，所以通常會搭配安全聚合和差分隱私，讓伺服器只看得到平均、模型也不會記住個人。"
      }
    },
    {
      "@type": "Question",
      "name": "聯邦學習和分散式訓練差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "分散式訓練是把已經集中在資料中心的資料，分給很多台機器一起算，目的是算得更快，資料都在你的掌控之下。聯邦學習的資料從頭到尾留在使用者的手機或各機構裡，目的是保護隱私，裝置數量多、網路慢、而且不一定隨時在線上，所以需要聯邦平均這類特別的演算法。"
      }
    },
    {
      "@type": "Question",
      "name": "VPC Service Controls 是什麼？跟 IAM、防火牆差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "VPC Service Controls 是在 BigQuery、Cloud Storage、Agent Platform 這些 Google 代管服務外面畫一道服務邊界，邊界外的請求會被擋下，資料也不能被複製到邊界外。IAM 管的是「你是誰、能做什麼」，防火牆管的是虛擬機器的網路流量，VPC Service Controls 管的是「從哪裡來、資料往哪裡去」。官方建議跟 IAM 一起用。"
      }
    },
    {
      "@type": "Question",
      "name": "個人 Gmail 帳號可以用 VPC Service Controls 嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不行。VPC Service Controls 的設定要掛在 Google Cloud 的組織（Organization）底下，組織是公司層級的最上層資源。用個人 Gmail 開的 Google Cloud 帳號沒有組織，所以沒辦法建立服務邊界。"
      }
    },
    {
      "@type": "Question",
      "name": "資料外洩和資料洩漏一樣嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不一樣。資料外洩（data exfiltration）是資料被搬出公司，是資安事件，用 VPC Service Controls 這類工具防範。資料洩漏（data leakage）是機器學習的問題，指答案不小心混進訓練資料，讓模型分數虛高。中文只差一個字，考試的英文用字完全不同。"
      }
    },
    {
      "@type": "Question",
      "name": "Model Armor 是什麼？跟 DLP 有什麼關係？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Model Armor 是大型語言模型的安檢門，在提示詞送進模型前、模型回答送出去前各檢查一次。它會用 Sensitive Data Protection（也就是 DLP）找出並遮掉個資，也能擋下提示詞注入、過濾有害內容。PMLE 新版考試指南第 6.1 節有直接點名 Model Armor。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/10/25/machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls/">機器學習的資料隱私怎麼保護？DLP、聯邦學習、VPC Service Controls</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/10/25/machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>特徵工程是什麼？特徵交叉、詞嵌入、資料增強一次看懂</title>
		<link>https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=feature-engineering-feature-cross-embedding-data-augmentation</link>
					<comments>https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 25 Oct 2026 05:40:00 +0000</pubDate>
				<category><![CDATA[AI 和機器學習]]></category>
		<category><![CDATA[證照考試]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[BigQuery]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[PMLE]]></category>
		<category><![CDATA[Vertex AI]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[生成式 AI]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=12807</guid>

					<description><![CDATA[<p>特徵工程是什麼？用連鎖飲料店算給你看：特徵交叉讓模型學到晴天下午爆單、詞嵌入算出哪杯最像珍奶、資料增強把 500 張照片變 6,000 張，附 BigQuery ML 寫法與 PMLE 考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/">特徵工程是什麼？特徵交叉、詞嵌入、資料增強一次看懂</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>特徵工程是什麼？就是把原始資料加工成更好用的線索：把特徵組合起來、把文字變成有意義的數字、把少量資料變多。</strong></p>



<p class="wp-block-paragraph">上一篇把資料洗乾淨、切好，這篇要教你怎麼「加工」。一樣用有 2,000 間分店的連鎖飲料店當例子，一次處理三個任務：</p>


<ul class="wp-block-list">
<li>預測每小時會賣幾杯冰飲 → <strong>特徵交叉</strong></li>

<li>客人打「想喝有奶味的」，就找到口味相近的飲料 → <strong>詞嵌入</strong></li>

<li>拍照辨識是哪一款飲料，但照片很少 → <strong>資料增強</strong></li>
</ul>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-01-overview.png" alt="特徵工程是什麼：特徵交叉把天氣和時段合起來看，詞嵌入讓口味相近的飲料靠在一起，資料增強把 500 張照片變成 6,000 張" class="wp-image-12802" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-01-overview.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-01-overview-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-01-overview-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-01-overview-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>特徵做得好，比模型選得好更重要</strong>：<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">第 3 篇</a>說過，模型是靠特徵（線索）在判斷。線索給得好，簡單的模型也能很準</li>

<li><strong>簡單的模型學不會「組合效果」</strong>：「晴天的下午冰飲會爆單」這種要兩個條件一起看的規律，很多模型自己看不出來</li>

<li><strong>文字和圖片不能直接丟給模型</strong>：模型只看得懂數字，文字要變成「有意義的數字」，圖片太少還要想辦法變多</li>

<li><strong>證照必考</strong>：PMLE 考試指南第 1 區明列「用 BigQuery ML 做特徵工程」，第 2 區要你會處理表格、文字、圖片等不同資料，還有在 Feature Store 建立和整合特徵</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">先搞懂：特徵工程是什麼？</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>特徵工程</strong>（Feature Engineering）：用你對問題的了解，把原始資料<strong>加工、組合成新的特徵</strong>，讓模型更容易看出規律。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">把<strong>老店員的經驗，寫成模型看得到的欄位</strong>。</p>



<p class="wp-block-paragraph">做了十年的店員知道「晴天的下午，冰飲會爆單」。但資料表裡只有「天氣」「時段」兩欄，模型不一定知道這兩欄要合起來看。你幫它多做一欄「晴天下午」，它一下就學會了。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">「工程」兩個字，意思是像蓋房子一樣<strong>有方法地打造</strong>。早期的機器學習模型能力有限，準不準很大一部分看人幫它做了哪些特徵，所以「做特徵」變成一門專門的功夫。</p>



<p class="wp-block-paragraph">後來的<strong>神經網路</strong>（模仿人腦神經元連結、一層一層計算的模型）可以自己找出一部分特徵組合。<a href="https://developers.google.com/machine-learning/crash-course/categorical-data/feature-crosses">Google 速成課程</a>也說，神經網路能在訓練時自動找到有用的組合，只是<strong>比較花運算資源</strong>。</p>



<p class="wp-block-paragraph">所以特徵工程沒有消失，只是分工變了。站上 <a href="https://dongdonggcp.com/2025/08/12/what-is-end-to-end-training-in-machine-learning/">End-to-end Training</a> 那篇講的，就是「讓模型自己學特徵」的做法。</p>



<h3 class="wp-block-heading">跟資料前處理差在哪</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>資料前處理（第 10 篇）</th><th>特徵工程（這篇）</th></tr></thead><tbody><tr><td>比喻</td><td>洗菜、切菜</td><td>配菜、調味</td></tr><tr><td>在做什麼</td><td>把資料清乾淨、轉成數字、調到適合的大小</td><td>用原本的資料<strong>做出新的線索</strong></td></tr><tr><td>例子</td><td>縮放、補遺失值、One-hot</td><td>特徵交叉、嵌入、資料增強</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">兩者的界線不是很硬。Google 速成課程把「分桶」也算成特徵工程；嵌入在上一篇是「類別太多」的解法，在這篇是「讓相近的東西靠在一起」的方法。</p>



<p class="wp-block-paragraph">記住大方向就好：<strong>前處理讓資料能用，特徵工程讓資料好用</strong>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">1. 特徵交叉（Feature Cross）：把兩個線索合起來看</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>特徵交叉</strong>：把兩個（或更多）類別特徵<strong>組合成一個新特徵</strong>，每一種組合都是一個新的類別。例如「天氣 × 時段」，就變成「晴_下午」「雨_早上」這樣的組合。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像一張<strong>棋盤</strong>：橫的一排是天氣，直的一排是時段，每個交叉點是一格。</p>



<p class="wp-block-paragraph">模型可以為<strong>每一格</strong>各記一個數字，不用只記「晴天加幾分」「下午加幾分」。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">「交叉」就是棋盤的意思：兩張清單一橫一直排開，每個交叉點是一種組合，數學上叫<strong>笛卡兒積</strong>（Cartesian product）。</p>



<p class="wp-block-paragraph"><a href="https://developers.google.com/machine-learning/crash-course/categorical-data/feature-crosses">Google 速成課程</a>說，特徵交叉是為了讓<strong>線性模型</strong>也能處理「要組合起來才看得出來」的規律。</p>



<p class="wp-block-paragraph"><strong>線性模型</strong>就是<a href="https://dongdonggcp.com/2026/10/20/classification-vs-regression-mae-rmse/">第 2 篇</a>線性迴歸那一類：每個特徵配一個<strong>權重</strong>（代表這個特徵有多重要的分數），乘一乘再加起來。它簡單、快、好解釋，但<strong>只會加法</strong>。</p>



<h3 class="wp-block-heading">算一次給你看：為什麼加法不夠用</h3>



<p class="wp-block-paragraph">假設（教學用的數字）某間分店每小時平均賣出的冰飲杯數：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>早上</th><th>下午</th></tr></thead><tbody><tr><td>雨天</td><td>15 杯</td><td>25 杯</td></tr><tr><td>晴天</td><td>20 杯</td><td>80 杯</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">模型如果只有「天氣」「時段」兩個特徵，它要學一個數字叫「<strong>晴天多賣幾杯</strong>」。問題來了：</p>



<pre class="wp-block-code"><code>晴天多賣幾杯？
早上：20 − 15 = 5 杯
下午：80 − 25 = 55 杯</code></pre>



<p class="wp-block-paragraph">同一個「晴天加分」，不可能同時是 5 又是 55。這種「<strong>A 的效果要看 B 是什麼</strong>」的情況，叫做<strong>交互作用</strong>（Interaction）。</p>



<p class="wp-block-paragraph">只會加法的模型學不到交互作用。硬要用加法，算出來最好的折衷是<strong>四格都猜錯 12.5 杯</strong>。</p>



<p class="wp-block-paragraph">加上特徵交叉「天氣 × 時段」之後，四種組合各有自己的權重：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>組合</th><th>模型可以直接學到</th></tr></thead><tbody><tr><td>雨_早上</td><td>15 杯</td></tr><tr><td>雨_下午</td><td>25 杯</td></tr><tr><td>晴_早上</td><td>20 杯</td></tr><tr><td>晴_下午</td><td><strong>80 杯</strong></td></tr></tbody></table></figure>



<p class="wp-block-paragraph">四格全部對上。老店員的經驗「晴天下午冰飲爆單」，就這樣被寫成了一個特徵。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-02-feature-cross.png" alt="特徵交叉怎麼算：晴天早上只多賣 5 杯、下午多賣 55 杯，一個權重不夠用；交叉成晴_下午後，模型直接學到 80 杯" class="wp-image-12803" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-02-feature-cross.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-02-feature-cross-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-02-feature-cross-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-02-feature-cross-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">組合有幾種？兩邊相乘</h3>



<pre class="wp-block-code"><code>天氣 3 種（晴、陰、雨）× 時段 4 種（早上、中午、下午、晚上）= 12 種組合</code></pre>



<p class="wp-block-paragraph">用<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">第 10 篇</a>的 One-hot 表示，就是 12 個 0 或 1 的欄位。例如「雨_下午」那一欄是 1，其他 11 欄都是 0。</p>



<h3 class="wp-block-heading">經緯度也能交叉：先分桶，再交叉</h3>



<p class="wp-block-paragraph">分店的位置是<strong>經度、緯度</strong>兩個數字。直接丟給模型，它只能學到「越往東生意越好」這種<strong>一直線</strong>的關係。但商圈是<strong>一塊一塊</strong>的，熱鬧的商圈旁邊可能就是安靜的住宅區。</p>



<p class="wp-block-paragraph">解法分兩步：</p>


<ol class="wp-block-list">
<li><strong>分桶</strong>（Binning，也叫 Bucketing）：把連續的數字<strong>切成幾段</strong>，每一段變成一個類別。比喻：把年齡切成「學生、上班族、退休族」來看。<a href="https://developers.google.com/machine-learning/crash-course/numerical-data/binning">Google 速成課程</a>說，數字跟答案沒有一直線的關係、或數字一團一團聚在一起時，分桶很好用</li>

<li><strong>交叉</strong>：經度切 4 段 × 緯度切 4 段 = <strong>16 格</strong>，就像把地圖畫成 4 × 4 的棋盤，每一格（大約一個街區）學自己的權重</li>
</ol>



<p class="wp-block-paragraph">只分桶、不交叉，模型學到的是一條條<strong>直的長條</strong>（某個經度範圍）和<strong>橫的長條</strong>（某個緯度範圍）。交叉之後，才是一格一格的<strong>街區</strong>。</p>



<h3 class="wp-block-heading">小心：交叉太多會「稀疏」</h3>



<p class="wp-block-paragraph"><strong>稀疏</strong>（Sparse）白話是「一大張表，幾乎都是 0」。速成課程提醒：一個有 100 種值的特徵，交叉一個有 200 種值的特徵，會變成 <strong>20,000</strong> 種組合。</p>



<p class="wp-block-paragraph">換成飲料店（教學用的數字）：</p>



<pre class="wp-block-code"><code>會員 10 萬人 × 飲料 50 款 = 5,000,000 種組合</code></pre>



<p class="wp-block-paragraph">大部分會員只點過三、四款，500 萬格裡絕大多數永遠不會出現。資料這麼少，模型很難學到東西，反而容易<strong>過度擬合</strong>（<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">第 7 篇</a>）。</p>



<p class="wp-block-paragraph">常見的處理方式：</p>


<ul class="wp-block-list">
<li><strong>只交叉有道理的組合</strong>：靠領域知識（老店員的經驗）挑</li>

<li><strong>交叉後再雜湊分桶</strong>：像第 10 篇的雜湊，把組合丟進固定數量的桶子。TensorFlow 的 <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/HashedCrossing"><code>HashedCrossing</code></a> 就是這樣做</li>

<li><strong>改用嵌入或神經網路</strong>：讓模型自己學組合（下一段就講嵌入）</li>
</ul>



<h3 class="wp-block-heading">數字的版本：多項式轉換</h3>



<p class="wp-block-paragraph">特徵交叉處理的是<strong>類別</strong>。如果是<strong>數字</strong>，對應的做法叫<strong>多項式轉換</strong>（Polynomial Transform），例如把氣溫平方，或把「氣溫 × 濕度」做成新特徵。</p>



<p class="wp-block-paragraph">比喻：悶不悶熱，要看氣溫和濕度<strong>一起</strong>。<a href="https://developers.google.com/machine-learning/crash-course/numerical-data/polynomial-transforms">速成課程</a>說，這讓線性模型也能畫出<strong>曲線</strong>，不只是直線。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">特徵交叉是「<strong>用簡單模型做出聰明效果</strong>」的經典招式。PMLE 題目裡出現「線性模型學不到兩個特徵的組合效果」「經緯度」這類情境，答案常常就是它。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">2. 詞嵌入（Word Embedding）：讓意思相近的詞靠在一起</h2>



<h3 class="wp-block-heading">先看問題：One-hot 看不出誰跟誰像</h3>



<p class="wp-block-paragraph">上一篇說，類別要用 One-hot 轉成數字。假設菜單只有三款飲料：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>飲料</th><th>One-hot</th></tr></thead><tbody><tr><td>珍珠奶茶</td><td>(1, 0, 0)</td></tr><tr><td>鮮奶茶</td><td>(0, 1, 0)</td></tr><tr><td>檸檬綠茶</td><td>(0, 0, 1)</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">算任兩杯的「距離」（公式下面會講），結果全部一樣：</p>



<pre class="wp-block-code"><code>珍奶 ↔ 鮮奶茶：√(1² + 1²) = √2 ≈ 1.41
珍奶 ↔ 檸檬綠：√(1² + 1²) = √2 ≈ 1.41</code></pre>



<p class="wp-block-paragraph">在 One-hot 眼裡，珍奶跟鮮奶茶的差別，和珍奶跟檸檬綠茶<strong>一樣大</strong>。但喝過的人都知道，前兩杯像多了。</p>



<p class="wp-block-paragraph"><a href="https://developers.google.com/machine-learning/crash-course/embeddings">Google 速成課程</a>的例子是 5,000 道菜：One-hot 讓每道菜都變成一串 5,000 個數字，<strong>又長、又看不出熱狗和沙威瑪比較像</strong>，模型要學的權重也跟著暴增。</p>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>嵌入</strong>（Embedding）：用<strong>一小串數字</strong>來描述一個東西，<strong>意思相近的東西，數字也相近</strong>。對「詞」做這件事，就叫<strong>詞嵌入</strong>。</p>



<p class="wp-block-paragraph">這一小串數字叫<strong>向量</strong>（Vector），白話就是「一串排好順序的數字」，像地圖上的座標 (x, y)。串裡有幾個數字，就叫幾個<strong>維度</strong>（Dimension）。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像一張<strong>飲料口味地圖</strong>。橫軸是「奶味」、直軸是「果香」，每杯飲料在地圖上都有一個位置（教學用的數字）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>飲料</th><th>奶味</th><th>果香</th><th>座標（嵌入向量）</th></tr></thead><tbody><tr><td>珍珠奶茶</td><td>0.9</td><td>0.1</td><td>(0.9, 0.1)</td></tr><tr><td>鮮奶茶</td><td>0.8</td><td>0.0</td><td>(0.8, 0.0)</td></tr><tr><td>檸檬綠茶</td><td>0.0</td><td>0.9</td><td>(0.0, 0.9)</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">奶茶類會擠在右下角，果茶類在左上角。<strong>位置越近，口味越像</strong>。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">「嵌入」的英文 embed 是「鑲進去」的意思：把每個詞<strong>鑲進一張地圖裡</strong>，給它一個座標。</p>



<p class="wp-block-paragraph">最有名的早期做法，是 2013 年 Google 研究人員提出的 <strong>word2vec</strong>（word to vector，把詞變成向量）。想法很直覺：<strong>出現在相似句子裡的詞，意思也相近</strong>。</p>



<p class="wp-block-paragraph">速成課程的例子：「他們騎著驢子走進峽谷」「他們騎著馬走進峽谷」，驢子和馬出現在一樣的位置，所以它們的座標會靠在一起。</p>



<h3 class="wp-block-heading">算一次給你看 1：哪杯跟珍奶最像？</h3>



<p class="wp-block-paragraph">兩點之間的距離，用國中學過的<strong>畢氏定理</strong>算，這叫<strong>歐氏距離</strong>（Euclidean distance）：</p>



<pre class="wp-block-code"><code>距離 = √[(奶味差)² + (果香差)²]

珍奶 ↔ 鮮奶茶 = √[(0.9 − 0.8)² + (0.1 − 0.0)²]
             = √(0.01 + 0.01) = √0.02 ≈ 0.14

珍奶 ↔ 檸檬綠 = √[(0.9 − 0.0)² + (0.1 − 0.9)²]
             = √(0.81 + 0.64) = √1.45 ≈ 1.20</code></pre>



<h3 class="wp-block-heading">算一次給你看 2：餘弦相似度</h3>



<p class="wp-block-paragraph">另一種常見的量法叫<strong>餘弦相似度</strong>（Cosine similarity），看兩個向量<strong>指的方向</strong>像不像，跟距離遠近無關：</p>



<pre class="wp-block-code"><code>餘弦相似度 = (A₁ × B₁ + A₂ × B₂) ÷ (A 的長度 × B 的長度)
長度 = 這個點離原點 (0, 0) 多遠

珍奶的長度 = √(0.9² + 0.1²) = √0.82 ≈ 0.906
鮮奶茶的長度 = √(0.8² + 0²) = 0.8

珍奶 vs 鮮奶茶 = (0.9 × 0.8 + 0.1 × 0) ÷ (0.906 × 0.8)
              = 0.72 ÷ 0.725 ≈ 0.99

珍奶 vs 檸檬綠 = (0.9 × 0 + 0.1 × 0.9) ÷ (0.906 × 0.9)
              = 0.09 ÷ 0.815 ≈ 0.11</code></pre>



<h3 class="wp-block-heading">數字怎麼看</h3>


<ul class="wp-block-list">
<li><strong>距離</strong>：越小越像，0 代表一模一樣。0.14 比 1.20 小很多，所以喜歡珍奶的客人，該推薦鮮奶茶，不是檸檬綠茶</li>

<li><strong>餘弦相似度</strong>：越接近 1 越像，接近 0 代表沒什麼關係。珍奶和鮮奶茶 0.99，和檸檬綠只有 0.11，結論一樣</li>

<li><strong>跟 One-hot 比</strong>：One-hot 每兩杯都是 1.41，<strong>分不出遠近</strong>；嵌入分得出來，這就是它的價值</li>
</ul>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-03-embedding.png" alt="詞嵌入怎麼算：在奶味與果香的口味地圖上，珍奶和鮮奶茶距離 0.14，珍奶和檸檬綠距離 1.20；One-hot 每兩杯都是 1.41 分不出遠近" class="wp-image-12804" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-03-embedding.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-03-embedding-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-03-embedding-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-03-embedding-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">真實世界的嵌入長什麼樣子</h3>


<ul class="wp-block-list">
<li><strong>維度很多</strong>：速成課程說，詞嵌入常見 256、512、1,024 維。Google 現在的 <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/embeddings/get-text-embeddings"><code>gemini-embedding-001</code></a> 模型預設是 3,072 維</li>

<li><strong>每一維看不懂</strong>：真實模型學出來的維度，很少像「奶味」「果香」這麼好懂。但「相近的東西靠在一起」這件事一樣成立</li>

<li><strong>跟任務有關</strong>：速成課程舉例，「早餐麥片」和「早餐香腸」在「依時段推薦菜色」的模型裡很近，在「葷素分類」的模型裡就很遠</li>
</ul>



<h3 class="wp-block-heading">嵌入從哪裡來？</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>做法</th><th>白話</th><th>適合</th></tr></thead><tbody><tr><td>自己訓練</td><td>在神經網路裡放一層<strong>嵌入層</strong>，訓練時順便學出每個東西的座標</td><td>自己的分店、會員、商品編號（第 10 篇的高基數類別）</td></tr><tr><td>用現成的</td><td>直接用大公司拿海量資料訓練好的模型來轉</td><td>文字、圖片，例如顧客評論</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">新舊說法：word2vec 現在還用嗎？</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>word2vec 是「靜態嵌入」，現在主流是會看前後文的「情境嵌入」。</strong><br><a href="https://developers.google.com/machine-learning/crash-course/embeddings/obtaining-embeddings">速成課程</a>說，word2vec 已經<strong>大多被其他模型取代</strong>，但拿來理解概念還是很好用。它的限制是<strong>每個詞只有一個座標</strong>：「蘋果」不管出現在「蘋果牛奶」還是「蘋果手機」，座標都一樣。</p>



<p class="wp-block-paragraph"><strong>情境嵌入</strong>（Contextual embedding）會看前後文，同一個詞在不同句子裡給不同的座標。BERT、Transformer 都是這類做法（Transformer 是現在大型語言模型的基本架構）。現在的文字嵌入模型，例如 Google Cloud 上的 Gemini 嵌入模型，是把<strong>整段文字</strong>一起轉成一串數字。</p>
</blockquote>



<h3 class="wp-block-heading">嵌入可以拿來做什麼</h3>



<p class="wp-block-paragraph">依照 <a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-ai-generate-embedding">BigQuery 官方文件</a>，常見的用途：</p>


<ul class="wp-block-list">
<li><strong>語意搜尋</strong>：客人打「不要太甜、有奶味」，找出意思最接近的飲料，就算字面上完全不一樣</li>

<li><strong>推薦</strong>：找出跟這杯最像的其他飲料</li>

<li><strong>分類、分群</strong>：把評論分成正評負評、把相似的評論放在一起</li>

<li><strong>找異常</strong>：找出跟其他都不像的那一筆</li>
</ul>



<p class="wp-block-paragraph">生成式 AI 常說的 <strong>RAG</strong>（Retrieval-Augmented Generation，檢索增強生成）也是建在嵌入上：先用嵌入找出跟問題最相關的資料，再交給 Gemini 這類模型寫出答案。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">文字、圖片這類資料，幾乎都要先變成嵌入才能進模型；高基數類別也常用嵌入處理。現在的生成式 AI 應用，背後也幾乎都有「嵌入＋找相似」這一步。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">3. 資料增強（Data Augmentation）：照片太少，就變出更多</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>資料增強</strong>：把現有的訓練資料做一些<strong>合理的小變化</strong>，例如翻轉、旋轉、調亮度，變出更多「長得不太一樣、但答案一樣」的訓練資料。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>認朋友</strong>：同一個朋友，戴帽子、側臉、在昏暗的餐廳裡，你都要認得出來。如果你只看過對方一張正面大頭照，換個角度可能就認不出來了。</p>



<p class="wp-block-paragraph">資料增強就是<strong>幫模型多看幾種角度和光線</strong>。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">「增強」（augment）是「擴充、加量」的意思。<a href="https://www.tensorflow.org/tutorials/images/data_augmentation">TensorFlow 官方教學</a>的定義：用<strong>隨機、但合理的變化</strong>（例如旋轉圖片），增加訓練資料的多樣性。</p>



<p class="wp-block-paragraph">會需要它，是因為<strong>拍照、標註都很花錢</strong>。資料太少，模型就會把那幾張照片背起來，換一張新照片就認不得，這就是<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">第 7 篇</a>的過度擬合。用程式「變」出新照片，幾乎不用成本。</p>



<h3 class="wp-block-heading">算一次給你看</h3>



<p class="wp-block-paragraph">假設（教學用的數字）飲料店想做「拍照辨識是哪一款飲料」的模型，有 10 款飲料，每款只拍了 50 張：</p>



<pre class="wp-block-code"><code>原始照片：10 款 × 50 張 = 500 張</code></pre>



<p class="wp-block-paragraph">每張照片做三種變化：</p>



<pre class="wp-block-code"><code>左右翻轉：不翻、翻 → 2 種
旋轉：左轉一點、不轉、右轉一點 → 3 種
亮度：原本、暗一點 → 2 種

每張可以變出：2 × 3 × 2 = 12 個版本
總共：500 × 12 = 6,000 張</code></pre>



<p class="wp-block-paragraph">實際上變化是<strong>隨機</strong>的。模型每看完一輪全部的照片（叫一個<strong>回合</strong>，Epoch），下一輪拿到的又是隨機變過的新版本，所以看到的樣子比 6,000 種還多。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-04-augmentation.png" alt="資料增強怎麼算：500 張照片乘上翻轉 2 種、旋轉 3 種、亮度 2 種，變成 6,000 張；只對訓練集做，而且變化不能改變答案" class="wp-image-12805" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-04-augmentation.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-04-augmentation-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-04-augmentation-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-04-augmentation-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">兩條一定要守的規則</h3>


<ol class="wp-block-list">
<li><strong>只對訓練集做</strong>。TensorFlow 教學明寫：資料增強只應該用在訓練集。驗證集、測試集要用<strong>真實的照片</strong>打分數，否則分數會灌水，跟<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">第 8 篇的資料洩漏</a>是同一類問題</li>

<li><strong>變化不能改變答案</strong>。左右翻轉一杯珍奶，還是珍奶；但亮度調太亮，紅茶看起來像奶茶，答案就被改掉了。同理，辨識數字的模型不能把 6 轉 180 度，那會變成 9</li>
</ol>



<h3 class="wp-block-heading">筆記說的「放進 tf.data 管道」是什麼意思</h3>



<p class="wp-block-paragraph">先認識幾個名詞：</p>


<ul class="wp-block-list">
<li><strong>TensorFlow</strong>：Google 開發的機器學習程式工具包。<strong>Keras</strong> 是它裡面比較好上手的一層，用來組模型</li>

<li><strong>tf.data</strong>：TensorFlow 讀資料、整理資料的<strong>流水線</strong>，資料一批一批從硬碟讀出來、整理好，送去給模型</li>

<li><strong>CPU、GPU</strong>：CPU 是電腦的一般大腦，什麼都能做；GPU 是顯示卡上的晶片，特別擅長同時做大量計算，訓練模型主要靠它</li>
</ul>



<p class="wp-block-paragraph">TensorFlow 教學列了兩種放資料增強的位置：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>做法 A：放進模型裡</th><th>做法 B：放進 tf.data 流水線</th></tr></thead><tbody><tr><td>在哪裡算</td><td>GPU，跟模型一起算</td><td>CPU，跟 GPU 訓練<strong>同時進行</strong></td></tr><tr><td>存模型時</td><td>增強層會跟著存下來</td><td><strong>不會</strong>跟著模型存下來</td></tr><tr><td>預測時</td><td>自動停用，不會亂變</td><td>本來就只套在訓練資料上</td></tr><tr><td>適合</td><td>想簡單、部署時前處理跟著模型走</td><td>不想讓 GPU 閒著等資料</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>部署</strong>是把訓練好的模型放上線給大家用。做法 A 的好處是：上線時不用在<strong>伺服器</strong>（負責接收照片、回傳預測結果的那台電腦）另外寫一份前處理程式。</p>



<p class="wp-block-paragraph">做法 B 的寫法（教學用的範例）：</p>



<pre class="wp-block-code"><code>import tensorflow as tf
from tensorflow.keras import layers

data_augmentation = tf.keras.Sequential([
    layers.RandomFlip("horizontal"),   # 隨機左右翻轉
    layers.RandomRotation(0.05),       # 隨機旋轉，最多 0.05 × 360 = 18 度
    layers.RandomBrightness(0.2),      # 隨機調亮或調暗一點
])

# 只對訓練集做增強，再預先準備下一批
train_ds = train_ds.map(lambda x, y: (data_augmentation(x, training=True), y))
train_ds = train_ds.prefetch(tf.data.AUTOTUNE)</code></pre>



<p class="wp-block-paragraph">逐行翻成白話：</p>


<ul class="wp-block-list">
<li><code>RandomFlip</code>、<code>RandomRotation</code>、<code>RandomBrightness</code>：三種隨機變化，對應上面算的翻轉、旋轉、亮度</li>

<li><code>train_ds.map(...)</code>：把訓練集的每一批照片，都丟進增強流水線；<code>training=True</code> 是告訴它「現在在訓練，要隨機變」</li>

<li><code>prefetch</code>（預先準備）：CPU 做增強的同時，GPU 繼續訓練上一批，誰都不用等誰。讀資料加速<a href="https://dongdonggcp.com/2026/10/25/tfrecords-tf-data-prefetch-input-pipeline/">第 13 篇</a>會細講</li>
</ul>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">圖片、聲音這類資料，最常遇到的就是「資料太少、過度擬合」。PMLE 題目看到「圖片很少」「訓練分數很高、驗證分數很低」，資料增強是很常見的答案。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">三招一張表比完</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>特徵交叉</th><th>詞嵌入</th><th>資料增強</th></tr></thead><tbody><tr><td>解決什麼</td><td>兩個特徵要合起來看</td><td>類別、文字看不出遠近</td><td>資料太少、過度擬合</td></tr><tr><td>常用在</td><td>表格資料、線性模型</td><td>文字、高基數類別</td><td>圖片、聲音</td></tr><tr><td>一句話比喻</td><td>棋盤格</td><td>口味地圖</td><td>認朋友的各種角度</td></tr><tr><td>要小心</td><td>組合太多會稀疏</td><td>嵌入跟任務有關</td><td>只做訓練集、不能改答案</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">在 GCP 上怎麼做</h2>



<p class="wp-block-paragraph"><strong>GCP（Google Cloud Platform）</strong> 是 Google 的雲端服務，白話說就是<strong>租用 Google 機房裡的電腦和工具</strong>。</p>



<h3 class="wp-block-heading">1. BigQuery ML：用 SQL 做特徵交叉</h3>


<ul class="wp-block-list">
<li><strong>BigQuery</strong>：Google 的大型資料倉庫，專門存放和分析超大量的表格資料</li>

<li><strong>BigQuery ML</strong>：讓你<a href="https://docs.cloud.google.com/bigquery/docs/bqml-introduction">用 SQL（跟資料庫說話的語言）直接在 BigQuery 裡訓練模型</a></li>
</ul>



<p class="wp-block-paragraph">依照<a href="https://docs.cloud.google.com/bigquery/docs/manual-preprocessing">手動前處理的官方文件</a>，BigQuery ML 有現成的特徵工程函數：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>函數</th><th>做什麼</th></tr></thead><tbody><tr><td><a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-feature-cross"><code>ML.FEATURE_CROSS</code></a></td><td>特徵交叉（類別），最多 10 個特徵</td></tr><tr><td><a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-bucketize"><code>ML.BUCKETIZE</code></a></td><td>依你給的切點分桶</td></tr><tr><td><code>ML.QUANTILE_BUCKETIZE</code></td><td>分桶，讓每一桶的筆數差不多</td></tr><tr><td><a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-polynomial-expand"><code>ML.POLYNOMIAL_EXPAND</code></a></td><td>多項式轉換（數字）</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">把這篇的冰飲例子寫進 <code>TRANSFORM</code>（教學用的範例）：</p>



<pre class="wp-block-code"><code>CREATE MODEL `shop.iced_cups_fe`
TRANSFORM(
  ML.FEATURE_CROSS(STRUCT(weather, time_slot)) AS weather_x_slot,  -- 天氣 × 時段
  ML.FEATURE_CROSS(STRUCT(
    ML.BUCKETIZE(longitude, [121.50, 121.55, 121.60]) AS lon,
    ML.BUCKETIZE(latitude, [25.00, 25.05, 25.10]) AS lat
  )) AS area,                                                       -- 經緯度切成 16 格
  weather,
  time_slot,
  iced_cups)
OPTIONS(model_type='LINEAR_REG',
        input_label_cols=['iced_cups']) AS
SELECT weather, time_slot, longitude, latitude, iced_cups
FROM `shop.hourly_sales_train`;</code></pre>



<p class="wp-block-paragraph">逐行翻成白話：</p>


<ul class="wp-block-list">
<li><code>ML.FEATURE_CROSS(STRUCT(weather, time_slot))</code>：<code>STRUCT</code> 是把幾個欄位包成一組，這裡把天氣和時段包起來交叉，結果像「晴_下午」</li>

<li><code>ML.BUCKETIZE(longitude, [121.50, 121.55, 121.60])</code>：經度用 3 個切點切成 4 段；緯度也一樣</li>

<li>外面再包一層 <code>ML.FEATURE_CROSS</code>：4 段 × 4 段 = 16 格街區</li>

<li>原本的 <code>weather</code>、<code>time_slot</code> 也留著：模型同時有「單看天氣」和「組合起來看」兩種線索</li>

<li><code>model_type='LINEAR_REG'</code>：用線性迴歸，就是前面說「只會加法」的那種模型，所以才特別需要特徵交叉</li>

<li>寫在 <code>TRANSFORM</code> 裡，上線預測時會自動用同樣的方式交叉和分桶，不會前後不一致（第 10 篇講過）</li>
</ul>



<h3 class="wp-block-heading">2. BigQuery：用 SQL 把顧客評論變成嵌入</h3>



<pre class="wp-block-code"><code>-- 步驟 1：建一個遠端模型，指到 Agent Platform 上的嵌入模型
CREATE OR REPLACE MODEL `shop.embedding_model`
  REMOTE WITH CONNECTION `us.my_connection`
  OPTIONS(ENDPOINT = 'gemini-embedding-001');

-- 步驟 2：把每則評論轉成一串數字
SELECT *
FROM AI.GENERATE_EMBEDDING(
  MODEL `shop.embedding_model`,
  (SELECT review_id, review_text AS content FROM `shop.reviews`));</code></pre>



<p class="wp-block-paragraph">逐行翻成白話：</p>


<ul class="wp-block-list">
<li><strong>遠端模型</strong>（Remote model）：BigQuery 裡的一個「捷徑」，真正的計算交給 Agent Platform 上的嵌入模型</li>

<li><strong>連線</strong>（Connection）：讓 BigQuery 有權限去呼叫其他服務的通行證</li>

<li><a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-ai-generate-embedding"><code>AI.GENERATE_EMBEDDING</code></a>：把 <code>content</code> 欄位的文字轉成嵌入，結果放在 <code>embedding</code> 欄位</li>

<li>要找最像的評論或飲料，可以接著用 <code>VECTOR_SEARCH</code>（<a href="https://docs.cloud.google.com/bigquery/docs/vector-search-intro">向量搜尋</a>，預設就是用上面算過的歐氏距離）；只比少數幾筆，可以用 <code>AI.SIMILARITY</code>（餘弦相似度）</li>
</ul>



<p class="wp-block-paragraph"><strong>評論是中文，要選支援多語言的模型。</strong> 依照官方文件，<code>gemini-embedding-001</code> 支援多語言，<code>text-embedding-005</code> 專攻英文和程式碼。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>舊文章可能看到 <code>ML.GENERATE_TEXT_EMBEDDING</code> 或 <code>ML.GENERATE_EMBEDDING</code>。</strong><br>官方文件現在建議新的查詢改用 <code>AI.GENERATE_EMBEDDING</code>，功能一樣、輸出的欄位名稱比較簡單。舊教材常見的 textembedding-gecko 模型，官方文件已提醒之後可能停用；現在 Agent Platform 列出的 Google 文字嵌入模型是 <code>gemini-embedding-001</code> 和 <code>gemini-embedding-2</code>。</p>
</blockquote>



<h3 class="wp-block-heading">3. Agent Platform：自己寫程式訓練</h3>



<p class="wp-block-paragraph">需要自訂模型時，在 Google 的機器學習平台上寫 TensorFlow／Keras 程式。這個平台最近改名了：</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>舊題庫可能還會看到 Vertex AI，現在叫 Gemini Enterprise Agent Platform（簡稱 Agent Platform）。</strong><br>Google Cloud 在 2026 年 4 月 22 日正式改名（<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/vertex-ai-name-changes">官方對照表</a>），2026 年 6 月 1 日起的 PMLE 考試指南也全面用新名稱。</p>
</blockquote>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>舊名稱（舊題庫常見）</th><th>現在的名稱</th><th>跟這篇的關係</th></tr></thead><tbody><tr><td>Vertex AI</td><td>Gemini Enterprise Agent Platform</td><td>整個平台</td></tr><tr><td>Vertex AI Workbench</td><td>Gemini Enterprise Agent Platform Workbench</td><td>網頁版的程式筆記本，試做特徵</td></tr><tr><td>Vertex AI Training</td><td>Gemini Enterprise Agent Platform Managed Training</td><td>跑自訂訓練</td></tr><tr><td>Vertex AI Feature Store</td><td>Feature Store on Gemini Enterprise Agent Platform</td><td>存放做好的特徵</td></tr><tr><td>Vertex AI Vector Search</td><td>Vector Search on Gemini Enterprise Agent Platform</td><td>大量嵌入找相似</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">在程式裡，三招各有對應的 Keras 工具：特徵交叉用 <code>HashedCrossing</code>、嵌入用 <code>StringLookup</code> 搭配 <code>Embedding</code>、資料增強用 <code>RandomFlip</code> 這類隨機層。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>舊題庫可能還會看到 <code>tf.feature_column.crossed_column</code>、<code>embedding_column</code>。</strong><br>TensorFlow 官方已經<a href="https://www.tensorflow.org/tutorials/structured_data/feature_columns">不建議新程式使用 feature column</a>，除了安全性修正不會再更新，改用 Keras 前處理層：<code>crossed_column</code> 換成 <code>HashedCrossing</code>，<code>embedding_column</code> 換成 <code>StringLookup</code>＋<code>Embedding</code>。</p>
</blockquote>



<h3 class="wp-block-heading">4. 做好的特徵放哪裡：Feature Store</h3>



<p class="wp-block-paragraph">考試指南第 2 區有一項「在 Feature Store 建立和整合特徵」。<strong>Feature Store</strong>（特徵商店）白話是「<strong>特徵的共用倉庫</strong>」。</p>



<p class="wp-block-paragraph">像「晴_下午」這種做好的特徵存一份，訓練和上線預測都從這裡拿，不同團隊、不同模型也能共用，不用每個人各做一次。它跟其他資料服務怎麼選，<a href="https://dongdonggcp.com/2026/10/25/gcp-data-services-for-ml-bigquery-cloud-storage-feature-store-bigtable/">第 23 篇</a>會比較。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">考試會怎麼考</h2>



<p class="wp-block-paragraph">Google Cloud <strong>Professional Machine Learning Engineer（PMLE，專業機器學習工程師）</strong> 證照，2026 年 6 月 1 日起的<a href="https://services.google.com/fh/files/misc/professional_machine_learning_engineer_exam_guide_english_new.pdf">官方考試指南</a>裡，這篇的內容對應到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考試區塊</th><th>跟這篇有關的項目</th></tr></thead><tbody><tr><td>第 1 區：用低程式碼方式打造 AI 方案（約 13%）</td><td><strong>用 BigQuery ML 做特徵工程或特徵選擇</strong></td></tr><tr><td>第 2 區：跨團隊管理資料與模型（約 16%）</td><td>整理與探索<strong>不同資料型態</strong>（表格、文字、圖片）；在 <strong>Feature Store</strong> 建立和整合特徵</td></tr><tr><td>第 5 區：自動化與協調 ML 管線（約 18%）</td><td>確保訓練和上線的前處理一致</td></tr></tbody></table></figure>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-05-exam-keywords.png" alt="PMLE 考試關鍵字：兩個特徵要一起看想到特徵交叉，經緯度想到分桶再交叉，找相似文字想到嵌入加向量搜尋，圖片太少想到資料增強" class="wp-image-12806" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-05-exam-keywords.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-05-exam-keywords-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-05-exam-keywords-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml11-05-exam-keywords-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目出現的關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「兩個特徵合起來才有意義」「線性模型學不到組合效果」</td><td><strong>特徵交叉</strong></td></tr><tr><td>「經緯度」「地理位置」</td><td><strong>先分桶、再交叉</strong></td></tr><tr><td>「交叉後組合太多」「太稀疏」</td><td>雜湊（<code>HashedCrossing</code>）、少交叉、改用嵌入</td></tr><tr><td>「數字和答案是曲線關係」</td><td><strong>多項式轉換</strong></td></tr><tr><td>「找相似的文字／商品」「語意搜尋」「推薦」</td><td><strong>嵌入＋向量搜尋</strong></td></tr><tr><td>「同一個詞在不同句子意思不同」</td><td><strong>情境嵌入</strong>（不是 word2vec）</td></tr><tr><td>「只會 SQL、要做文字嵌入」</td><td>BigQuery <code>AI.GENERATE_EMBEDDING</code></td></tr><tr><td>「圖片很少」「訓練很高、驗證很低」</td><td><strong>資料增強</strong></td></tr><tr><td>「GPU 在等資料」</td><td>增強放進 <strong>tf.data</strong>，搭配 <code>prefetch</code></td></tr><tr><td>「部署時前處理要跟著模型走」</td><td>增強層、前處理層<strong>放進模型裡</strong>；BigQuery ML 用 <code>TRANSFORM</code></td></tr><tr><td>「特徵要給多個模型共用」</td><td><strong>Feature Store</strong></td></tr></tbody></table></figure>



<h3 class="wp-block-heading">五個常見陷阱</h3>


<ol class="wp-block-list">
<li><strong>驗證集、測試集也做增強</strong>：增強只做訓練集，打分數要用真實資料</li>

<li><strong>兩個種類很多的特徵直接交叉</strong>：組合會爆炸、太稀疏，要先想清楚或改用雜湊、嵌入</li>

<li><strong>增強改變了答案</strong>：翻轉、旋轉、亮度要合理，6 轉成 9 就錯了</li>

<li><strong>想用 One-hot 比相似度</strong>：One-hot 每兩個類別距離都一樣，要比相似要用嵌入</li>

<li><strong>中文資料選了只支援英文的嵌入模型</strong>：例如 <code>text-embedding-005</code>，要改選多語言模型</li>
</ol>



<h3 class="wp-block-heading">練習情境（自己出的練習，不是真實考題）</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">一家連鎖飲料店想做「拍照辨識飲料品項」的模型，每款飲料只有幾十張照片。訓練準確率 98%，驗證準確率只有 65%。部署時希望前處理跟著模型一起走，不用在伺服器另外寫程式。應該怎麼做？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「訓練很高、驗證很低」→ 過度擬合；「照片很少」→ <strong>資料增強</strong></li>

<li>「前處理要跟著模型走」→ 把 <code>RandomFlip</code>、<code>RandomRotation</code> 等增強層<strong>放進模型裡</strong>（做法 A），存模型時一起存下來，預測時自動停用</li>

<li>驗證集維持真實照片，<strong>不做增強</strong></li>
</ul>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">同一家店想讓客人在 App 輸入「想喝有奶味、不要太甜」，就推薦口味相近的飲料。飲料說明都在 BigQuery，團隊只會 SQL。應該怎麼做？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「找口味相近」「字面不一樣也要找得到」→ <strong>嵌入＋向量搜尋</strong></li>

<li>「資料在 BigQuery、只會 SQL」→ 建遠端模型，用 <strong><code>AI.GENERATE_EMBEDDING</code></strong> 把飲料說明轉成嵌入，再用 <strong><code>VECTOR_SEARCH</code></strong> 找最近的</li>

<li>「中文」→ 選 <code>gemini-embedding-001</code> 這類支援多語言的模型</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">特徵工程是什麼？</h3>



<p class="wp-block-paragraph">特徵工程是用你對問題的了解，把原始資料加工、組合成新的特徵，讓模型更容易看出規律。常見的做法有特徵交叉（把兩個特徵組合起來）、嵌入（把文字或類別變成有意義的數字）、資料增強（把少量資料變多）。就像把老店員的經驗，寫成模型看得到的欄位。</p>



<h3 class="wp-block-heading">特徵工程和資料前處理差在哪？</h3>



<p class="wp-block-paragraph">資料前處理是把資料清乾淨、轉成數字、調到適合的大小，像洗菜切菜；特徵工程是用原本的資料做出新的線索，像配菜調味。兩者界線不是很硬，例如分桶有人歸在前處理、有人歸在特徵工程。大方向是：前處理讓資料能用，特徵工程讓資料好用。</p>



<h3 class="wp-block-heading">特徵交叉是什麼？什麼時候要用？</h3>



<p class="wp-block-paragraph">特徵交叉是把兩個以上的類別特徵組合成一個新特徵，例如天氣乘上時段，變成晴_下午、雨_早上等組合。當「一個特徵的效果要看另一個特徵是什麼」時就該用，例如晴天早上只多賣 5 杯、晴天下午多賣 55 杯。線性模型只會加法，加上特徵交叉才學得到這種組合效果。</p>



<h3 class="wp-block-heading">特徵交叉的組合太多怎麼辦？</h3>



<p class="wp-block-paragraph">組合數是兩邊相乘，例如 100 種乘 200 種就有 20,000 種，大部分組合幾乎沒有資料，模型容易過度擬合。可以只交叉有道理的組合、交叉後再雜湊分桶到固定數量的桶子（例如 TensorFlow 的 HashedCrossing），或改用嵌入、神經網路讓模型自己學組合。</p>



<h3 class="wp-block-heading">詞嵌入是什麼？跟 One-hot 差在哪？</h3>



<p class="wp-block-paragraph">詞嵌入是用一小串數字（向量）描述一個詞，意思相近的詞，數字也相近。One-hot 讓每兩個類別的距離都一樣，看不出珍奶比較像鮮奶茶還是檸檬綠茶；嵌入則會讓珍奶和鮮奶茶靠得很近。嵌入的數字也短得多，One-hot 有幾千種類別就要幾千欄，嵌入常見只要幾百個數字。</p>



<h3 class="wp-block-heading">word2vec 現在還有人用嗎？</h3>



<p class="wp-block-paragraph">Google 速成課程說 word2vec 已經大多被其他模型取代，但拿來理解概念還是很好用。它是靜態嵌入，每個詞只有一個座標，「蘋果牛奶」和「蘋果手機」的蘋果長一樣。現在主流是會看前後文的情境嵌入，例如 BERT、Transformer，以及 Google Cloud 上的 Gemini 嵌入模型。</p>



<h3 class="wp-block-heading">嵌入向量要幾個維度？</h3>



<p class="wp-block-paragraph">沒有固定答案。Google 速成課程說詞嵌入常見 256、512 或 1,024 維；gemini-embedding-001 預設是 3,072 維，也可以用 output_dimensionality 參數設小一點。維度越多能記的細節越多，但也越佔空間、算得越慢，要在品質和成本之間取捨。</p>



<h3 class="wp-block-heading">資料增強是什麼？驗證集和測試集要做嗎？</h3>



<p class="wp-block-paragraph">資料增強是把訓練資料做合理的小變化，例如翻轉、旋轉、調亮度，變出更多訓練資料，用來對付資料太少和過度擬合。只有訓練集要做，驗證集和測試集要用真實資料打分數，否則分數會灌水。變化也不能改變答案，例如辨識數字時不能把 6 轉成 9。</p>



<h3 class="wp-block-heading">深度學習還需要特徵工程嗎？</h3>



<p class="wp-block-paragraph">需要，但分工不一樣了。神經網路可以自己學出一部分特徵組合，例如用嵌入層學出類別的座標，但比較花運算資源，也需要更多資料。表格資料搭配簡單模型時，人工做的特徵交叉、分桶還是很有效；圖片資料雖然不太需要手工特徵，資料增強還是常用。</p>



<h3 class="wp-block-heading">BigQuery 怎麼產生文字嵌入？ML.GENERATE_EMBEDDING 和 AI.GENERATE_EMBEDDING 差在哪？</h3>



<p class="wp-block-paragraph">先在 BigQuery 建一個遠端模型，指到 Agent Platform 上的嵌入模型（例如 gemini-embedding-001），再用 AI.GENERATE_EMBEDDING 把文字欄位轉成嵌入。官方文件說 AI.GENERATE_EMBEDDING 和 ML.GENERATE_EMBEDDING 功能一樣，但輸出的欄位名稱比較簡單，新的查詢建議用 AI.GENERATE_EMBEDDING。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>特徵工程</strong>：把老店員的經驗寫成模型看得到的欄位；前處理讓資料能用，特徵工程讓資料好用</li>

<li><strong>特徵交叉</strong>：兩個類別特徵組合成新特徵（像棋盤格），讓線性模型學到<strong>交互作用</strong>；經緯度先分桶再交叉；組合太多會稀疏</li>

<li><strong>詞嵌入</strong>：用一小串數字描述詞，意思近、距離就近；word2vec 是靜態嵌入，現在主流是看前後文的<strong>情境嵌入</strong></li>

<li><strong>資料增強</strong>：翻轉、旋轉、調亮度把資料變多；<strong>只做訓練集、不能改變答案</strong>；可以放進模型或 tf.data 流水線</li>

<li>GCP 上：BigQuery ML 用 <code>ML.FEATURE_CROSS</code>、<code>ML.BUCKETIZE</code>，文字嵌入用 <strong><code>AI.GENERATE_EMBEDDING</code></strong>；<strong>Vertex AI 已改名為 Gemini Enterprise Agent Platform</strong>，做好的特徵放 Feature Store</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/20/types-of-machine-learning-supervised-unsupervised-reinforcement/">機器學習有哪幾種？監督式、非監督式、強化學習一次看懂</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/10/20/classification-vs-regression-mae-rmse/">分類和迴歸差在哪？一個例子搞懂，附 MAE、RMSE 計算</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">特徵、標籤、超參數是什麼？機器學習 5 個必懂名詞</a></li>

<li>第 4 篇：<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">訓練集、驗證集、測試集怎麼切？時間序列為什麼不能亂切</a></li>

<li>第 5 篇：<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">混淆矩陣是什麼？用快篩搞懂準確率、精確率、召回率、F1</a></li>

<li>第 6 篇：<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">ROC 曲線和 AUC 怎麼看？門檻怎麼調、AUC-PR 差在哪</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">過度擬合是什麼？正則化、Dropout、提前停止 3 招解決</a></li>

<li>第 8 篇：<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">資料洩漏是什麼？模型考試作弊的 3 種常見情況</a></li>

<li>第 9 篇：<a href="https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/">類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</a></li>

<li>上一篇：第 10 篇：<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">資料前處理怎麼做？標準化、遺失值、高基數類別</a></li>

<li>下一篇：第 12 篇：<a href="https://dongdonggcp.com/2026/10/25/machine-learning-data-privacy-dlp-federated-learning-vpc-service-controls/">機器學習的資料隱私怎麼保護？DLP、聯邦學習、VPC Service Controls</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/08/12/what-is-end-to-end-training-in-machine-learning/">End-to-end Training（端到端訓練）是什麼？</a></li>

<li><a href="https://dongdonggcp.com/2024/08/23/what-is-generative-ai-what-is-the-difference-to-machine-learning/">生成式 AI 是什麼？跟機器學習差在哪裡？</a></li>

<li><a href="https://dongdonggcp.com/2025/07/04/is-bigquery-a-database-what-is-the-usage/">BigQuery 不就是查詢嗎？跟資料庫差在哪裡？能做什麼分析？</a></li>

<li><a href="https://dongdonggcp.com/2025/04/14/vertex-ai-functions-agent-builder-model-builder-model-garden-introduction/">Vertex AI 核心功能 Agent Builder、Model Builder 和 Model Garden 介紹</a></li>

<li><a href="https://dongdonggcp.com/2025/04/27/gcp-learning-roadmap/">GCP 學習路徑 Learning Roadmap 和八大關卡</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">前處理讓食材乾淨，特徵工程讓菜有味道；這兩篇合起來，就是模型拿到好資料的完整準備。如果你想有系統地從雲端基礎一路學到在 GCP 上動手做機器學習，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "特徵工程是什麼？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "特徵工程是用你對問題的了解，把原始資料加工、組合成新的特徵，讓模型更容易看出規律。常見的做法有特徵交叉（把兩個特徵組合起來）、嵌入（把文字或類別變成有意義的數字）、資料增強（把少量資料變多）。就像把老店員的經驗，寫成模型看得到的欄位。"
      }
    },
    {
      "@type": "Question",
      "name": "特徵工程和資料前處理差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "資料前處理是把資料清乾淨、轉成數字、調到適合的大小，像洗菜切菜；特徵工程是用原本的資料做出新的線索，像配菜調味。兩者界線不是很硬，例如分桶有人歸在前處理、有人歸在特徵工程。大方向是：前處理讓資料能用，特徵工程讓資料好用。"
      }
    },
    {
      "@type": "Question",
      "name": "特徵交叉是什麼？什麼時候要用？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "特徵交叉是把兩個以上的類別特徵組合成一個新特徵，例如天氣乘上時段，變成晴_下午、雨_早上等組合。當「一個特徵的效果要看另一個特徵是什麼」時就該用，例如晴天早上只多賣 5 杯、晴天下午多賣 55 杯。線性模型只會加法，加上特徵交叉才學得到這種組合效果。"
      }
    },
    {
      "@type": "Question",
      "name": "特徵交叉的組合太多怎麼辦？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "組合數是兩邊相乘，例如 100 種乘 200 種就有 20,000 種，大部分組合幾乎沒有資料，模型容易過度擬合。可以只交叉有道理的組合、交叉後再雜湊分桶到固定數量的桶子（例如 TensorFlow 的 HashedCrossing），或改用嵌入、神經網路讓模型自己學組合。"
      }
    },
    {
      "@type": "Question",
      "name": "詞嵌入是什麼？跟 One-hot 差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "詞嵌入是用一小串數字（向量）描述一個詞，意思相近的詞，數字也相近。One-hot 讓每兩個類別的距離都一樣，看不出珍奶比較像鮮奶茶還是檸檬綠茶；嵌入則會讓珍奶和鮮奶茶靠得很近。嵌入的數字也短得多，One-hot 有幾千種類別就要幾千欄，嵌入常見只要幾百個數字。"
      }
    },
    {
      "@type": "Question",
      "name": "word2vec 現在還有人用嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Google 速成課程說 word2vec 已經大多被其他模型取代，但拿來理解概念還是很好用。它是靜態嵌入，每個詞只有一個座標，「蘋果牛奶」和「蘋果手機」的蘋果長一樣。現在主流是會看前後文的情境嵌入，例如 BERT、Transformer，以及 Google Cloud 上的 Gemini 嵌入模型。"
      }
    },
    {
      "@type": "Question",
      "name": "嵌入向量要幾個維度？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "沒有固定答案。Google 速成課程說詞嵌入常見 256、512 或 1,024 維；gemini-embedding-001 預設是 3,072 維，也可以用 output_dimensionality 參數設小一點。維度越多能記的細節越多，但也越佔空間、算得越慢，要在品質和成本之間取捨。"
      }
    },
    {
      "@type": "Question",
      "name": "資料增強是什麼？驗證集和測試集要做嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "資料增強是把訓練資料做合理的小變化，例如翻轉、旋轉、調亮度，變出更多訓練資料，用來對付資料太少和過度擬合。只有訓練集要做，驗證集和測試集要用真實資料打分數，否則分數會灌水。變化也不能改變答案，例如辨識數字時不能把 6 轉成 9。"
      }
    },
    {
      "@type": "Question",
      "name": "深度學習還需要特徵工程嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "需要，但分工不一樣了。神經網路可以自己學出一部分特徵組合，例如用嵌入層學出類別的座標，但比較花運算資源，也需要更多資料。表格資料搭配簡單模型時，人工做的特徵交叉、分桶還是很有效；圖片資料雖然不太需要手工特徵，資料增強還是常用。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery 怎麼產生文字嵌入？ML.GENERATE_EMBEDDING 和 AI.GENERATE_EMBEDDING 差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "先在 BigQuery 建一個遠端模型，指到 Agent Platform 上的嵌入模型（例如 gemini-embedding-001），再用 AI.GENERATE_EMBEDDING 把文字欄位轉成嵌入。官方文件說 AI.GENERATE_EMBEDDING 和 ML.GENERATE_EMBEDDING 功能一樣，但輸出的欄位名稱比較簡單，新的查詢建議用 AI.GENERATE_EMBEDDING。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/">特徵工程是什麼？特徵交叉、詞嵌入、資料增強一次看懂</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>資料前處理怎麼做？標準化、遺失值、高基數類別</title>
		<link>https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=data-preprocessing-normalization-missing-values-high-cardinality</link>
					<comments>https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 22 Oct 2026 13:08:10 +0000</pubDate>
				<category><![CDATA[AI 和機器學習]]></category>
		<category><![CDATA[證照考試]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[BigQuery]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[PMLE]]></category>
		<category><![CDATA[Vertex AI]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[監督式學習]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=12787</guid>

					<description><![CDATA[<p>資料前處理怎麼做？用連鎖飲料店資料算給你看標準化、對數縮放、截斷、遺失值補中位數、One-hot 與雜湊分桶，附 BigQuery ML 自動前處理、TRANSFORM 寫法與 PMLE 考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">資料前處理怎麼做？標準化、遺失值、高基數類別</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>資料前處理怎麼做？把數字縮放到差不多大小、把缺的值補好並做記號、把類別轉成數字，類別太多就用雜湊或嵌入。</strong></p>



<p class="wp-block-paragraph">這篇繼續用手搖飲料店當例子，不過這次是有 2,000 間分店的連鎖店。我們會把一張「原始資料表」一步一步整理成模型吃得下的樣子，每一步都帶數字算一次，最後看 BigQuery ML 哪些步驟會自動幫你做、哪些要自己寫。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-01-overview.png" alt="資料前處理怎麼做：數字差太多要縮放、有缺值要補並做記號、類別要轉成數字、類別太多用雜湊或嵌入" class="wp-image-12782" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-01-overview.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-01-overview-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-01-overview-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-01-overview-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>模型只看得懂數字</strong>：「晴天」「雨天」、分店代碼「A0127」，模型都不認得，要先轉成數字</li>

<li><strong>資料一定是髒的</strong>：溫度計會壞、店員會漏填、某天包場營業額暴增。Google 速成課程也提醒：夠大的資料集，幾乎一定有不合規則的怪值</li>

<li><strong>前處理做錯，比模型選錯更傷</strong>：數字大小差太多，模型訓練得很慢；缺值亂補，模型學到錯的規律；前處理偷看了測試資料，就是<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">第 8 篇的資料洩漏</a></li>

<li><strong>證照必考</strong>：PMLE 考試指南第 2 區明列「探索與前處理資料」，第 5 區還有「確保訓練和上線的前處理一致」</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">先看全貌：一張原始資料表有哪些問題</h2>



<p class="wp-block-paragraph">假設（教學用的數字）連鎖飲料店每間分店、每一天都有一筆紀錄，要預測<strong>當天賣幾杯</strong>：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>欄位</th><th>範例</th><th>問題</th><th>處理方法</th></tr></thead><tbody><tr><td>氣溫</td><td>15～35 度</td><td>有幾天溫度計壞了，<strong>沒有值</strong></td><td>補值＋做記號</td></tr><tr><td>前一天營業額</td><td>2,000～80,000 元</td><td>跟氣溫差了好幾千倍，<strong>大小不一</strong></td><td>縮放（標準化）</td></tr><tr><td>某天營業額</td><td>500,000 元</td><td>公司包場，<strong>極端值</strong></td><td>截斷</td></tr><tr><td>天氣</td><td>晴、陰、雨</td><td><strong>是文字</strong>，模型看不懂</td><td>One-hot 編碼</td></tr><tr><td>分店代碼</td><td>A0001～A2000</td><td>有 2,000 種，<strong>類別太多</strong></td><td>雜湊分桶或嵌入</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>資料前處理</strong>（Data Preprocessing）：訓練模型之前，把原始資料<strong>清乾淨、轉成數字、調整到適合的大小</strong>的這些步驟。</p>



<p class="wp-block-paragraph">比喻：像<strong>煮菜前的備料</strong>。菜要洗、要切、要去掉壞掉的部分，大小切得差不多，才能一起下鍋。再好的廚師（模型），拿到沒洗的菜也煮不好。</p>



<p class="wp-block-paragraph">下面一個問題、一個問題處理。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">1. 數字大小差太多：縮放（Normalization）</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>縮放</strong>：把不同特徵的數字，<strong>換算到差不多的範圍</strong>，例如都變成 0 到 1 之間，或都以 0 為中心。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>把不同國家的價錢換算成同一種貨幣</strong>。日幣 1,000 和美金 10，數字差 100 倍，但不換算的話，你會以為日幣的東西貴很多。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph"><a href="https://developers.google.com/machine-learning/crash-course/numerical-data/normalization">Google 機器學習速成課程</a>舉的例子：一個特徵從 154 到 24,917,482，另一個只從 5 到 22，範圍差太多了。縮放的好處：</p>


<ul class="wp-block-list">
<li><strong>訓練收斂比較快</strong>：數字範圍差很多時，模型在修正參數時會「彈來彈去」，很難穩定</li>

<li><strong>模型不會偏心</strong>：沒縮放的話，數字大的特徵（營業額）很容易被模型看得比數字小的特徵（氣溫）重要</li>

<li><strong>避免數字爆掉</strong>：數字太大時，計算可能超出電腦能表示的範圍，出現 NaN（不是數字）</li>
</ul>



<h3 class="wp-block-heading">四種常見做法，各算一次</h3>



<p class="wp-block-paragraph"><strong>做法 1：線性縮放</strong>（Linear Scaling，也叫 Min-Max 縮放），換算到 0～1：</p>



<pre class="wp-block-code"><code>縮放後 = (原始值 − 最小值) ÷ (最大值 − 最小值)

前一天營業額 41,000 元，範圍 2,000～80,000：
= (41,000 − 2,000) ÷ (80,000 − 2,000)
= 39,000 ÷ 78,000
= 0.5</code></pre>



<p class="wp-block-paragraph">最小值變 0、最大值變 1、正中間變 0.5。</p>



<p class="wp-block-paragraph"><strong>做法 2：Z 分數標準化</strong>（Z-score，也就是第 8 篇提過的標準化），換算成「跟平均差幾個標準差」：</p>



<pre class="wp-block-code"><code>Z 分數 = (原始值 − 平均) ÷ 標準差

氣溫平均 25 度、標準差 5 度：
35 度 → (35 − 25) ÷ 5 = +2.0（比平均熱 2 個標準差）
20 度 → (20 − 25) ÷ 5 = −1.0（比平均冷 1 個標準差）</code></pre>



<p class="wp-block-paragraph"><strong>標準差</strong>白話說就是「數字通常離平均多遠」。標準差 5 度，代表大部分的日子落在平均上下 5 度左右。</p>



<p class="wp-block-paragraph"><strong>做法 3：對數縮放</strong>（Log Scaling），把差很多倍的數字拉近：</p>



<pre class="wp-block-code"><code>分店的網路評論數：10、100、1,000、10,000 則
取自然對數 ln 之後：2.3、4.6、6.9、9.2</code></pre>



<p class="wp-block-paragraph">原本最大和最小差 <strong>1,000 倍</strong>，取對數後只差 <strong>4 倍</strong>。適合「少數很大、大多很小」的資料，例如評論數、粉絲數、收入。</p>



<p class="wp-block-paragraph"><strong>做法 4：截斷</strong>（Clipping），把極端值壓回上限：</p>



<pre class="wp-block-code"><code>某天公司包場，營業額 500,000 元
平常最高 80,000 元 → 設上限 80,000
500,000 → 截成 80,000</code></pre>



<p class="wp-block-paragraph">速成課程說這個方法「很奇怪，但非常有效」：極端值少見，卻會把縮放後的數字全部擠成一團。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-02-scaling.png" alt="數字縮放怎麼算：線性縮放 41,000 元變 0.5，Z 分數 35 度變 +2.0，對數縮放 10 到 10,000 變 2.3 到 9.2，截斷 500,000 壓回 80,000" class="wp-image-12783" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-02-scaling.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-02-scaling-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-02-scaling-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-02-scaling-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">什麼時候用哪一種</h3>



<p class="wp-block-paragraph">依照 Google 速成課程的整理：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>做法</th><th>公式</th><th>適合的資料</th></tr></thead><tbody><tr><td>線性縮放</td><td>(x − 最小) ÷ (最大 − 最小)</td><td>數值在範圍內<strong>分布平均</strong></td></tr><tr><td>Z 分數</td><td>(x − 平均) ÷ 標準差</td><td>大多集中在平均附近（<strong>鐘形</strong>）</td></tr><tr><td>對數縮放</td><td>ln(x)</td><td>一邊拖著<strong>長長的尾巴</strong>（少數極大）</td></tr><tr><td>截斷</td><td>超過上限就設成上限</td><td>有<strong>極端離群值</strong></td></tr></tbody></table></figure>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">兩個重點一定要記住：</p>


<ol class="wp-block-list">
<li><strong>最小值、最大值、平均、標準差，都只能用訓練集算</strong>，再套到驗證、測試和上線資料（第 8 篇的「先切再算」）</li>

<li><strong>訓練和上線要用同一套算法</strong>。速成課程特別提醒：訓練時縮放了，預測時也要用同樣的方式縮放，結果才準</li>
</ol>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">2. 資料有缺：遺失值（Missing Values）</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>遺失值</strong>：某一筆資料的某個欄位<strong>沒有值</strong>，在資料庫裡通常顯示成 <code>NULL</code>（空的）。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>問卷有幾題沒填</strong>。整份丟掉很可惜，亂猜一個答案又可能猜錯。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph"><a href="https://developers.google.com/machine-learning/crash-course/overfitting/data-characteristics">Google 速成課程</a>把「漏填的值」列為資料不可靠的常見原因之一，例如有人忘了填房子的屋齡。處理方式有兩大類：</p>


<ol class="wp-block-list">
<li><strong>刪掉</strong>：缺值的那幾筆不要用。資料很多、缺得很少時可以這樣做</li>

<li><strong>補值</strong>（Imputation）：用一個合理的數字補上，常見的是<strong>平均數、中位數</strong>，文字類別則補<strong>最常出現的值</strong></li>
</ol>



<p class="wp-block-paragraph">速成課程還建議：補值時<strong>另外加一欄「這格是補的」</strong>，讓模型知道哪些值是真的、哪些是猜的。</p>



<h3 class="wp-block-heading">算一次給你看：平均數還是中位數？</h3>



<p class="wp-block-paragraph">假設（教學用的數字）某間分店 6 天的氣溫，有 2 天溫度計壞了：</p>



<pre class="wp-block-code"><code>28、30、缺、32、40、缺</code></pre>



<p class="wp-block-paragraph"><strong>用平均數補</strong>：</p>



<pre class="wp-block-code"><code>平均 = (28 + 30 + 32 + 40) ÷ 4 = 130 ÷ 4 = 32.5 度</code></pre>



<p class="wp-block-paragraph"><strong>用中位數補</strong>（從小排到大，取正中間；有偶數個就取中間兩個的平均）：</p>



<pre class="wp-block-code"><code>排序：28、30、32、40
中位數 = (30 + 32) ÷ 2 = 31 度</code></pre>



<p class="wp-block-paragraph">再加一欄記號：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>天</th><th>氣溫（原始）</th><th>氣溫（補值後）</th><th>氣溫是補的</th></tr></thead><tbody><tr><td>1</td><td>28</td><td>28</td><td>0</td></tr><tr><td>2</td><td>30</td><td>30</td><td>0</td></tr><tr><td>3</td><td>缺</td><td><strong>31</strong></td><td><strong>1</strong></td></tr><tr><td>4</td><td>32</td><td>32</td><td>0</td></tr><tr><td>5</td><td>40</td><td>40</td><td>0</td></tr><tr><td>6</td><td>缺</td><td><strong>31</strong></td><td><strong>1</strong></td></tr></tbody></table></figure>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-03-missing-values.png" alt="遺失值怎麼補：28、30、32、40 的平均是 32.5，被 40 度拉高；中位數是 31，比較穩；補值後加一欄記號標出哪些是補的" class="wp-image-12784" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-03-missing-values.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-03-missing-values-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-03-missing-values-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-03-missing-values-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">數字怎麼看</h3>


<ul class="wp-block-list">
<li>平均數 32.5 被那一天 <strong>40 度</strong>拉高了；中位數 31 比較不受極端值影響。<strong>資料有極端值時，中位數比較穩</strong></li>

<li>「是補的」這一欄很有用：如果溫度計都在<strong>颱風天</strong>壞掉，那「缺值」本身就藏著資訊，模型可以學到</li>

<li>補值用的平均數、中位數，一樣<strong>只能用訓練集算</strong></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">3. 文字類別：One-hot 編碼</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>One-hot 編碼</strong>：一個有 N 種可能的類別，變成 <strong>N 個 0 或 1 的欄位</strong>，屬於哪一種，那一欄就是 1，其他都是 0。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>問卷的勾選題</strong>：晴、陰、雨三個框，只能勾一個。勾到的是 1，沒勾的是 0。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">One-hot 的意思是「只有一個是熱的（亮的）」。<a href="https://developers.google.com/machine-learning/crash-course/categorical-data/one-hot-encoding">Google 速成課程</a>的定義：每個類別用一串 N 個數字表示，<strong>剛好一個是 1，其他都是 0</strong>。</p>



<h3 class="wp-block-heading">算一次給你看</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>天氣</th><th>天氣_晴</th><th>天氣_陰</th><th>天氣_雨</th></tr></thead><tbody><tr><td>晴</td><td>1</td><td>0</td><td>0</td></tr><tr><td>陰</td><td>0</td><td>1</td><td>0</td></tr><tr><td>雨</td><td>0</td><td>0</td><td>1</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>為什麼不直接編成 1、2、3？</strong> 如果晴 = 1、陰 = 2、雨 = 3，模型會以為「雨是晴的 3 倍」「陰在晴和雨的正中間」。天氣沒有大小順序，用 1、2、3 會讓模型學到不存在的關係。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">BigQuery ML 遇到文字欄位，<strong>大部分模型會自動做 One-hot</strong>，你不用自己轉（後面會講）。但類別一多，One-hot 就會出問題，這就是下一段。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">4. 類別太多：高基數類別（High Cardinality）</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>基數</strong>（Cardinality）：一個欄位<strong>有幾種不同的值</strong>。天氣只有 3 種，基數是 3；分店代碼有 2,000 種，基數是 2,000。<strong>高基數類別</strong>就是種類多到 One-hot 不好處理的類別欄位。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>問卷的勾選題有 2,000 個選項</strong>。表格會變得超大，而且大部分的框都是空的；有些選項全部問卷加起來只有一兩個人勾，根本看不出規律。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">速成課程舉的例子：英文單字約 50 萬個、德國的姓氏約 85 萬個。類別這麼多時，<strong>One-hot 通常是不好的選擇</strong>。分店代碼、會員編號、商品編號、郵遞區號，都是常見的高基數類別。</p>



<h3 class="wp-block-heading">算一次給你看：三種做法要幾個欄位</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>做法</th><th>白話</th><th>欄位數</th></tr></thead><tbody><tr><td>One-hot</td><td>每間分店一欄</td><td><strong>2,000</strong> 欄（每列只有 1 個 1，其他 1,999 個都是 0）</td></tr><tr><td>雜湊分桶</td><td>分店丟進 200 個桶子</td><td><strong>200</strong> 欄</td></tr><tr><td>嵌入</td><td>每間分店用一小串數字描述</td><td>例如 <strong>8</strong> 個數字</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>雜湊分桶</strong>（Hash Bucketing）：用一個固定的公式（雜湊函數）把每個分店代碼換成一個號碼，再除以桶子數取餘數，決定丟進哪個桶子。筆記裡的「One-Hot Hash Buckets」就是這個做法。</p>



<pre class="wp-block-code"><code>2,000 間分店 ÷ 200 個桶子 = 平均每桶 10 間分店</code></pre>


<ul class="wp-block-list">
<li><strong>好處</strong>：欄位從 2,000 降到 200；而且<strong>新開的分店</strong>也能算出桶號，不會沒地方放</li>

<li><strong>代價</strong>：同一個桶子裡的 10 間分店，模型會把它們當成同一間，這叫<strong>碰撞</strong>（Collision）。桶子越多，碰撞越少，但欄位越多</li>
</ul>



<p class="wp-block-paragraph"><strong>嵌入</strong>（Embedding）：讓模型<strong>自己學</strong>一小串數字來描述每間分店，例如 8 個數字。生意型態相似的分店，學出來的數字也會相近。速成課程說，類別很多時，<strong>嵌入通常比 One-hot 好得多</strong>，訓練比較快、預測也比較快。嵌入在第 11 篇特徵工程會細講。</p>



<p class="wp-block-paragraph"><strong>另一個常用的小技巧</strong>：很少出現的類別（例如只出現幾次的分店），全部歸成一類「其他」，速成課程叫它<strong>詞彙外</strong>（Out-of-vocabulary，OOV）桶子，模型只要為它學一個權重。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-04-high-cardinality.png" alt="高基數類別怎麼處理：2,000 間分店用 One-hot 要 2,000 欄，雜湊分桶到 200 個桶子平均每桶 10 間，嵌入只要 8 個數字" class="wp-image-12785" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-04-high-cardinality.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-04-high-cardinality-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-04-high-cardinality-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-04-high-cardinality-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">高基數類別處理不好，模型會變得又大又慢，還很容易對「出現很少次的類別」過度擬合（<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">第 7 篇</a>）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">補充：圖片資料怎麼前處理</h2>



<p class="wp-block-paragraph">筆記裡提到圖片資料要用 <strong>TFRecords</strong> 存在 <strong>Cloud Storage</strong>（Google 的雲端檔案儲存空間）。圖片的前處理常見的是：統一尺寸、把像素值從 0～255 縮放到 0～1。大量圖片要讀得快，會打包成 TFRecords 這種格式，<a href="https://dongdonggcp.com/2026/10/25/tfrecords-tf-data-prefetch-input-pipeline/">第 13 篇</a>會專門講。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">五個問題一張表比完</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>問題</th><th>處理方法</th><th>一句話</th><th>注意</th></tr></thead><tbody><tr><td>數字大小差很多</td><td>線性縮放、Z 分數</td><td>換算成同一種貨幣</td><td>統計值只用訓練集算</td></tr><tr><td>少數極大、大多很小</td><td>對數縮放</td><td>把差很多倍的數字拉近</td><td>數值要大於 0</td></tr><tr><td>極端值</td><td>截斷</td><td>超過上限就壓回上限</td><td>先確認是不是輸入錯誤</td></tr><tr><td>有缺值</td><td>刪除、補平均數／中位數、加記號</td><td>問卷沒填的題目</td><td>有極端值時用中位數</td></tr><tr><td>文字類別</td><td>One-hot</td><td>勾選題</td><td>不要編成 1、2、3</td></tr><tr><td>類別太多</td><td>雜湊分桶、嵌入、OOV</td><td>2,000 個選項的勾選題</td><td>雜湊會碰撞</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">在 GCP 上怎麼做</h2>



<p class="wp-block-paragraph"><strong>GCP（Google Cloud Platform）</strong> 是 Google 的雲端服務，白話說就是<strong>租用 Google 機房裡的電腦和工具</strong>。</p>



<h3 class="wp-block-heading">1. BigQuery ML：很多步驟會自動做</h3>


<ul class="wp-block-list">
<li><strong>BigQuery</strong>：Google 的大型資料倉庫，專門存放和分析超大量的表格資料</li>

<li><strong>BigQuery ML</strong>：讓你<a href="https://docs.cloud.google.com/bigquery/docs/bqml-introduction">用 SQL（跟資料庫說話的語言）直接在 BigQuery 裡訓練模型</a></li>
</ul>



<p class="wp-block-paragraph">依照<a href="https://docs.cloud.google.com/bigquery/docs/auto-preprocessing">自動前處理的官方文件</a>，你什麼都不寫，BigQuery ML 訓練時就會：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>欄位類型</th><th>自動做什麼</th></tr></thead><tbody><tr><td>數字（INT64、FLOAT64 等）</td><td><strong>標準化</strong>（大部分模型）；提升樹、隨機森林不做</td></tr><tr><td>數字欄位的 <code>NULL</code></td><td>訓練和預測時都<strong>補平均數</strong></td></tr><tr><td>文字、布林、日期等</td><td><strong>One-hot 編碼</strong>；提升樹、隨機森林改用標籤編碼（每種值給一個號碼）</td></tr><tr><td>文字欄位的 <code>NULL</code></td><td>多開一個類別放它們；預測時遇到<strong>沒看過的新值</strong>，權重當 0</td></tr><tr><td>時間戳記 <code>TIMESTAMP</code></td><td>拆出星期幾、月份、幾點等，分別處理</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>想自己控制</strong>，就把前處理寫在 <a href="https://docs.cloud.google.com/bigquery/docs/manual-preprocessing"><code>TRANSFORM</code></a> 裡。下面把這篇的處理方法全部寫進去（教學用的範例）：</p>



<pre class="wp-block-code"><code>CREATE MODEL `shop.daily_cups_prep`
TRANSFORM(
  ML.IMPUTER(temperature, 'median') OVER() AS temperature_filled,   -- 缺值補中位數
  IF(temperature IS NULL, 1, 0) AS temperature_missing,             -- 記號：這格是補的
  ML.MIN_MAX_SCALER(LEAST(yesterday_revenue, 80000)) OVER()
    AS revenue_scaled,                                              -- 截斷後縮放到 0～1
  weather,                                                          -- 文字，自動 One-hot
  CAST(ML.HASH_BUCKETIZE(store_id, 200) AS STRING) AS store_bucket, -- 2,000 間分店分 200 桶
  cups_sold)
OPTIONS(model_type='LINEAR_REG',
        input_label_cols=['cups_sold']) AS
SELECT temperature, yesterday_revenue, weather, store_id, cups_sold
FROM `shop.store_daily_train`;</code></pre>



<p class="wp-block-paragraph">逐行翻成白話：</p>


<ul class="wp-block-list">
<li><a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-imputer"><code>ML.IMPUTER(temperature, 'median')</code></a>：氣溫缺值補<strong>中位數</strong>（也可以選 <code>mean</code> 平均、<code>most_frequent</code> 最常見）</li>

<li><code>IF(temperature IS NULL, 1, 0)</code>：加一欄「是補的」記號</li>

<li><code>LEAST(yesterday_revenue, 80000)</code>：超過 80,000 的壓回 80,000（截斷），再用 <code>ML.MIN_MAX_SCALER</code> 縮放到 0～1</li>

<li><code>weather</code>：直接放進去，BigQuery ML 自動 One-hot</li>

<li><a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-hash-bucketize"><code>ML.HASH_BUCKETIZE(store_id, 200)</code></a>：分店代碼分成 200 桶；轉成文字（<code>CAST ... AS STRING</code>），桶號才會被當成類別，而不是大小有意義的數字</li>
</ul>



<p class="wp-block-paragraph">依照官方文件，<code>TRANSFORM</code> 裡這類要看整欄資料才能算的函數（後面要加 <code>OVER()</code>），<strong>訓練時算出來的統計值，預測時會自動沿用</strong>。所以上線預測時，氣溫缺值一樣補訓練期間的中位數，不會用到新資料，也不會前後不一致。訓練完還可以用 <code>ML.TRANSFORM</code> 看處理後的資料長什麼樣子。</p>



<h3 class="wp-block-heading">2. 資料很大時，用哪個工具做前處理</h3>



<p class="wp-block-paragraph">PMLE 考試指南寫得很明白：要<strong>依照資料量和複雜度</strong>選前處理工具，例子有 BigQuery（SQL）、Dataflow、Apache Spark 和記憶體內的 Python 工具。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>情況</th><th>工具</th><th>白話</th></tr></thead><tbody><tr><td>資料不大，筆電放得下</td><td>pandas 等 Python 工具</td><td>在一台電腦的記憶體裡處理</td></tr><tr><td>大量表格資料，SQL 寫得出來</td><td><strong>BigQuery</strong></td><td>直接在資料倉庫裡用 SQL 處理</td></tr><tr><td>大量資料，要做成批次或即時的處理管線</td><td><strong>Dataflow</strong></td><td>Google 全代管的資料處理服務，可以同時處理批次和串流資料</td></tr><tr><td>已經有 Spark 程式</td><td><strong>Dataproc</strong> 上跑 Spark</td><td>Google 代管的 Hadoop／Spark 叢集，站上有<a href="https://dongdonggcp.com/2025/04/23/whai-is-dataproc-architecture-and-usage-introduction/">一篇介紹</a></td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>串流</strong>（Streaming）白話就是「資料一直源源不絕地進來」，例如每一筆刷卡交易；<strong>批次</strong>（Batch）是「累積一大包再一次處理」，例如每天半夜跑一次。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>舊題庫可能還會看到 Vertex AI，現在叫 Gemini Enterprise Agent Platform。</strong><br>Google Cloud 在 2026 年 4 月 22 日把 Vertex AI 改名（<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/vertex-ai-name-changes">官方對照表</a>）。前處理好的特徵要給很多模型共用時，可以放進 Feature Store on Gemini Enterprise Agent Platform（原 Vertex AI Feature Store）。</p>
</blockquote>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">考試會怎麼考</h2>



<p class="wp-block-paragraph">Google Cloud <strong>Professional Machine Learning Engineer（PMLE，專業機器學習工程師）</strong> 證照，2026 年 6 月 1 日起的<a href="https://services.google.com/fh/files/misc/professional_machine_learning_engineer_exam_guide_english_new.pdf">官方考試指南</a>裡，這篇的內容對應到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考試區塊</th><th>跟這篇有關的項目</th></tr></thead><tbody><tr><td>第 1 區：用低程式碼方式打造 AI 方案（約 13%）</td><td>用 BigQuery ML 做特徵工程</td></tr><tr><td>第 2 區：跨團隊管理資料與模型（約 16%）</td><td><strong>探索與前處理資料</strong>、<strong>依資料量與複雜度選前處理工具</strong></td></tr><tr><td>第 5 區：自動化與協調 ML 管線（約 18%）</td><td><strong>確保訓練和上線的前處理一致</strong></td></tr></tbody></table></figure>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-05-exam-keywords.png" alt="PMLE 考試關鍵字：特徵範圍差很多想到標準化，有極端值想到中位數或截斷，類別太多想到雜湊或嵌入，訓練上線前處理一致想到 TRANSFORM" class="wp-image-12786" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-05-exam-keywords.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-05-exam-keywords-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-05-exam-keywords-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml10-05-exam-keywords-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目出現的關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「特徵範圍差很多」「訓練收斂很慢」</td><td><strong>標準化／縮放</strong></td></tr><tr><td>「少數值特別大」「長尾分布」</td><td><strong>對數縮放</strong></td></tr><tr><td>「有極端離群值」</td><td><strong>截斷</strong>；補值改用<strong>中位數</strong></td></tr><tr><td>「有缺值」</td><td>刪除或補值，並<strong>加一欄記號</strong></td></tr><tr><td>「類別欄位轉數字」「沒有大小順序」</td><td><strong>One-hot</strong>，不要編成 1、2、3</td></tr><tr><td>「類別有幾萬、幾十萬種」</td><td><strong>雜湊分桶</strong>或<strong>嵌入</strong></td></tr><tr><td>「預測時出現沒看過的新類別」</td><td>雜湊分桶、OOV 桶子</td></tr><tr><td>「訓練和上線的前處理要一致」</td><td>BigQuery ML 的 <code>TRANSFORM</code></td></tr><tr><td>「資料量很大、要串流處理」</td><td><strong>Dataflow</strong></td></tr><tr><td>「已經有 Spark 程式」</td><td><strong>Dataproc</strong></td></tr></tbody></table></figure>



<h3 class="wp-block-heading">三個常見陷阱</h3>


<ol class="wp-block-list">
<li><strong>用全部資料算平均再切</strong>：縮放、補值用的統計值，只能用訓練集算</li>

<li><strong>類別編成 1、2、3</strong>：沒有順序的類別要用 One-hot，否則模型會學到不存在的大小關係</li>

<li><strong>上線時忘了做一樣的前處理</strong>：訓練時縮放過、上線時沒縮放，模型拿到的數字完全不一樣，表現會暴跌</li>
</ol>



<h3 class="wp-block-heading">練習情境（自己出的練習，不是真實考題）</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">一家電商用 BigQuery ML 訓練模型，預測訂單會不會退貨。特徵包括商品價格（50～80,000 元）、顧客編號（約 300 萬個）、付款方式（4 種）。上線後發現，預測服務收到的價格沒有經過和訓練時一樣的縮放，結果很差。應該怎麼調整？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「訓練和上線的前處理不一致」→ 把縮放寫進 BigQuery ML 的 <strong><code>TRANSFORM</code></strong>，訓練時的統計值預測時自動沿用</li>

<li>「顧客編號 300 萬個」→ <strong>高基數</strong>，不要 One-hot，改用<strong>雜湊分桶</strong>（<code>ML.HASH_BUCKETIZE</code>）或嵌入，或考慮這個特徵到底有沒有用</li>

<li>「付款方式 4 種」→ 文字欄位，BigQuery ML <strong>自動 One-hot</strong></li>

<li>「價格範圍很大」→ 標準化；如果少數商品特別貴，考慮<strong>對數縮放</strong></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">資料前處理是什麼？</h3>



<p class="wp-block-paragraph">資料前處理是訓練模型之前，把原始資料清乾淨、轉成數字、調整到適合大小的步驟，包括縮放數字、補遺失值、把文字類別轉成數字、處理極端值等。就像煮菜前的備料，菜洗好切好，才能一起下鍋。</p>



<h3 class="wp-block-heading">標準化和正規化差在哪？</h3>



<p class="wp-block-paragraph">這兩個詞在不同教材裡用法不一樣。常見的說法是：線性縮放（Min-Max）把數字換算到 0～1，Z 分數標準化把數字換算成「跟平均差幾個標準差」。Google 速成課程把這些統稱為 normalization，並依資料分布建議用哪一種。</p>



<h3 class="wp-block-heading">什麼時候要做特徵縮放？</h3>



<p class="wp-block-paragraph">當不同特徵的數字範圍差很多時，例如營業額幾萬、氣溫幾十。縮放可以讓模型訓練收斂得比較快，也避免模型偏向數字大的特徵。BigQuery ML 大部分模型會自動標準化數字欄位，但提升樹和隨機森林不做，因為樹狀模型不受數字大小影響。</p>



<h3 class="wp-block-heading">遺失值要刪掉還是補值？</h3>



<p class="wp-block-paragraph">資料很多、缺得很少，可以直接刪；缺得多就要補值。數字常用平均數或中位數補，有極端值時中位數比較穩；文字類別補最常出現的值。Google 速成課程建議補值後另外加一欄記號，讓模型知道哪些值是補的。</p>



<h3 class="wp-block-heading">One-hot 編碼是什麼？為什麼不能直接編成 1、2、3？</h3>



<p class="wp-block-paragraph">One-hot 編碼把一個有 N 種值的類別，變成 N 個 0 或 1 的欄位，屬於哪一種那一欄就是 1。如果直接編成 1、2、3，模型會以為類別之間有大小和倍數關係，例如「雨是晴的 3 倍」，學到不存在的規律。</p>



<h3 class="wp-block-heading">高基數類別是什麼？要怎麼處理？</h3>



<p class="wp-block-paragraph">高基數類別是種類非常多的類別欄位，例如會員編號、商品編號、郵遞區號。用 One-hot 會產生幾千、幾萬個欄位。常見處理方法是雜湊分桶（把類別丟進固定數量的桶子）、嵌入（讓模型學一小串數字描述每個類別），以及把很少出現的類別歸成一類「其他」。</p>



<h3 class="wp-block-heading">雜湊分桶有什麼缺點？</h3>



<p class="wp-block-paragraph">不同的類別可能被分到同一個桶子，這叫碰撞，模型會把它們當成同一個類別。例如 2,000 間分店分成 200 個桶子，平均每個桶子有 10 間分店。桶子越多碰撞越少，但欄位也越多，要在兩者之間取捨。</p>



<h3 class="wp-block-heading">BigQuery ML 會自動做哪些前處理？</h3>



<p class="wp-block-paragraph">依照官方文件，大部分模型會自動標準化數字欄位、數字缺值補平均數、文字等欄位做 One-hot 編碼、文字缺值另開一類，時間戳記拆成星期幾、月份等。想自己控制可以寫在 TRANSFORM 裡，例如 ML.IMPUTER、ML.MIN_MAX_SCALER、ML.HASH_BUCKETIZE，訓練時算出的統計值預測時會自動沿用。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>縮放</strong>：數字範圍差很多時，用線性縮放（0～1）或 Z 分數；長尾用對數、極端值用截斷；統計值<strong>只用訓練集算</strong></li>

<li><strong>遺失值</strong>：刪除或補值；有極端值用<strong>中位數</strong>；補完<strong>加一欄記號</strong></li>

<li><strong>One-hot</strong>：沒有順序的類別變成多個 0／1 欄位，不要編成 1、2、3</li>

<li><strong>高基數類別</strong>：One-hot 太大，用<strong>雜湊分桶</strong>（會碰撞）、<strong>嵌入</strong>或 OOV 桶子</li>

<li>BigQuery ML 自動標準化、補平均、One-hot；自己控制寫進 <strong><code>TRANSFORM</code></strong>，訓練和上線自動一致；資料很大選 BigQuery、Dataflow 或 Dataproc</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/20/types-of-machine-learning-supervised-unsupervised-reinforcement/">機器學習有哪幾種？監督式、非監督式、強化學習一次看懂</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/10/20/classification-vs-regression-mae-rmse/">分類和迴歸差在哪？一個例子搞懂，附 MAE、RMSE 計算</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">特徵、標籤、超參數是什麼？機器學習 5 個必懂名詞</a></li>

<li>第 4 篇：<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">訓練集、驗證集、測試集怎麼切？時間序列為什麼不能亂切</a></li>

<li>第 5 篇：<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">混淆矩陣是什麼？用快篩搞懂準確率、精確率、召回率、F1</a></li>

<li>第 6 篇：<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">ROC 曲線和 AUC 怎麼看？門檻怎麼調、AUC-PR 差在哪</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">過度擬合是什麼？正則化、Dropout、提前停止 3 招解決</a></li>

<li>第 8 篇：<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">資料洩漏是什麼？模型考試作弊的 3 種常見情況</a></li>

<li>上一篇：第 9 篇：<a href="https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/">類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</a></li>

<li>下一篇：第 11 篇：<a href="https://dongdonggcp.com/2026/10/25/feature-engineering-feature-cross-embedding-data-augmentation/">特徵工程是什麼？特徵交叉、詞嵌入、資料增強一次看懂</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/07/04/is-bigquery-a-database-what-is-the-usage/">BigQuery 不就是查詢嗎？跟資料庫差在哪裡？能做什麼分析？</a></li>

<li><a href="https://dongdonggcp.com/2025/04/23/whai-is-dataproc-architecture-and-usage-introduction/">Dataproc 是什麼？架構與用法介紹</a></li>

<li><a href="https://dongdonggcp.com/2024/10/01/how-to-pass-gcp-data-engineer-certification-test/">GCP Data Engineer 證照怎麼準備</a></li>

<li><a href="https://dongdonggcp.com/2025/04/27/gcp-learning-roadmap/">GCP 學習路徑 Learning Roadmap 和八大關卡</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">資料前處理沒有一個步驟是炫技的，但每一步都決定模型拿到的是「乾淨的食材」還是「沒洗的菜」。下一篇的特徵工程，會在這個基礎上，教你怎麼把資料變得更有用。如果你想有系統地從雲端基礎一路學到在 GCP 上動手做機器學習，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "資料前處理是什麼？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "資料前處理是訓練模型之前，把原始資料清乾淨、轉成數字、調整到適合大小的步驟，包括縮放數字、補遺失值、把文字類別轉成數字、處理極端值等。就像煮菜前的備料，菜洗好切好，才能一起下鍋。"
      }
    },
    {
      "@type": "Question",
      "name": "標準化和正規化差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "這兩個詞在不同教材裡用法不一樣。常見的說法是：線性縮放（Min-Max）把數字換算到 0～1，Z 分數標準化把數字換算成「跟平均差幾個標準差」。Google 速成課程把這些統稱為 normalization，並依資料分布建議用哪一種。"
      }
    },
    {
      "@type": "Question",
      "name": "什麼時候要做特徵縮放？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "當不同特徵的數字範圍差很多時，例如營業額幾萬、氣溫幾十。縮放可以讓模型訓練收斂得比較快，也避免模型偏向數字大的特徵。BigQuery ML 大部分模型會自動標準化數字欄位，但提升樹和隨機森林不做，因為樹狀模型不受數字大小影響。"
      }
    },
    {
      "@type": "Question",
      "name": "遺失值要刪掉還是補值？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "資料很多、缺得很少，可以直接刪；缺得多就要補值。數字常用平均數或中位數補，有極端值時中位數比較穩；文字類別補最常出現的值。Google 速成課程建議補值後另外加一欄記號，讓模型知道哪些值是補的。"
      }
    },
    {
      "@type": "Question",
      "name": "One-hot 編碼是什麼？為什麼不能直接編成 1、2、3？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "One-hot 編碼把一個有 N 種值的類別，變成 N 個 0 或 1 的欄位，屬於哪一種那一欄就是 1。如果直接編成 1、2、3，模型會以為類別之間有大小和倍數關係，例如「雨是晴的 3 倍」，學到不存在的規律。"
      }
    },
    {
      "@type": "Question",
      "name": "高基數類別是什麼？要怎麼處理？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "高基數類別是種類非常多的類別欄位，例如會員編號、商品編號、郵遞區號。用 One-hot 會產生幾千、幾萬個欄位。常見處理方法是雜湊分桶（把類別丟進固定數量的桶子）、嵌入（讓模型學一小串數字描述每個類別），以及把很少出現的類別歸成一類「其他」。"
      }
    },
    {
      "@type": "Question",
      "name": "雜湊分桶有什麼缺點？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不同的類別可能被分到同一個桶子，這叫碰撞，模型會把它們當成同一個類別。例如 2,000 間分店分成 200 個桶子，平均每個桶子有 10 間分店。桶子越多碰撞越少，但欄位也越多，要在兩者之間取捨。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 會自動做哪些前處理？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "依照官方文件，大部分模型會自動標準化數字欄位、數字缺值補平均數、文字等欄位做 One-hot 編碼、文字缺值另開一類，時間戳記拆成星期幾、月份等。想自己控制可以寫在 TRANSFORM 裡，例如 ML.IMPUTER、ML.MIN_MAX_SCALER、ML.HASH_BUCKETIZE，訓練時算出的統計值預測時會自動沿用。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">資料前處理怎麼做？標準化、遺失值、高基數類別</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</title>
		<link>https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=class-imbalance-oversampling-downsampling-upweighting</link>
					<comments>https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 22 Oct 2026 13:08:03 +0000</pubDate>
				<category><![CDATA[AI 和機器學習]]></category>
		<category><![CDATA[證照考試]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[BigQuery]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[PMLE]]></category>
		<category><![CDATA[Vertex AI]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[監督式學習]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=12781</guid>

					<description><![CDATA[<p>類別不平衡怎麼辦？用 10,000 筆交易只有 100 筆盜刷的例子，算給你看過取樣、欠取樣加權、類別權重怎麼做，為什麼準確率 99% 也沒用，附 BigQuery ML 設定與 PMLE 考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/">類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>類別不平衡怎麼辦？先別看準確率，再用過取樣、欠取樣加權或類別權重，讓模型多注意那一小群少數資料。</strong></p>



<p class="wp-block-paragraph">這篇用信用卡盜刷當例子：10,000 筆交易裡只有 100 筆是盜刷。我們會一步一步算給你看，為什麼模型學不會抓盜刷、過取樣和欠取樣各怎麼做，以及 Google 推薦的「欠取樣再加權」為什麼一定要做第二步。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-01-imbalance.png" alt="類別不平衡是什麼：10,000 筆交易只有 100 筆盜刷，佔 1%；全部猜正常準確率 99%，但一筆盜刷都抓不到" class="wp-image-12777" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-01-imbalance.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-01-imbalance-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-01-imbalance-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-01-imbalance-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>真實世界的資料大多不平衡</strong>：盜刷、罕見疾病、設備故障、垃圾信，你最想抓的那一類，通常都是最少的那一類</li>

<li><strong>模型會「偷懶」</strong>：少數類別太少，模型只要一直猜多數類別，分數就很好看，<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">第 5 篇</a>算過，準確率 99% 也可能一個都沒抓到</li>

<li><strong>處理方法有順序、有陷阱</strong>：資料複製的時機錯了，會變成<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">第 8 篇的資料洩漏</a>；欠取樣少做一步，模型會高估風險好幾倍</li>

<li><strong>證照必考</strong>：PMLE 考題很愛問「詐騙只佔 0.1%，該怎麼訓練、怎麼評估」</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">類別不平衡（Class Imbalance）</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>類別不平衡</strong>：分類資料裡，<strong>某一類的數量遠遠少於另一類</strong>。</p>


<ul class="wp-block-list">
<li>數量多的那一類，叫<strong>多數類別</strong>（Majority Class），例如正常交易</li>

<li>數量少的那一類，叫<strong>少數類別</strong>（Minority Class），例如盜刷交易</li>
</ul>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>班上 99 個人講國語、只有 1 個人講台語</strong>。老師如果只照「大家最常說什麼」來學，很快就會國語說得很好，台語一句也學不會，因為練習的機會太少了。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph"><a href="https://developers.google.com/machine-learning/crash-course/overfitting/imbalanced-datasets">Google 機器學習速成課程</a>舉的例子：信用卡交易裡，盜刷可能<strong>不到 0.1%</strong>；醫療診斷資料裡，某種罕見病毒的病人可能<strong>不到 0.01%</strong>。速成課程也直接說：真實世界裡，<strong>不平衡的資料遠比平衡的資料常見</strong>。</p>



<p class="wp-block-paragraph">反過來，如果兩類數量差不多（例如 235 筆對 247 筆），就叫<strong>平衡的資料集</strong>。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">模型學不會少數類別，偏偏少數類別通常就是你<strong>最想抓</strong>的那一類。不處理的話，你會得到一個準確率很高、但完全沒用的模型。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">算一次給你看：為什麼模型學不會抓盜刷</h2>



<p class="wp-block-paragraph">假設（教學用的數字）銀行有 <strong>10,000 筆</strong>交易，其中 <strong>100 筆盜刷</strong>、9,900 筆正常：</p>



<pre class="wp-block-code"><code>盜刷比例 = 100 ÷ 10,000 = 1%</code></pre>



<h3 class="wp-block-heading">問題 1：偷懶就能拿高分</h3>



<p class="wp-block-paragraph">模型如果<strong>全部猜「正常」</strong>：</p>



<pre class="wp-block-code"><code>準確率 = 猜對的 ÷ 全部 = 9,900 ÷ 10,000 = 99%
召回率 = 抓到的盜刷 ÷ 全部盜刷 = 0 ÷ 100 = 0%</code></pre>



<p class="wp-block-paragraph">準確率 99%，一筆盜刷都沒抓到。這就是第 5 篇講的「準確率陷阱」。</p>



<h3 class="wp-block-heading">問題 2：練習時根本看不到盜刷</h3>



<p class="wp-block-paragraph">模型訓練時，不是一次看完 10,000 筆，而是<strong>一小批一小批</strong>地看（一批叫一個 <strong>Batch</strong>，<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">第 3 篇</a>講過的批次大小）。每批看完就修正一次。</p>



<p class="wp-block-paragraph">如果一批 100 筆，盜刷佔 1%：</p>



<pre class="wp-block-code"><code>每批平均有幾筆盜刷 = 100 × 1% = 1 筆
某一批「一筆盜刷都沒有」的機率 = 0.99 的 100 次方 ≈ 0.37</code></pre>



<p class="wp-block-paragraph">（每一筆是正常交易的機率是 0.99，100 筆全部都是正常，就是 0.99 連乘 100 次。）</p>



<p class="wp-block-paragraph">如果一批只有 20 筆：</p>



<pre class="wp-block-code"><code>某一批一筆盜刷都沒有的機率 = 0.99 的 20 次方 ≈ 0.82</code></pre>



<h3 class="wp-block-heading">數字怎麼看</h3>


<ul class="wp-block-list">
<li>一批 100 筆時，<strong>大約每 3 批就有 1 批完全沒有盜刷</strong>；就算有，通常也只有 1 筆</li>

<li>一批 20 筆時，<strong>超過 8 成的批次</strong>完全看不到盜刷</li>

<li>模型大部分時間都在練習「什麼是正常交易」，幾乎沒機會學「盜刷長什麼樣子」。Google 速成課程的說法一樣：<strong>嚴重不平衡時，大部分的批次裡根本沒有少數類別</strong></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">第一步永遠是：換掉評估方式</h2>



<p class="wp-block-paragraph">在動資料之前，先把「怎麼打分數」換掉，不然你根本看不出處理得好不好：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>不要看</th><th>改看</th><th>為什麼</th></tr></thead><tbody><tr><td>準確率（Accuracy）</td><td><strong>召回率</strong>（Recall）</td><td>盜刷抓到幾成，<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">第 5 篇</a></td></tr><tr><td></td><td><strong>精確率</strong>（Precision）</td><td>被抓的有幾成真的是盜刷</td></tr><tr><td></td><td><strong>F1 分數</strong></td><td>兩個都顧</td></tr><tr><td>AUC-ROC</td><td><strong>AUC-PR</strong></td><td>不平衡時 ROC 會被大量正常交易灌水，<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">第 6 篇</a></td></tr></tbody></table></figure>



<p class="wp-block-paragraph">另外，<strong>驗證集和測試集要保持真實比例</strong>（1% 盜刷）。下面介紹的過取樣、欠取樣，<strong>只能動訓練集</strong>，原因後面會講。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">解法 1：過取樣（Oversampling），把少的那一類複製多一點</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>過取樣</strong>：把少數類別的資料<strong>重複使用好幾次</strong>，讓它在訓練集裡變多。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>考前把錯最多的題型多抄幾份來練</strong>。題目本身沒有變多，但你練到的次數變多了。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">依照 <a href="https://developers.google.com/machine-learning/glossary#oversampling">Google 機器學習詞彙表</a>，過取樣就是<strong>重複使用少數類別的樣本</strong>，讓訓練集比較平衡。例如多數對少數是 5,000 比 1 時，100 萬筆資料裡只有約 200 筆少數類別，太少了，可以把這 200 筆重複使用很多次。</p>



<p class="wp-block-paragraph">除了直接複製，也有<strong>用相似的樣本「內插」出新資料</strong>的做法，最有名的是 <strong>SMOTE</strong>（Synthetic Minority Over-sampling Technique，合成少數類別過取樣），可以參考 <a href="https://imbalanced-learn.org/stable/over_sampling.html">imbalanced-learn 的說明</a>。</p>



<h3 class="wp-block-heading">算一次給你看</h3>



<p class="wp-block-paragraph">把 100 筆盜刷<strong>各複製成 10 份</strong>：</p>



<pre class="wp-block-code"><code>盜刷變成 = 100 × 10 = 1,000 筆
正常交易 = 9,900 筆（不動）
盜刷比例 = 1,000 ÷ (1,000 + 9,900) = 1,000 ÷ 10,900 ≈ 9.2%</code></pre>



<p class="wp-block-paragraph">盜刷從 1% 變成約 9.2%，每批 100 筆裡平均就有 9 筆盜刷可以練習。</p>



<h3 class="wp-block-heading">數字怎麼看，和兩個陷阱</h3>


<ul class="wp-block-list">
<li><strong>好處</strong>：資料一筆都沒丟，少數類別練習機會變多</li>

<li><strong>陷阱 1：容易死背</strong>。同一筆盜刷被看 10 次，模型可能記住「這 100 筆的細節」，而不是盜刷的共同特徵，也就是<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">第 7 篇的過度擬合</a></li>

<li><strong>陷阱 2：先複製再切，就洩漏了</strong>。如果先把資料複製 10 份，再切訓練集、測試集，同一筆盜刷的分身會同時出現在兩邊，測試分數會假性變好。<strong>正確順序：先切資料，再只對訓練集過取樣</strong>（<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">第 8 篇</a>講過的「考卷混進練習題」）</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">解法 2：欠取樣＋加權（Downsampling ＋ Upweighting）</h2>



<p class="wp-block-paragraph">這是 <a href="https://developers.google.com/machine-learning/crash-course/overfitting/imbalanced-datasets">Google 速成課程</a>推薦的做法，分兩步。速成課程還特別先打預防針：很多學生第一次看到會覺得「這不可能是對的」，因為它有點反直覺。</p>



<h3 class="wp-block-heading">白話是什麼</h3>


<ul class="wp-block-list">
<li><strong>欠取樣</strong>（Downsampling）：訓練時<strong>只用一部分的多數類別</strong>，把多數類別變少</li>

<li><strong>加權</strong>（Upweighting）：被丟掉的那一類，<strong>每一筆的錯誤算重一點</strong>，把丟掉的份量補回來</li>
</ul>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>做民調</strong>。台北人太多，你只抽十分之一來訪問，省時間；但統計時，每個台北人的回答要<strong>乘以 10</strong>，結果才會代表真正的全台灣。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">為什麼要拆成兩步？速成課程的解釋是：模型要學會兩件事，</p>


<ol class="wp-block-list">
<li><strong>每一類長什麼樣子</strong>（哪些特徵對應盜刷）</li>

<li><strong>每一類有多常見</strong>（盜刷其實只佔 1%）</li>
</ol>



<p class="wp-block-paragraph">一般的訓練把這兩件事混在一起。欠取樣讓模型看清楚第 1 件事；加權把第 2 件事補回來。</p>



<h3 class="wp-block-heading">算一次給你看：只做第一步會怎樣</h3>



<p class="wp-block-paragraph"><strong>第一步：欠取樣</strong>，正常交易只留 <strong>十分之一</strong>：</p>



<pre class="wp-block-code"><code>正常交易 = 9,900 ÷ 10 = 990 筆
盜刷     = 100 筆（全部保留）
盜刷比例 = 100 ÷ (100 + 990) = 100 ÷ 1,090 ≈ 9.2%</code></pre>



<p class="wp-block-paragraph">問題來了：模型練習時看到的世界，<strong>每 11 筆就有 1 筆是盜刷</strong>，但真實世界是每 100 筆才 1 筆。它學到的「盜刷有多常見」<strong>高估了大約 9 倍</strong>。上線後，它給每筆交易的盜刷機率都會偏高。這種「模型平均預測值和真實比例對不上」的現象，叫<strong>預測偏差</strong>（Prediction Bias）。</p>



<p class="wp-block-paragraph"><strong>第二步：加權</strong>，正常交易丟掉了九成，所以<strong>每一筆正常交易的錯誤算 10 倍</strong>：</p>



<pre class="wp-block-code"><code>加權後的正常交易份量 = 990 × 10 = 9,900
加權後的盜刷比例 = 100 ÷ (100 + 9,900) = 100 ÷ 10,000 = 1%</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-02-downsample-upweight.png" alt="欠取樣加權怎麼算：正常交易只留 990 筆，盜刷比例變 9.2%；每筆正常交易權重乘 10，份量回到 9,900，比例回到真實的 1%" class="wp-image-12778" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-02-downsample-upweight.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-02-downsample-upweight-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-02-downsample-upweight-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-02-downsample-upweight-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">數字怎麼看</h3>


<ul class="wp-block-list">
<li><strong>只欠取樣</strong>：盜刷看起來佔 9.2%，模型會<strong>高估風險</strong></li>

<li><strong>欠取樣＋加權</strong>：練習時盜刷夠多（學得到樣子），算分數時比例又回到 1%（知道它很少見）</li>

<li><strong>欠取樣幾倍、加權幾倍，要一樣</strong>：丟掉九成就乘 10，丟掉一半就乘 2</li>

<li><strong>幾倍最好？</strong> 速成課程建議把它當成<strong>超參數</strong>，多試幾種比例；重點是每一批裡要有足夠的少數類別</li>
</ul>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">速成課程列出的好處：<strong>模型更好</strong>（同時知道盜刷的樣子和真實比例）、<strong>訓練更快收斂</strong>（每批都看得到盜刷），而且資料變少，也<strong>省硬碟空間和訓練時間</strong>。資料量很大時，這招特別划算。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">解法 3：類別權重（Class Weights），直接把少數類別的錯算重一點</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>類別權重</strong>：資料不動，但告訴模型：<strong>漏掉一筆盜刷，要扣的分是錯判一筆正常交易的好幾倍</strong>。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像考試的<strong>配分</strong>。選擇題一題 1 分、申論題一題 20 分。題目數量沒變，但學生自然會花更多力氣在申論題上。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">這跟解法 2 的「加權」是同一個工具，只是方向不同：</p>


<ul class="wp-block-list">
<li>解法 2：先丟掉多數類別，再把<strong>多數類別</strong>加權補回來</li>

<li>解法 3：資料不丟，直接把<strong>少數類別</strong>加權</li>
</ul>



<p class="wp-block-paragraph">Google 速成課程的摘要提到：<strong>直接加權少數類別比較簡單，但跟「欠取樣＋加權多數類別」比起來，可能會增加預測偏差</strong>。</p>



<h3 class="wp-block-heading">算一次給你看：BigQuery ML 的自動權重</h3>



<p class="wp-block-paragraph">BigQuery ML 有一個選項 <code>AUTO_CLASS_WEIGHTS</code>，依照<a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-create-glm">官方文件</a>，它用這條公式自動算每一類的權重：</p>



<pre class="wp-block-code"><code>某一類的權重 = 總筆數 ÷ (這一類的筆數 × 類別數)</code></pre>



<p class="wp-block-paragraph">套進我們的數字（2 類）：</p>



<pre class="wp-block-code"><code>盜刷的權重 = 10,000 ÷ (100 × 2)   = 10,000 ÷ 200    = 50
正常的權重 = 10,000 ÷ (9,900 × 2) = 10,000 ÷ 19,800 ≈ 0.505

兩類的總份量：
盜刷 = 100 × 50      = 5,000
正常 = 9,900 × 0.505 ≈ 5,000</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-03-class-weights.png" alt="類別權重怎麼算：盜刷權重 10,000 ÷ 200 = 50，正常權重約 0.505，兩類總份量都是 5,000，漏掉 1 筆盜刷等於錯判約 99 筆正常交易" class="wp-image-12779" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-03-class-weights.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-03-class-weights-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-03-class-weights-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-03-class-weights-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">數字怎麼看</h3>


<ul class="wp-block-list">
<li>加權之後，兩類的總份量都是 <strong>5,000</strong>，模型會把兩類看得一樣重</li>

<li>漏掉 1 筆盜刷的代價（50），等於錯判 <strong>約 99 筆</strong>正常交易（50 ÷ 0.505 ≈ 99）</li>

<li><strong>代價</strong>：模型會變得比較敢說「盜刷」，召回率上升、精確率下降，就是第 6 篇講的取捨</li>

<li>權重不一定要用自動公式，也可以自己設，例如只想讓盜刷重 10 倍</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">解法 4：調門檻，不用重新訓練</h2>



<p class="wp-block-paragraph"><a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">第 6 篇〈ROC 曲線和 AUC 怎麼看？〉</a>講過，模型會先算出一個機率，再跟<strong>門檻</strong>比。預設門檻 0.5 對盜刷來說通常太高，因為盜刷的機率本來就很少超過一半。</p>



<p class="wp-block-paragraph"><strong>把門檻調低</strong>（例如 0.2），模型就比較敢說「這筆是盜刷」，召回率上升。這招不用動資料、不用重新訓練，常常是最快的第一步。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">4 招一張表比完</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>過取樣</th><th>欠取樣＋加權</th><th>類別權重</th><th>調門檻</th></tr></thead><tbody><tr><td>白話</td><td>少的複製多一點</td><td>多的丟一些，再把份量補回來</td><td>少的錯算重一點</td><td>降低判斷「是」的標準</td></tr><tr><td>比喻</td><td>錯題多抄幾份練</td><td>民調抽樣再乘回去</td><td>申論題配分高</td><td>及格線調低</td></tr><tr><td>資料量</td><td>變多</td><td>變少</td><td>不變</td><td>不變</td></tr><tr><td>訓練速度</td><td>變慢</td><td><strong>變快</strong></td><td>不變</td><td>不用重訓</td></tr><tr><td>主要風險</td><td>死背重複的資料</td><td>丟掉一些資訊；忘了加權會高估</td><td>精確率下降、預測偏差</td><td>精確率下降</td></tr><tr><td>適合</td><td>資料量不大</td><td><strong>資料量很大</strong></td><td>想快速試、不想動資料</td><td>模型已經訓練好</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>實務順序建議</strong>：先換評估指標 → 試調門檻 → 試類別權重 → 資料量大就欠取樣＋加權、資料量小就過取樣。不管用哪一招，<strong>都只動訓練集</strong>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">在 GCP 上怎麼做</h2>



<p class="wp-block-paragraph"><strong>GCP（Google Cloud Platform）</strong> 是 Google 的雲端服務，白話說就是<strong>租用 Google 機房裡的電腦和工具</strong>。</p>



<h3 class="wp-block-heading">1. BigQuery ML：一行開啟類別權重</h3>


<ul class="wp-block-list">
<li><strong>BigQuery</strong>：Google 的大型資料倉庫，專門存放和分析超大量的表格資料</li>

<li><strong>BigQuery ML</strong>：讓你<a href="https://docs.cloud.google.com/bigquery/docs/bqml-introduction">用 SQL（跟資料庫說話的語言）直接在 BigQuery 裡訓練模型</a></li>
</ul>



<p class="wp-block-paragraph"><strong>自動權重</strong>（教學用的範例，<code>label</code> 欄位裡是 <code>fraud</code> 或 <code>normal</code>）：</p>



<pre class="wp-block-code"><code>CREATE MODEL `bank.fraud_model`
OPTIONS(model_type='LOGISTIC_REG',
        input_label_cols=['label'],
        auto_class_weights=TRUE) AS
SELECT amount, merchant_type, hour_of_day, label
FROM `bank.transactions_train`;</code></pre>



<p class="wp-block-paragraph"><strong>欠取樣＋自己設權重</strong>：正常交易只留十分之一，再用 <code>CLASS_WEIGHTS</code> 把正常交易的權重設成 10：</p>



<pre class="wp-block-code"><code>CREATE MODEL `bank.fraud_model_ds`
OPTIONS(model_type='LOGISTIC_REG',
        input_label_cols=['label'],
        class_weights=[STRUCT('normal', 10.0), STRUCT('fraud', 1.0)]) AS
SELECT amount, merchant_type, hour_of_day, label
FROM `bank.transactions_train`
WHERE label = 'fraud'
   OR MOD(ABS(FARM_FINGERPRINT(transaction_id)), 10) = 0;</code></pre>



<p class="wp-block-paragraph">最後一行的意思是：盜刷全部留下，正常交易用交易編號算一個固定的號碼，<strong>只留號碼尾數是 0 的那十分之一</strong>。用 <code>FARM_FINGERPRINT</code> 而不是隨機抽，好處是每次跑都抽到同一批，結果可以重現。</p>



<p class="wp-block-paragraph">依照官方文件，幾個要注意的地方：</p>


<ul class="wp-block-list">
<li><code>AUTO_CLASS_WEIGHTS</code> <strong>預設是 FALSE</strong>，也就是預設不處理不平衡</li>

<li>在線性模型的文件裡，它<strong>只能用在邏輯迴歸</strong>；深度神經網路等分類模型也有同樣的選項</li>

<li><code>AUTO_CLASS_WEIGHTS</code> 和 <code>CLASS_WEIGHTS</code> <strong>不能同時設</strong></li>

<li><code>CLASS_WEIGHTS</code> 要<strong>每一個類別都給權重</strong>，權重加起來不用等於 1</li>

<li>評估時用 <code>ML.EVALUATE</code> 看 <code>precision</code>、<code>recall</code>、<code>f1_score</code>，用 <code>ML.ROC_CURVE</code> 找適合的門檻（第 6 篇）</li>
</ul>



<h3 class="wp-block-heading">2. AutoML on Agent Platform：選對最佳化目標</h3>



<p class="wp-block-paragraph"><strong>AutoML</strong>：只要把資料丟進去，Google 自動幫你挑模型、調超參數的服務，不用寫程式。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>舊題庫可能還會看到 Vertex AI AutoML 或 AutoML Tables，現在叫 AutoML on Gemini Enterprise Agent Platform。</strong><br>Google Cloud 在 2026 年 4 月 22 日把 Vertex AI 改名為 Gemini Enterprise Agent Platform（簡稱 Agent Platform），底下功能跟著改名（<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/vertex-ai-name-changes">官方對照表</a>）。功能本身是延續的。</p>
</blockquote>



<p class="wp-block-paragraph">表格資料的分類模型，<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">第 6 篇</a>介紹過可以選最佳化目標。少數類別才是重點時，選 <strong>AUC PR（<code>maximize-au-prc</code>）</strong>，<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/tabular-data/classification-regression/train-model">官方文件</a>的說明是「為比較少見的那一類最佳化」。</p>



<p class="wp-block-paragraph">另外<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">第 4 篇</a>提過：AutoML <strong>不會幫你做分層抽樣</strong>，少數類別很少時，要自己用手動切分確保驗證集、測試集裡都有盜刷。</p>



<h3 class="wp-block-heading">3. Agent Platform 自訂訓練（原 Vertex AI Training）</h3>



<p class="wp-block-paragraph">自己寫程式訓練時，以 Keras 為例，類別權重一行就能加：</p>



<pre class="wp-block-code"><code>model.fit(x_train, y_train,
          validation_data=(x_val, y_val),
          class_weight={0: 0.505, 1: 50.0})   # 0 是正常、1 是盜刷</code></pre>



<p class="wp-block-paragraph">數字就是上面 <code>AUTO_CLASS_WEIGHTS</code> 公式算出來的權重。寫好的程式可以放到 Gemini Enterprise Agent Platform Managed Training（原 Vertex AI Training）上跑。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">考試會怎麼考</h2>



<p class="wp-block-paragraph">Google Cloud <strong>Professional Machine Learning Engineer（PMLE，專業機器學習工程師）</strong> 證照，2026 年 6 月 1 日起的<a href="https://services.google.com/fh/files/misc/professional_machine_learning_engineer_exam_guide_english_new.pdf">官方考試指南</a>裡，這篇的內容對應到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考試區塊</th><th>跟這篇有關的項目</th></tr></thead><tbody><tr><td>第 1 區：用低程式碼方式打造 AI 方案（約 13%）</td><td>用 BigQuery ML、Agent Platform AutoML 建分類模型</td></tr><tr><td>第 2 區：跨團隊管理資料與模型（約 16%）</td><td>探索與前處理資料、評估模型</td></tr><tr><td>第 3 區：把原型擴展成正式模型（約 21%）</td><td>排除模型訓練的問題</td></tr></tbody></table></figure>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-04-exam-keywords.png" alt="PMLE 考試關鍵字：少數類別只佔 1% 別看準確率，資料量大用欠取樣加權，BigQuery ML 用 AUTO_CLASS_WEIGHTS，AutoML 選 AUC PR，過取樣要先切再複製" class="wp-image-12780" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-04-exam-keywords.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-04-exam-keywords-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-04-exam-keywords-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml09-04-exam-keywords-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目出現的關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「詐騙只佔 0.1%」「罕見」「極度不平衡」</td><td><strong>類別不平衡</strong>，先換評估指標</td></tr><tr><td>「準確率很高，但抓不到少數類別」</td><td>不看準確率，改看<strong>召回率、F1、AUC-PR</strong></td></tr><tr><td>「資料量很大，訓練太慢，又不平衡」</td><td><strong>欠取樣＋加權</strong>（Downsampling ＋ Upweighting）</td></tr><tr><td>「欠取樣後，模型預測的機率普遍偏高」</td><td>忘了<strong>加權</strong>（Upweighting）</td></tr><tr><td>「BigQuery ML 邏輯迴歸，類別不平衡」</td><td><code>AUTO_CLASS_WEIGHTS=TRUE</code></td></tr><tr><td>「AutoML 表格分類，在意少數類別」</td><td>最佳化目標選 <strong>AUC PR</strong></td></tr><tr><td>「少數類別樣本太少」</td><td><strong>過取樣</strong>（記得先切資料）</td></tr><tr><td>「不想重新訓練，想多抓一些」</td><td><strong>調低門檻</strong></td></tr></tbody></table></figure>



<h3 class="wp-block-heading">三個常見陷阱</h3>


<ol class="wp-block-list">
<li><strong>測試集也做了平衡</strong>：測試集要反映真實比例，才能知道上線後的表現；過取樣、欠取樣只動訓練集</li>

<li><strong>先過取樣再切資料</strong>：同一筆的分身跨到測試集，分數假性變好，這是資料洩漏</li>

<li><strong>欠取樣後沒加權</strong>：模型以為少數類別很常見，上線後一直誤報</li>
</ol>



<h3 class="wp-block-heading">練習情境（自己出的練習，不是真實考題）</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">一家電商有 5 億筆點擊紀錄，要預測「會不會下單」，下單只佔 0.2%。用全部資料訓練一次要 3 天，團隊希望縮短訓練時間，同時不要讓模型高估下單機率。最適合的做法是什麼？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「只佔 0.2%」→ <strong>類別不平衡</strong></li>

<li>「資料量很大、訓練要 3 天」→ 適合<strong>欠取樣</strong>，把「沒下單」的資料大量丟掉，訓練變快</li>

<li>「不要高估下單機率」→ 欠取樣之後一定要<strong>加權</strong>，丟掉幾倍就乘回幾倍</li>

<li>評估時用<strong>真實比例</strong>的測試集，看召回率、精確率或 AUC-PR，不看準確率</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">類別不平衡是什麼？</h3>



<p class="wp-block-paragraph">類別不平衡是分類資料中，某一類的數量遠少於另一類，例如 10,000 筆交易只有 100 筆盜刷。數量多的叫多數類別，少的叫少數類別。真實世界的資料大多是不平衡的，而且少數類別通常就是最想抓的那一類。</p>



<h3 class="wp-block-heading">類別不平衡為什麼不能看準確率？</h3>



<p class="wp-block-paragraph">因為模型只要全部猜多數類別，準確率就很高。例如盜刷佔 1%，全部猜正常的準確率是 99%，但召回率是 0，一筆盜刷都沒抓到。不平衡時要改看召回率、精確率、F1 或 AUC-PR。</p>



<h3 class="wp-block-heading">過取樣和欠取樣差在哪？</h3>



<p class="wp-block-paragraph">過取樣是把少數類別重複使用好幾次，讓它變多，資料量變大；欠取樣是只用一部分的多數類別，讓它變少，資料量變小、訓練變快。過取樣容易讓模型死背重複的資料，欠取樣會丟掉一些資訊，而且要記得加權。</p>



<h3 class="wp-block-heading">欠取樣之後為什麼要加權（Upweighting）？</h3>



<p class="wp-block-paragraph">因為欠取樣讓模型看到一個比真實世界更平衡的假世界，它會高估少數類別有多常見。例如正常交易只留十分之一，盜刷看起來從 1% 變成 9.2%。把每筆正常交易的權重乘 10，份量回到 9,900 筆，比例就回到真實的 1%。</p>



<h3 class="wp-block-heading">類別權重怎麼算？</h3>



<p class="wp-block-paragraph">BigQuery ML 的 AUTO_CLASS_WEIGHTS 用「總筆數 ÷（這一類的筆數 × 類別數）」計算。10,000 筆交易裡有 100 筆盜刷時，盜刷的權重是 50、正常交易約 0.505，兩類加權後的總份量都是 5,000，模型會把兩類看得一樣重。</p>



<h3 class="wp-block-heading">過取樣要在切資料之前還是之後？</h3>



<p class="wp-block-paragraph">一定要在切資料之後，而且只對訓練集做。如果先複製再切，同一筆資料的分身會同時出現在訓練集和測試集，測試分數會假性變好，這是資料洩漏。驗證集和測試集要保持真實的比例。</p>



<h3 class="wp-block-heading">SMOTE 是什麼？</h3>



<p class="wp-block-paragraph">SMOTE 是合成少數類別過取樣（Synthetic Minority Over-sampling Technique），它不是直接複製少數類別的資料，而是用相似樣本之間「內插」出新的資料點，讓少數類別變多，比單純複製比較不容易死背。</p>



<h3 class="wp-block-heading">BigQuery ML 怎麼處理類別不平衡？</h3>



<p class="wp-block-paragraph">可以設 AUTO_CLASS_WEIGHTS=TRUE 讓它依各類比例自動算權重（預設是 FALSE），或用 CLASS_WEIGHTS 自己指定每一類的權重，兩者不能同時用。欠取樣可以在 SQL 裡用 FARM_FINGERPRINT 固定抽出一部分多數類別，評估時再用 ML.ROC_CURVE 找適合的門檻。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>類別不平衡</strong>：少數類別太少，模型會一直猜多數類別；全部猜正常也有 99% 準確率，所以<strong>先換評估指標</strong></li>

<li><strong>過取樣</strong>：少數類別複製多一點；小心死背，而且<strong>先切資料再複製</strong></li>

<li><strong>欠取樣＋加權</strong>：多數類別丟掉一部分讓訓練變快，再<strong>乘回同樣倍數</strong>，比例才會回到真實；Google 速成課程推薦這招</li>

<li><strong>類別權重</strong>：資料不動，少數類別的錯算重一點；BigQuery ML 用 <code>AUTO_CLASS_WEIGHTS</code>（預設關閉）或 <code>CLASS_WEIGHTS</code></li>

<li><strong>調門檻</strong>最快、不用重訓；AutoML 在意少數類別就選 <strong>AUC PR</strong>；不管哪一招，<strong>驗證集、測試集都要保持真實比例</strong></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/20/types-of-machine-learning-supervised-unsupervised-reinforcement/">機器學習有哪幾種？監督式、非監督式、強化學習一次看懂</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/10/20/classification-vs-regression-mae-rmse/">分類和迴歸差在哪？一個例子搞懂，附 MAE、RMSE 計算</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">特徵、標籤、超參數是什麼？機器學習 5 個必懂名詞</a></li>

<li>第 4 篇：<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">訓練集、驗證集、測試集怎麼切？時間序列為什麼不能亂切</a></li>

<li>第 5 篇：<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">混淆矩陣是什麼？用快篩搞懂準確率、精確率、召回率、F1</a></li>

<li>第 6 篇：<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">ROC 曲線和 AUC 怎麼看？門檻怎麼調、AUC-PR 差在哪</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">過度擬合是什麼？正則化、Dropout、提前停止 3 招解決</a></li>

<li>上一篇：第 8 篇：<a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">資料洩漏是什麼？模型考試作弊的 3 種常見情況</a></li>

<li>下一篇：第 10 篇：<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">資料前處理怎麼做？標準化、遺失值、高基數類別</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/07/04/is-bigquery-a-database-what-is-the-usage/">BigQuery 不就是查詢嗎？跟資料庫差在哪裡？能做什麼分析？</a></li>

<li><a href="https://dongdonggcp.com/2026/03/27/bigquery-billing-guide/">BigQuery 計費方式完整介紹：費用結構、自動擴充與省錢技巧全攻略</a></li>

<li><a href="https://dongdonggcp.com/2025/09/10/ipas-ai-planner-exam-ai-introduction/">iPAS AI 應用規劃師初級認證考試 人工智慧概論 重點整理＆簡報下載</a></li>

<li><a href="https://dongdonggcp.com/2025/04/27/gcp-learning-roadmap/">GCP 學習路徑 Learning Roadmap 和八大關卡</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">類別不平衡的關鍵，是讓模型「看得到」少數類別，又「不誤會」它有多常見。下一篇要講資料前處理：數字怎麼縮放、缺的資料怎麼補、類別太多怎麼辦。如果你想有系統地從雲端基礎一路學到在 GCP 上動手做機器學習，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "類別不平衡是什麼？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "類別不平衡是分類資料中，某一類的數量遠少於另一類，例如 10,000 筆交易只有 100 筆盜刷。數量多的叫多數類別，少的叫少數類別。真實世界的資料大多是不平衡的，而且少數類別通常就是最想抓的那一類。"
      }
    },
    {
      "@type": "Question",
      "name": "類別不平衡為什麼不能看準確率？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "因為模型只要全部猜多數類別，準確率就很高。例如盜刷佔 1%，全部猜正常的準確率是 99%，但召回率是 0，一筆盜刷都沒抓到。不平衡時要改看召回率、精確率、F1 或 AUC-PR。"
      }
    },
    {
      "@type": "Question",
      "name": "過取樣和欠取樣差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "過取樣是把少數類別重複使用好幾次，讓它變多，資料量變大；欠取樣是只用一部分的多數類別，讓它變少，資料量變小、訓練變快。過取樣容易讓模型死背重複的資料，欠取樣會丟掉一些資訊，而且要記得加權。"
      }
    },
    {
      "@type": "Question",
      "name": "欠取樣之後為什麼要加權（Upweighting）？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "因為欠取樣讓模型看到一個比真實世界更平衡的假世界，它會高估少數類別有多常見。例如正常交易只留十分之一，盜刷看起來從 1% 變成 9.2%。把每筆正常交易的權重乘 10，份量回到 9,900 筆，比例就回到真實的 1%。"
      }
    },
    {
      "@type": "Question",
      "name": "類別權重怎麼算？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "BigQuery ML 的 AUTO_CLASS_WEIGHTS 用「總筆數 ÷（這一類的筆數 × 類別數）」計算。10,000 筆交易裡有 100 筆盜刷時，盜刷的權重是 50、正常交易約 0.505，兩類加權後的總份量都是 5,000，模型會把兩類看得一樣重。"
      }
    },
    {
      "@type": "Question",
      "name": "過取樣要在切資料之前還是之後？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "一定要在切資料之後，而且只對訓練集做。如果先複製再切，同一筆資料的分身會同時出現在訓練集和測試集，測試分數會假性變好，這是資料洩漏。驗證集和測試集要保持真實的比例。"
      }
    },
    {
      "@type": "Question",
      "name": "SMOTE 是什麼？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "SMOTE 是合成少數類別過取樣（Synthetic Minority Over-sampling Technique），它不是直接複製少數類別的資料，而是用相似樣本之間「內插」出新的資料點，讓少數類別變多，比單純複製比較不容易死背。"
      }
    },
    {
      "@type": "Question",
      "name": "BigQuery ML 怎麼處理類別不平衡？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "可以設 AUTO_CLASS_WEIGHTS=TRUE 讓它依各類比例自動算權重（預設是 FALSE），或用 CLASS_WEIGHTS 自己指定每一類的權重，兩者不能同時用。欠取樣可以在 SQL 裡用 FARM_FINGERPRINT 固定抽出一部分多數類別，評估時再用 ML.ROC_CURVE 找適合的門檻。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/">類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>資料洩漏是什麼？模型考試作弊的 3 種常見情況</title>
		<link>https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=data-leakage-machine-learning</link>
					<comments>https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 22 Oct 2026 04:37:40 +0000</pubDate>
				<category><![CDATA[AI 和機器學習]]></category>
		<category><![CDATA[證照考試]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[BigQuery]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[PMLE]]></category>
		<category><![CDATA[Vertex AI]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[監督式學習]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=12774</guid>

					<description><![CDATA[<p>資料洩漏是什麼？用飲料店例子算給你看偷看未來、答案藏在題目裡、考卷混進練習題 3 種情況，學會用 4 個警訊抓出來，附 BigQuery ML、AutoML 防範做法與 PMLE 考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">資料洩漏是什麼？模型考試作弊的 3 種常見情況</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>資料洩漏是什麼？就是訓練時模型偷看到預測當下拿不到的資訊，測試分數漂亮、上線就翻車，像考試前偷看到答案。</strong></p>



<p class="wp-block-paragraph">這篇繼續用手搖飲料店當例子，把最常見的 3 種「作弊」方式一個一個算給你看：偷看未來、答案藏在題目裡、考卷混進練習題，最後教你怎麼在 GCP 上防範。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-01-three-leaks.png" alt="資料洩漏的 3 種情況：偷看未來、答案藏在題目裡、考卷混進練習題" class="wp-image-12768" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-01-three-leaks.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-01-three-leaks-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-01-three-leaks-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-01-three-leaks-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>它是最會騙人的錯誤</strong>：上一篇講的過度擬合，至少驗證分數會變差，你還看得出來；資料洩漏是<strong>連驗證、測試分數都一起變好</strong>，直到上線才翻車</li>

<li><strong>分數越漂亮，越要懷疑</strong>：準確率 99%、AUC 0.99，很多時候不是模型厲害，是模型作弊</li>

<li><strong>專業團隊也常踩</strong>：洩漏常常藏在一個看起來很合理的欄位、一行前處理程式裡，不是粗心的人才會犯</li>

<li><strong>證照必考</strong>：PMLE 考題很愛描述「測試分數極高，上線後表現很差」，問你原因</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">資料洩漏（Data Leakage）</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>資料洩漏</strong>：訓練模型時，用到了<strong>正式上線預測那一刻拿不到的資訊</strong>。模型靠這些資訊考高分，但上線後這些資訊不存在，表現就崩了。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>考試前偷看到答案</strong>。模擬考考 100 分，大家都以為你很強；正式考試答案沒有外流，你就原形畢露。</p>



<p class="wp-block-paragraph">麻煩的是，作弊的那個人常常<strong>不知道自己在作弊</strong>。資料洩漏通常不是故意的，而是資料整理過程中不小心「漏」進去的。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">Leak 是「漏水」的意思。資料像水一樣，從<strong>不該流過去的地方</strong>（未來、答案、測試集）滲進了訓練過程。</p>



<p class="wp-block-paragraph"><a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">第 4 篇〈訓練集、驗證集、測試集怎麼切？〉</a>講時間序列為什麼不能亂切時，已經碰過一次：隨機切飲料店的 1,000 天資料，測試集裡有 96% 的日子，模型練習時看過它隔壁那天的答案。那就是資料洩漏的一種。</p>



<h3 class="wp-block-heading">為什麼要學</h3>



<p class="wp-block-paragraph">第 7 篇〈過度擬合是什麼？〉講的問題，驗證集抓得到；<strong>資料洩漏，驗證集抓不到</strong>，因為驗證集本身也被污染了。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><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><strong>變差</strong>（看得出來）</td><td><strong>也很好</strong>（看不出來）</td></tr><tr><td>上線後</td><td>差</td><td>差，而且常常差很多</td></tr><tr><td>怎麼發現</td><td>比較訓練和驗證的差距</td><td>分數好到不像真的、檢查每個特徵的來源</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">先看全貌：3 種常見的作弊方式</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>情況</th><th>白話</th><th>考試比喻</th><th>飲料店例子</th></tr></thead><tbody><tr><td><strong>1. 偷看未來</strong></td><td>用到預測時間點<strong>之後</strong>才有的資料</td><td>考前拿到明天的報紙</td><td>用「這週平均銷量」預測週三</td></tr><tr><td><strong>2. 答案藏在題目裡</strong></td><td>某個特徵其實就是答案的分身，或預測時還不存在</td><td>題目裡直接寫了答案</td><td>用「今天開了幾張發票」預測今天賣幾杯</td></tr><tr><td><strong>3. 考卷混進練習題</strong></td><td>測試資料的資訊，在訓練過程被用到</td><td>模擬考題目先拿去練習</td><td>先用全部資料算平均，再切訓練、測試</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">下面一個一個算給你看。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">情況 1：偷看未來（時間洩漏）</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph">模型在預測某個時間點時，用到了<strong>那個時間點之後</strong>才會知道的資料。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">就像<strong>拿明天的報紙預測明天的股價</strong>。當然準，但現實中你不可能有明天的報紙。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">最常見的兩種：</p>


<ol class="wp-block-list">
<li><strong>切資料時亂切</strong>：時間序列隨機洗牌，訓練集裡混進了「未來的日子」（第 4 篇講過）</li>

<li><strong>算特徵時偷用未來</strong>：資料切得很正確，但某個特徵在計算時，用到了未來的數字。這種更難發現</li>
</ol>



<h3 class="wp-block-heading">算一次給你看：「這週平均銷量」的陷阱</h3>



<p class="wp-block-paragraph">店長想預測<strong>週三</strong>賣幾杯，覺得「這週的生意好不好」是個好線索，就加了一個特徵：<strong>本週平均銷量</strong>。</p>



<p class="wp-block-paragraph">假設（教學用的數字）這週的實際銷量是：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>週一</th><th>週二</th><th>週三</th><th>週四</th><th>週五</th><th>週六</th><th>週日</th></tr></thead><tbody><tr><td>100</td><td>110</td><td>130</td><td>150</td><td>160</td><td>200</td><td>190</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>整理歷史資料時，算出來的「本週平均」：</strong></p>



<pre class="wp-block-code"><code>(100 + 110 + 130 + 150 + 160 + 200 + 190) ÷ 7 = 1,040 ÷ 7 ≈ 149 杯</code></pre>



<p class="wp-block-paragraph"><strong>但週三早上真正要預測時，你只知道週一、週二：</strong></p>



<pre class="wp-block-code"><code>(100 + 110) ÷ 2 = 105 杯</code></pre>



<h3 class="wp-block-heading">數字怎麼看</h3>


<ul class="wp-block-list">
<li>訓練時的「本週平均」149 杯，裡面包含了<strong>週三自己的答案</strong>（130），還有<strong>週四到週日的未來</strong></li>

<li>模型學到的是「本週平均 149 時，週三大約賣 130」，等於拿著答案在練習</li>

<li>上線時這個欄位只會是 105 這種數字，模型從沒看過這種情況，預測就亂掉了</li>
</ul>



<p class="wp-block-paragraph"><strong>解法</strong>：每個特徵都要問一句「<strong>在預測的那一刻，這個數字算得出來嗎？</strong>」只能用那一刻<strong>之前</strong>的資料算。這叫做<strong>時間點正確</strong>（Point-in-time Correctness）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">情況 2：答案藏在題目裡（標籤洩漏）</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph"><strong>標籤洩漏</strong>（Label Leakage）：某個特徵其實是<strong>答案的分身</strong>，或是<strong>要等答案出來之後才會有</strong>的資訊。</p>



<p class="wp-block-paragraph">依照 <a href="https://developers.google.com/machine-learning/glossary#label-leakage">Google 機器學習詞彙表</a>，標籤洩漏是一種模型設計上的缺陷：<strong>某個特徵替代了標籤</strong>。（標籤就是要預測的答案，<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">第 3 篇</a>講過。）</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">像<strong>考卷的題目寫著：「請問 2 + 3 等於多少？（提示：答案是 5）」</strong>。學生全部答對，但這張考卷完全測不出實力。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">Google 速成課程舉過兩個例子，很值得記住：</p>


<ul class="wp-block-list">
<li><strong>預測今天的營收，卻用了「今天來店的人數」當特徵</strong>：這個數字非常準，但在一天結束前根本不知道（<a href="https://developers.google.com/machine-learning/crash-course/production-ml-systems/monitoring">速成課程：監控資料管線</a>）</li>

<li><strong>預測病人有沒有癌症，卻用了「醫院名稱」當特徵</strong>：有些醫院專門治療癌症，模型學到「在這間醫院的人大多有癌症」。但模型本來的用途，就是先判斷有沒有癌症，<strong>再決定要送去哪間醫院</strong>，預測時根本還沒有醫院名稱</li>
</ul>



<h3 class="wp-block-heading">算一次給你看：「發票張數」的陷阱</h3>



<p class="wp-block-paragraph">店長想在<strong>每天早上 9 點</strong>預測今天會賣幾杯，好決定要備多少料。資料表裡剛好有一欄「<strong>今天開了幾張發票</strong>」，加進去之後分數超好。</p>



<p class="wp-block-paragraph">假設（教學用的數字）平均每張發票買 1.3 杯，某一天開了 120 張發票、實際賣了 158 杯：</p>



<pre class="wp-block-code"><code>模型預測 = 120 × 1.3 = 156 杯
誤差 = 158 − 156 = 2 杯</code></pre>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>用了哪些特徵</th><th>測試誤差</th><th>早上 9 點上線時</th></tr></thead><tbody><tr><td>氣溫＋假日</td><td>14 杯</td><td>一樣約 14 杯</td></tr><tr><td>氣溫＋假日＋<strong>今天發票張數</strong></td><td><strong>2 杯</strong></td><td>9 點還沒開店，發票是 <strong>0 張</strong></td></tr></tbody></table></figure>



<p class="wp-block-paragraph">上線時：</p>



<pre class="wp-block-code"><code>模型預測 = 0 × 1.3 = 0 杯
誤差 = 158 − 0 = 158 杯</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-02-label-leakage.png" alt="標籤洩漏：用今天的發票張數預測今天賣幾杯，測試誤差只有 2 杯，但早上 9 點發票是 0 張，上線誤差 158 杯" class="wp-image-12769" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-02-label-leakage.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-02-label-leakage-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-02-label-leakage-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-02-label-leakage-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">數字怎麼看</h3>


<ul class="wp-block-list">
<li>測試誤差從 14 杯「進步」到 2 杯，<strong>進步太多本身就是警訊</strong></li>

<li>發票張數和賣出杯數，幾乎是同一件事的兩種記法，它就是答案的分身</li>

<li>Google 速成課程也提醒：<strong>評估分數好得驚人時（例如 AUC 0.99），要回頭找這種會「滲進」標籤的特徵</strong></li>
</ul>



<h3 class="wp-block-heading">其他常見的例子</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><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>「有沒有開某種藥」</td><td>確診後才會開藥</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">情況 3：考卷混進練習題（訓練與測試污染）</h2>



<h3 class="wp-block-heading">白話是什麼</h3>



<p class="wp-block-paragraph">測試集（或驗證集）的資訊，在<strong>訓練過程的某個步驟</strong>被用到了。資料本身切得沒錯，但「整理資料」或「挑模型」的步驟偷看了考卷。</p>



<h3 class="wp-block-heading">比喻</h3>



<p class="wp-block-paragraph">老師出模擬考之前，<strong>先拿模擬考的題目給學生練習</strong>。模擬考成績很高，但那不是實力。</p>



<h3 class="wp-block-heading">來龍去脈</h3>



<p class="wp-block-paragraph">最常見的三種：</p>


<ol class="wp-block-list">
<li><strong>先算統計值，再切資料</strong>（前處理洩漏）</li>

<li><strong>同一筆資料出現在兩份</strong>（重複資料，第 4 篇講過）</li>

<li><strong>用同一份資料挑超參數，又拿來報最終分數</strong>（選模型洩漏）</li>
</ol>



<h3 class="wp-block-heading">算一次給你看 1：先算平均再切，平均值偷看了未來</h3>



<p class="wp-block-paragraph"><strong>標準化</strong>（Standardization）是常見的前處理：把數字換算成「跟平均差了幾個標準差」，讓不同單位的特徵可以放在一起比較（<a href="https://dongdonggcp.com/2026/10/22/data-preprocessing-normalization-missing-values-high-cardinality/">第 10 篇</a>會細講）。它的第一步是<strong>算平均值</strong>。</p>



<p class="wp-block-paragraph">假設（教學用的數字）飲料店 1,000 天裡，前 800 天是訓練集，平均氣溫 22 度；最後 200 天（驗證集＋測試集）剛好是夏天，平均氣溫 30 度。</p>



<p class="wp-block-paragraph"><strong>錯誤做法：先用全部 1,000 天算平均，再切資料</strong></p>



<pre class="wp-block-code"><code>平均氣溫 = (800 × 22 + 200 × 30) ÷ 1,000
         = (17,600 + 6,000) ÷ 1,000
         = 23.6 度</code></pre>



<p class="wp-block-paragraph"><strong>正確做法：先切資料，只用訓練集的 800 天算</strong></p>



<pre class="wp-block-code"><code>平均氣溫 = 22 度</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-03-split-first.png" alt="先切再算：用全部資料算平均氣溫是 23.6 度，偷看了夏天的測試資料；只用訓練集算是 22 度" class="wp-image-12770" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-03-split-first.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-03-split-first-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-03-split-first-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-03-split-first-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">數字怎麼看</h3>


<ul class="wp-block-list">
<li>差的 <strong>1.6 度</strong>，就是「最後 200 天比較熱」這件事，<strong>偷偷流進了訓練過程</strong></li>

<li>這個例子的影響不大，重點是原則：<strong>任何從資料「算出來」的東西（平均、標準差、最大最小值、要保留哪些特徵），都只能用訓練集算</strong>，再拿去套用到驗證集、測試集和上線資料</li>

<li>同樣的錯如果發生在「用全部資料挑出最有用的特徵」，分數會被灌水得非常明顯</li>
</ul>



<h3 class="wp-block-heading">算一次給你看 2：巢狀交叉驗證，挑模型和打分數要分開</h3>



<p class="wp-block-paragraph">先認識<strong>交叉驗證</strong>（Cross-Validation）：資料不多時，把訓練資料分成 5 份，<strong>輪流</strong>拿其中 1 份當驗證、其他 4 份訓練，做 5 次，把 5 次的分數平均。比喻：同一本講義，輪流抽不同的章節來小考，比只考一次公平。</p>



<p class="wp-block-paragraph">問題來了：假設你有 <strong>4 組超參數</strong>要比較，每組都做 5 份交叉驗證，最後<strong>挑分數最高的那組，又直接拿那個分數當「模型實力」報告</strong>。</p>



<p class="wp-block-paragraph">這也是偷看。就像<strong>同一份模擬考考 4 次，挑最高分當實力</strong>，一定會高估。<a href="https://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html">scikit-learn 官方範例</a>的說法是：用沒有巢狀的交叉驗證挑參數，分數會<strong>過度樂觀</strong>。</p>



<p class="wp-block-paragraph"><strong>巢狀交叉驗證</strong>（Nested Cross-Validation）的做法是把兩件事拆開：</p>


<ul class="wp-block-list">
<li><strong>外層</strong>（5 份）：只負責<strong>打分數</strong></li>

<li><strong>內層</strong>（每次外層的 4 份訓練資料裡，再切 3 份）：只負責<strong>挑超參數</strong></li>
</ul>



<p class="wp-block-paragraph">要訓練幾次？</p>



<pre class="wp-block-code"><code>內層挑超參數：外層 5 次 × 內層 3 份 × 4 組超參數 = 60 次
外層用挑出的超參數重新訓練：5 次
總共 = 60 + 5 = 65 次

一般交叉驗證：5 份 × 4 組 = 20 次</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-04-nested-cv.png" alt="巢狀交叉驗證：外層 5 份負責打分數，內層 3 份負責挑超參數，4 組超參數共訓練 65 次，一般交叉驗證 20 次" class="wp-image-12771" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-04-nested-cv.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-04-nested-cv-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-04-nested-cv-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-04-nested-cv-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">數字怎麼看</h3>


<ul class="wp-block-list">
<li>巢狀交叉驗證要訓練 <strong>65 次</strong>，大約是一般做法的 <strong>3 倍</strong>，換來一個<strong>不灌水</strong>的分數</li>

<li>資料夠多時，不一定要這麼麻煩：直接照第 4 篇的做法，切出一份<strong>完全不碰的測試集</strong>，最後只用一次，效果一樣</li>

<li>資料很少、切不出獨立測試集時，巢狀交叉驗證就很有用</li>
</ul>



<h3 class="wp-block-heading">另外兩個常見的污染</h3>


<ul class="wp-block-list">
<li><strong>重複資料</strong>：同一筆資料出現在訓練集和測試集，模型考到練習過的原題（第 4 篇陷阱 1）</li>

<li><strong>先複製再切</strong>：處理類別不平衡時，常會把少數類別的資料複製好幾份（過取樣）。如果<strong>先複製、再切資料</strong>，同一筆的分身就會跨到兩份裡。正確順序是<strong>先切，再只對訓練集複製</strong>（第 9 篇會講）</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">怎麼發現資料洩漏：4 個警訊</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>警訊</th><th>白話</th><th>怎麼查</th></tr></thead><tbody><tr><td><strong>分數好到不像真的</strong></td><td>準確率 99%、AUC 0.99、誤差幾乎是 0</td><td>回頭檢查每個特徵</td></tr><tr><td><strong>某一個特徵特別重要</strong></td><td>模型幾乎只靠一個欄位做判斷</td><td>看特徵重要度（<a href="https://dongdonggcp.com/2026/10/25/explainable-ai-shapley-integrated-gradients-xrai/">第 21 篇</a>的可解釋 AI 會講）</td></tr><tr><td><strong>上線後表現暴跌</strong></td><td>測試很好，上線很差</td><td>比對訓練資料和上線資料（<a href="https://dongdonggcp.com/2026/10/25/model-monitoring-drift-training-serving-skew/">第 20 篇</a>的模型監控會講）</td></tr><tr><td><strong>預測當下拿不到</strong></td><td>這個欄位要等事情發生後才有</td><td>每個特徵都問：「預測那一刻，拿得到嗎？」</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">最後一個是最有用的習慣：<strong>把每個特徵列出來，旁邊寫上「它在什麼時間點、由誰產生」</strong>。比預測時間點晚的，全部拿掉。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">在 GCP 上怎麼做</h2>



<p class="wp-block-paragraph"><strong>GCP（Google Cloud Platform）</strong> 是 Google 的雲端服務，白話說就是<strong>租用 Google 機房裡的電腦和工具</strong>。</p>



<h3 class="wp-block-heading">1. BigQuery ML：照時間切，前處理寫在 TRANSFORM 裡</h3>


<ul class="wp-block-list">
<li><strong>BigQuery</strong>：Google 的大型資料倉庫，專門存放和分析超大量的表格資料</li>

<li><strong>BigQuery ML</strong>：讓你<a href="https://docs.cloud.google.com/bigquery/docs/bqml-introduction">用 SQL（跟資料庫說話的語言）直接在 BigQuery 裡訓練模型</a></li>
</ul>



<p class="wp-block-paragraph"><strong>防情況 1（偷看未來）</strong>：有時間順序的資料，用 <code>DATA_SPLIT_METHOD='SEQ'</code> 照時間切，舊的訓練、新的評估。<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">第 4 篇</a>有完整範例。依照<a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-create-glm">官方文件</a>，拿來排序的那一欄（<code>DATA_SPLIT_COL</code>）<strong>會自動被排除，不會被當成特徵</strong>。</p>



<p class="wp-block-paragraph"><strong>防情況 3（前處理洩漏）</strong>：把前處理寫在 <code>TRANSFORM</code> 裡，而且只拿訓練期間的資料來建模型（教學用的範例）：</p>



<pre class="wp-block-code"><code>CREATE MODEL `shop.daily_cups_tf`
TRANSFORM(
  ML.STANDARD_SCALER(temperature) OVER() AS temperature_scaled,
  is_holiday,
  cups_sold)
OPTIONS(model_type='LINEAR_REG',
        input_label_cols=['cups_sold']) AS
SELECT temperature, is_holiday, cups_sold
FROM `shop.daily_sales_train`;   -- 只放訓練期間的資料</code></pre>



<p class="wp-block-paragraph">依照 <a href="https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-standard-scaler"><code>ML.STANDARD_SCALER</code> 官方文件</a>，寫在 <code>TRANSFORM</code> 裡時，<strong>訓練時算出來的平均和標準差，預測時會自動沿用</strong>。所以之後用 <code>ML.PREDICT</code> 預測新的一天，它會拿訓練期間的 22 度當平均，不會偷看任何新資料，也不用你自己再算一次。</p>



<p class="wp-block-paragraph">這也解決了另一個相關的問題：<strong>訓練和上線時前處理不一致</strong>（Training-Serving Skew），第 20 篇會細講。</p>



<h3 class="wp-block-heading">2. AutoML on Agent Platform：用時間欄位切</h3>



<p class="wp-block-paragraph"><strong>AutoML</strong>：只要把資料丟進去，Google 自動幫你挑模型、調超參數的服務，不用寫程式。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>舊題庫可能還會看到 Vertex AI AutoML，現在叫 AutoML on Gemini Enterprise Agent Platform。</strong><br>Google Cloud 在 2026 年 4 月 22 日把 Vertex AI 改名為 Gemini Enterprise Agent Platform（簡稱 Agent Platform），底下功能跟著改名（<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/vertex-ai-name-changes">官方對照表</a>）。功能本身是延續的。</p>
</blockquote>



<p class="wp-block-paragraph">依照<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/tabular-data/data-splits">官方文件</a>：</p>


<ul class="wp-block-list">
<li>資料跟時間有關時，<strong>預設的隨機切法不是最好的選擇</strong>，要改用<strong>時間切分</strong>（Chronological split）：指定一欄當 Time column，最早的當訓練、接著當驗證、最新的當測試</li>

<li>時間欄位最好有<strong>至少 20 個不同的值</strong>，驗證集和測試集才不會是空的</li>

<li>也可以自己加一欄，填 <code>TRAIN</code>、<code>VALIDATE</code>、<code>TEST</code> 來<strong>手動切</strong>，例如照分店切，避免同一間店跨兩份</li>

<li>預測型（forecasting）模型預設就照時間切，而且會<strong>丟掉預測範圍橫跨兩份資料的那些列，避免資料洩漏</strong></li>
</ul>



<h3 class="wp-block-heading">3. Feature Store on Agent Platform：取回「當時」的特徵值</h3>



<p class="wp-block-paragraph"><strong>Feature Store</strong>：把整理好的特徵集中存放、讓不同模型共用的服務，第 3 篇比喻成「全公司共用的線索倉庫」（舊名 Vertex AI Feature Store）。</p>



<p class="wp-block-paragraph">防範情況 1 最有用的功能是<strong>離線取用歷史特徵</strong>：依照<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/featurestore/latest/serve-historical-features">官方文件</a>，你可以<strong>指定時間點</strong>，取回「那個時間點當下」的特徵值來組訓練資料。等於自動幫你做到「週三早上只拿得到週一、週二的資料」。這個功能目前是<strong>預先發布</strong>（Preview）階段。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>舊名稱</th><th>現在的名稱</th></tr></thead><tbody><tr><td>Vertex AI</td><td>Gemini Enterprise Agent Platform（Agent Platform）</td></tr><tr><td>Vertex AI AutoML</td><td>AutoML on Gemini Enterprise Agent Platform</td></tr><tr><td>Vertex AI Feature Store</td><td>Feature Store on Gemini Enterprise Agent Platform</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">考試會怎麼考</h2>



<p class="wp-block-paragraph">Google Cloud <strong>Professional Machine Learning Engineer（PMLE，專業機器學習工程師）</strong> 證照，2026 年 6 月 1 日起的<a href="https://services.google.com/fh/files/misc/professional_machine_learning_engineer_exam_guide_english_new.pdf">官方考試指南</a>裡，這篇的內容對應到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考試區塊</th><th>跟這篇有關的項目</th></tr></thead><tbody><tr><td>第 2 區：跨團隊管理資料與模型（約 16%）</td><td>探索與前處理資料、在 Feature Store 建立特徵</td></tr><tr><td>第 3 區：把原型擴展成正式模型（約 21%）</td><td>排除模型訓練的問題</td></tr><tr><td>第 5 區：自動化與協調 ML 管線（約 18%）</td><td><strong>驗證資料與模型</strong>、<strong>確保訓練和上線的前處理一致</strong></td></tr></tbody></table></figure>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-05-exam-keywords.png" alt="PMLE 考試關鍵字：測試很好上線很差想到資料洩漏，時間資料想到照時間切，前處理要先切再算，挑超參數又要打分數想到巢狀交叉驗證" class="wp-image-12772" srcset="https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-05-exam-keywords.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-05-exam-keywords-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-05-exam-keywords-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/10/ml08-05-exam-keywords-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目出現的關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「測試分數極高，上線後很差」</td><td><strong>資料洩漏</strong>（或訓練與上線不一致）</td></tr><tr><td>「AUC 0.99」「準確率接近 100%」</td><td>先懷疑<strong>資料洩漏</strong></td></tr><tr><td>「有時間順序的資料」「預測未來」</td><td><strong>照時間切</strong>，BigQuery ML 用 <code>SEQ</code>、AutoML 用時間欄位</td></tr><tr><td>「某個欄位要等結果出來才有」</td><td><strong>標籤洩漏</strong>，拿掉該特徵</td></tr><tr><td>「標準化、正規化、填補遺失值」</td><td><strong>先切再算</strong>，只用訓練集的統計值</td></tr><tr><td>「確保訓練和預測的前處理一致」</td><td>BigQuery ML 的 <code>TRANSFORM</code></td></tr><tr><td>「同時要調超參數又要估計實力」「資料很少」</td><td><strong>巢狀交叉驗證</strong></td></tr><tr><td>「取回某個時間點當下的特徵值」</td><td>Feature Store 的<strong>歷史特徵（時間點正確）</strong></td></tr></tbody></table></figure>



<h3 class="wp-block-heading">三個常見陷阱</h3>


<ol class="wp-block-list">
<li><strong>以為隨機切最公平</strong>：有時間順序的資料，隨機切就是在偷看未來</li>

<li><strong>把「跟答案超相關」的特徵當寶</strong>：相關到不合理，通常是答案的分身</li>

<li><strong>看到分數低才檢查，分數高就不檢查</strong>：資料洩漏讓分數變高，所以<strong>分數異常好時更要檢查</strong></li>
</ol>



<h3 class="wp-block-heading">練習情境（自己出的練習，不是真實考題）</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">一家電信公司要預測「下個月哪些用戶會解約」。資料科學家用 BigQuery ML 訓練邏輯迴歸，特徵包括月租費、使用年資、近 3 個月客服來電次數，以及「是否已提出攜碼申請」。測試集 AUC 高達 0.99，但上線後幾乎抓不到要解約的人。最可能的原因和修正方式是什麼？</p>
</blockquote>



<p class="wp-block-paragraph"><strong>判斷過程</strong>：</p>


<ul class="wp-block-list">
<li>「AUC 0.99」→ 好到不像真的，先懷疑<strong>資料洩漏</strong></li>

<li>「是否已提出攜碼申請」→ 用戶通常是決定解約之後才會申請攜碼，等於<strong>答案的分身</strong>，而且在「預測下個月」那一刻，大多數人還沒申請</li>

<li>修正：<strong>拿掉這個特徵</strong>，並檢查其他特徵在預測時間點是否拿得到；資料要<strong>照時間切</strong>，用過去的月份訓練、最近的月份測試</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">資料洩漏是什麼？</h3>



<p class="wp-block-paragraph">資料洩漏是訓練模型時，用到了正式上線預測那一刻拿不到的資訊。模型靠這些資訊在驗證和測試時拿到很高的分數，但上線後這些資訊不存在，表現就大幅下降。就像考試前偷看到答案。</p>



<h3 class="wp-block-heading">資料洩漏和過度擬合差在哪？</h3>



<p class="wp-block-paragraph">過度擬合是模型死背，訓練分數好、驗證分數差，比較兩者就看得出來。資料洩漏是模型作弊，連驗證和測試分數都一起變好，要等上線才發現，所以更難察覺。</p>



<h3 class="wp-block-heading">資料洩漏有哪幾種？</h3>



<p class="wp-block-paragraph">常見有三種：偷看未來（用到預測時間點之後的資料，例如時間序列隨機切）、答案藏在題目裡（標籤洩漏，特徵是答案的分身或要等結果出來才有）、考卷混進練習題（測試資料的資訊在前處理、挑模型時被用到）。</p>



<h3 class="wp-block-heading">怎麼知道模型有沒有資料洩漏？</h3>



<p class="wp-block-paragraph">注意四個警訊：分數好到不像真的、模型幾乎只靠一個特徵、測試很好但上線暴跌、某個特徵在預測當下根本拿不到。最實用的方法是把每個特徵列出來，寫上它在什麼時間點產生，比預測時間點晚的都要拿掉。</p>



<h3 class="wp-block-heading">標籤洩漏是什麼？</h3>



<p class="wp-block-paragraph">標籤洩漏是某個特徵其實替代了要預測的答案。Google 速成課程的例子是：用「今天來店的人數」預測今天的營收，這個數字很準，但要等一天結束才知道，預測當下根本拿不到。</p>



<h3 class="wp-block-heading">標準化為什麼要先切資料再算？</h3>



<p class="wp-block-paragraph">因為標準化要用到平均值和標準差，如果用全部資料算，驗證集和測試集的資訊就混進了訓練過程。正確做法是只用訓練集算統計值，再套用到其他資料。BigQuery ML 把前處理寫在 TRANSFORM 裡，訓練時算的統計值預測時會自動沿用。</p>



<h3 class="wp-block-heading">巢狀交叉驗證是什麼？什麼時候要用？</h3>



<p class="wp-block-paragraph">巢狀交叉驗證把「挑超參數」和「打分數」拆成內外兩層：外層負責估計模型實力，內層只負責挑超參數，避免挑最高分又拿它當實力的偷看問題。代價是訓練次數多很多，適合資料少、切不出獨立測試集的時候。</p>



<h3 class="wp-block-heading">時間序列資料要怎麼避免資料洩漏？</h3>



<p class="wp-block-paragraph">照時間切資料，舊的訓練、新的測試，不要隨機洗牌；每個特徵都只能用預測時間點之前的資料計算。BigQuery ML 可以用 DATA_SPLIT_METHOD=&#8217;SEQ&#8217;，AutoML on Agent Platform 可以指定時間欄位做時間切分。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>資料洩漏</strong>＝模型訓練時偷看到上線時拿不到的資訊；它讓驗證、測試分數一起變好，比過度擬合更難發現</li>

<li><strong>偷看未來</strong>：時間資料要照時間切，每個特徵只能用預測時間點之前的資料算</li>

<li><strong>答案藏在題目裡</strong>：問每個特徵「預測那一刻拿得到嗎？」，答案的分身要拿掉</li>

<li><strong>考卷混進練習題</strong>：先切再算統計值、刪掉重複資料、挑超參數和打分數要分開（巢狀交叉驗證）</li>

<li>GCP 上：BigQuery ML 用 <code>SEQ</code> 照時間切、前處理寫進 <code>TRANSFORM</code>；AutoML 用時間欄位切；Feature Store 取回時間點當下的特徵值</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/20/types-of-machine-learning-supervised-unsupervised-reinforcement/">機器學習有哪幾種？監督式、非監督式、強化學習一次看懂</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/10/20/classification-vs-regression-mae-rmse/">分類和迴歸差在哪？一個例子搞懂，附 MAE、RMSE 計算</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/10/20/features-labels-hyperparameters-machine-learning/">特徵、標籤、超參數是什麼？機器學習 5 個必懂名詞</a></li>

<li>第 4 篇：<a href="https://dongdonggcp.com/2026/10/21/train-validation-test-split-time-series/">訓練集、驗證集、測試集怎麼切？時間序列為什麼不能亂切</a></li>

<li>第 5 篇：<a href="https://dongdonggcp.com/2026/10/21/confusion-matrix-accuracy-precision-recall-f1/">混淆矩陣是什麼？用快篩搞懂準確率、精確率、召回率、F1</a></li>

<li>第 6 篇：<a href="https://dongdonggcp.com/2026/10/22/roc-curve-auc-threshold-auc-pr/">ROC 曲線和 AUC 怎麼看？門檻怎麼調、AUC-PR 差在哪</a></li>

<li>上一篇：第 7 篇：<a href="https://dongdonggcp.com/2026/10/22/overfitting-regularization-dropout-early-stopping/">過度擬合是什麼？正則化、Dropout、提前停止 3 招解決</a></li>

<li>下一篇：第 9 篇：<a href="https://dongdonggcp.com/2026/10/22/class-imbalance-oversampling-downsampling-upweighting/">類別不平衡怎麼辦？過取樣、欠取樣與 Upweighting</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/07/04/is-bigquery-a-database-what-is-the-usage/">BigQuery 不就是查詢嗎？跟資料庫差在哪裡？能做什麼分析？</a></li>

<li><a href="https://dongdonggcp.com/2025/04/14/vertex-ai-functions-agent-builder-model-builder-model-garden-introduction/">Vertex AI 核心功能 Agent Builder、Model Builder 和 Model Garden 介紹</a></li>

<li><a href="https://dongdonggcp.com/2025/09/10/ipas-ai-planner-exam-ai-introduction/">iPAS AI 應用規劃師初級認證考試 人工智慧概論 重點整理＆簡報下載</a></li>

<li><a href="https://dongdonggcp.com/2025/04/27/gcp-learning-roadmap/">GCP 學習路徑 Learning Roadmap 和八大關卡</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">資料洩漏最可怕的地方，是它會讓你對一個不能用的模型充滿信心。養成「每個特徵都問一句：預測那一刻拿得到嗎？」的習慣，就能避開大部分的坑。如果你想有系統地從雲端基礎一路學到在 GCP 上動手做機器學習，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "資料洩漏是什麼？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "資料洩漏是訓練模型時，用到了正式上線預測那一刻拿不到的資訊。模型靠這些資訊在驗證和測試時拿到很高的分數，但上線後這些資訊不存在，表現就大幅下降。就像考試前偷看到答案。"
      }
    },
    {
      "@type": "Question",
      "name": "資料洩漏和過度擬合差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "過度擬合是模型死背，訓練分數好、驗證分數差，比較兩者就看得出來。資料洩漏是模型作弊，連驗證和測試分數都一起變好，要等上線才發現，所以更難察覺。"
      }
    },
    {
      "@type": "Question",
      "name": "資料洩漏有哪幾種？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "常見有三種：偷看未來（用到預測時間點之後的資料，例如時間序列隨機切）、答案藏在題目裡（標籤洩漏，特徵是答案的分身或要等結果出來才有）、考卷混進練習題（測試資料的資訊在前處理、挑模型時被用到）。"
      }
    },
    {
      "@type": "Question",
      "name": "怎麼知道模型有沒有資料洩漏？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "注意四個警訊：分數好到不像真的、模型幾乎只靠一個特徵、測試很好但上線暴跌、某個特徵在預測當下根本拿不到。最實用的方法是把每個特徵列出來，寫上它在什麼時間點產生，比預測時間點晚的都要拿掉。"
      }
    },
    {
      "@type": "Question",
      "name": "標籤洩漏是什麼？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "標籤洩漏是某個特徵其實替代了要預測的答案。Google 速成課程的例子是：用「今天來店的人數」預測今天的營收，這個數字很準，但要等一天結束才知道，預測當下根本拿不到。"
      }
    },
    {
      "@type": "Question",
      "name": "標準化為什麼要先切資料再算？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "因為標準化要用到平均值和標準差，如果用全部資料算，驗證集和測試集的資訊就混進了訓練過程。正確做法是只用訓練集算統計值，再套用到其他資料。BigQuery ML 把前處理寫在 TRANSFORM 裡，訓練時算的統計值預測時會自動沿用。"
      }
    },
    {
      "@type": "Question",
      "name": "巢狀交叉驗證是什麼？什麼時候要用？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "巢狀交叉驗證把「挑超參數」和「打分數」拆成內外兩層：外層負責估計模型實力，內層只負責挑超參數，避免挑最高分又拿它當實力的偷看問題。代價是訓練次數多很多，適合資料少、切不出獨立測試集的時候。"
      }
    },
    {
      "@type": "Question",
      "name": "時間序列資料要怎麼避免資料洩漏？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "照時間切資料，舊的訓練、新的測試，不要隨機洗牌；每個特徵都只能用預測時間點之前的資料計算。BigQuery ML 可以用 DATA_SPLIT_METHOD='SEQ'，AutoML on Agent Platform 可以指定時間欄位做時間切分。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/">資料洩漏是什麼？模型考試作弊的 3 種常見情況</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/10/22/data-leakage-machine-learning/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
