聊天視窗

資料科學實務與方法:從理論到應用 - 第 4 章

第 4 章:探索性資料分析與可視化

發布於 2026-03-04 02:45

# 第 4 章:探索性資料分析與可視化 探索性資料分析(Exploratory Data Analysis, EDA)是資料科學流程中最直觀且關鍵的環節。它不僅能讓資料分析師快速掌握資料結構、分布與潛在問題,還能為後續的特徵工程、模型選擇提供決策支持。本章將從統計摘要、分布視覺化、相關性分析三大面向切入,並示範如何運用 Plotly 與 Bokeh 等交互式工具構建動態報告,提升洞察力與溝通效率。 ## 4.1 統計摘要(Descriptive Statistics) | 變數 | 最大值 | 最小值 | 平均值 | 中位數 | 標準差 | 25% 分位 | 75% 分位 | |------|--------|--------|--------|--------|--------|----------|----------| | TotalCharges | 8000 | 0 | 350 | 300 | 800 | 150 | 600 | | MonthlyCharges | 200 | 0 | 75 | 70 | 20 | 55 | 90 | | Tenure | 120 | 1 | 24 | 18 | 10 | 12 | 30 | > **技巧提示**: > - **`pandas.DataFrame.describe()`** 可一次性取得上述統計量,並自動排除非數值欄位。 > - **`pandas.DataFrame.agg(['mean', 'median', 'std'])`** 可針對特定列進行自訂聚合。 > - 在處理 **時間序列資料** 時,考慮使用 `datetime` 型別並透過 `pd.Grouper` 進行日/月聚合。 ### 4.1.1 Python 範例:快速統計摘要 python import pandas as pd # 讀取示例資料 df = pd.read_csv('customer_churn.csv') # 數值型別摘要 summary = df.describe().T print(summary[['min', '25%', '50%', '75%', 'max', 'mean', 'std']]) ## 4.2 分布視覺化(Distribution Visualization) ### 4.2.1 一維分布:直方圖與 KDE | 變數 | 類型 | 建議圖表 | |------|------|----------| | TotalCharges | 繼續 | `hist + KDE` | | Churn | 分類 | `countplot` | python import seaborn as sns import matplotlib.pyplot as plt sns.histplot(df['TotalCharges'], kde=True, bins=50, color='steelblue') plt.title('TotalCharges 分布') plt.xlabel('總費用 ($)') plt.ylabel('頻數') plt.show() ### 4.2.2 二維分布:箱型圖、Violin Plot python sns.boxplot(x='Churn', y='TotalCharges', data=df, palette='Set2') plt.title('按 churn 分類的 TotalCharges 盒鬍圖') plt.show() ### 4.2.3 多變數分布:配對圖(Pairplot) python sns.pairplot(df[['TotalCharges', 'MonthlyCharges', 'Tenure', 'Churn']], hue='Churn') plt.show() > **建議**: > - 當樣本數 **> 10k** 時,使用 **Hexbin** 或 **KDE** 取代直方圖以減少計算負擔。 > - 針對 **類別變數**,**Bar Plot** 或 **Count Plot** 可直接呈現頻率分佈。 ## 4.3 相關性分析(Correlation Analysis) ### 4.3.1 皮爾森相關係數矩陣 python corr = df.corr(method='pearson') plt.figure(figsize=(10,8)) sns.heatmap(corr, annot=True, cmap='coolwarm', fmt='.2f') plt.title('皮爾森相關係數矩陣') plt.show() ### 4.3.2 斯皮爾曼與肯德爾 - **斯皮爾曼**:適用於 **秩序型資料** 或 **非線性關係**。 - **肯德爾**:對 **離群值** 更具魯棒性。 python corr_spearman = df.corr(method='spearman') print(corr_spearman) > **注意**: > - 相關係數只衡量 **線性關係**;對於 **非線性** 或 **多變量** 關係,請配合 **部分相關** 或 **結構方程模型**。 > - 當變數數量眾多時,可使用 **主成分分析 (PCA)** 先降維,再檢視主成分間相關。 ## 4.4 交互式圖表工具 ### 4.4.1 Plotly - 支援 **即時滑動、放大**、**hover tooltip**。 - `plotly.express` 提供簡易語法。 python import plotly.express as px fig = px.scatter(df, x='Tenure', y='MonthlyCharges', color='Churn', hover_data=['TotalCharges']) fig.update_layout(title='Tenure vs MonthlyCharges (Churn 類別)') fig.show() ### 4.4.2 Bokeh - 適合 **大型資料集**,支援 **分頁與流式**。 - `bokeh.plotting.figure` 具備 `output_file` 與 `show` 方法。 python from bokeh.plotting import figure, output_file, show from bokeh.models import HoverTool output_file('bokeh_churn.html') p = figure(title='Churn 數據', x_axis_label='Tenure', y_axis_label='MonthlyCharges', tools='pan,wheel_zoom,box_zoom,reset,hover') p.circle('Tenure', 'MonthlyCharges', source=df, size=7, color='navy', alpha=0.5) hover = p.select_one(HoverTool) hover.tooltips = [ ('Churn', '@Churn'), ('TotalCharges', '@TotalCharges') ] show(p) ## 4.5 報告生成與自動化 - **Jupyter Notebook**:結合 Markdown 與程式碼,適合探索性報告。 - **JupyterLab**:提供多檔案視窗與命令列工具。 - **nbconvert**:可將 Notebook 轉成 HTML、PDF、LaTeX,支援自動化工作流。 bash # 轉成 HTML jupyter nbconvert --to html exploratory_report.ipynb # 轉成 PDF (需要 LaTeX) jupyter nbconvert --to pdf exploratory_report.ipynb > **實務建議**: > - 把 **資料處理**、**EDA**、**特徵工程** 與 **模型建構** 分別拆成多個 Notebook,避免單一檔案過大。 > - 在 CI 環境中使用 **GitHub Actions** 或 **GitLab CI** 觸發 `nbconvert`,確保報告始終為最新。 ## 4.6 案例分析:Netflix 觀眾行為探索 | 步驟 | 目的 | 主要工具 | |------|------|----------| | 1. 讀取 `watch_time.csv` | 取得每日觀看時數 | `pandas.read_csv` | | 2. 計算每日平均觀看時數 | 檢視季節性 | `df.groupby('date')['watch_time'].mean()` | | 3. 繪製時間序列 | 發現節假日影響 | `matplotlib` 或 `plotly` | | 4. 探索性相關 | 觀眾年齡與觀看類型 | `seaborn.heatmap` | | 5. 報告產出 | 向產品團隊說明 | `nbconvert` | > **結論**: > - 觀眾觀看時數在假日週末顯著上升,並且青少年觀眾偏好動作類型。 > - 建議在節假日前夕推播動作電影,以提高點擊率。 ## 4.7 小結 - **探索性資料分析** 是資料科學決策的第一道門檻,透過統計摘要、分布視覺化與相關性分析,可快速洞悉資料特性與潛在問題。 - **交互式圖表**(Plotly、Bokeh)能提升資料呈現的可操作性,適合多方協作與決策。 - **自動化報告**(Jupyter + nbconvert)保障分析結果隨時更新,減少手動錯誤。 - 在實務中,**EDA** 與 **特徵工程** 之間往往互相迴圈;經驗累積後,能更快識別「高資訊價值」的特徵。 > **練習題**: > 1. 以 `customer_churn.csv` 為例,使用 Plotly 或 Bokeh 生成一個可交互的 **散點矩陣**,並探討 `MonthlyCharges` 與 `TotalCharges` 與 `Churn` 的關係。 > 2. 使用 `seaborn` 的 `pairplot` 對 **所有數值變數** 進行視覺化,並撰寫一段文字說明觀察結果。 > 3. 以 `nbconvert` 產生一份 PDF 報告,並在 GitHub Actions 中設定自動建置。