Skip to content

Week 7 Demo code

我們一樣回到 PyCharm IDE 的 project 內建立一個叫做 week7_demo_data.py 的檔案

import numpy as np
import pandas as pd

#### 快速生成 Demo 資料集 ####
# 設定隨機種子,確保全班結果一致
np.random.seed(42)
n_samples = 1000

# 建立模擬數據:電商客戶行為資料
df = pd.DataFrame(
    {
        'CustomerID': [f'CUST_{i:04d}' for i in range(1, n_samples + 1)],
        'MemberLevel': np.random.choice(
            ['Standard', 'VIP', 'VVIP'], size=n_samples, p=[0.6, 0.3, 0.1]
        ),
        'MonthlyCharges': np.random.normal(
            loc=1200, scale=350, size=n_samples
        ).round(2),
        'TotalPurchases': np.random.poisson(lam=12, size=n_samples),
        'Churn': np.random.choice(
            [0, 1], size=n_samples, p=[0.88, 0.12]
        ),  # 模擬不平衡標籤 (12% 流失)
    }
)

# 修正極端負值
df.loc[df['MonthlyCharges'] < 300, 'MonthlyCharges'] = 350.0

# 查看前 5 筆資料
df.head()
#### 快速生成 Demo 資料集 END ####

#### Pandas 高階數據聚合 ####
# 任務:計算各會員等級的「平均月消費」、「總購買次數」與「客戶人數」
summary_df = df.groupby('MemberLevel').agg(
    avg_charges=('MonthlyCharges', 'mean'),
    total_purchases=('TotalPurchases', 'sum'),
    customer_count=('CustomerID', 'count'),
).reset_index()

# 格式化輸出
summary_df['avg_charges'] = summary_df['avg_charges'].round(2)

#### Pandas 高階數據聚合 END ####

#### EDA 視覺化與 AI 標籤健康檢查 ####
import matplotlib.pyplot as plt
import seaborn as sns

# 設定畫布主題與大小
sns.set_theme(style='whitegrid')
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

# 1. 檢驗 Target (Churn) 標籤平衡度 (修正版)
sns.countplot(
    x='Churn',
    data=df,
    ax=axes[0],
    hue='Churn',
    palette='Set2',
    legend=False,
)
axes[0].set_title(
    '1. Churn Label Distribution (Class Imbalance Check)', fontsize=12
)
axes[0].set_xlabel('Churn (0 = Retained, 1 = Churned)')
axes[0].set_ylabel('Customer Count')

# 在長條圖上標註實際人數
for p in axes[0].patches:
  axes[0].annotate(
      f'{int(p.get_height())}',
      (p.get_x() + p.get_width() / 2.0, p.get_height()),
      ha='center',
      va='center',
      xytext=(0, 5),
      textcoords='offset points',
  )

# 2. 檢驗 MonthlyCharges 特徵對 Churn 的區分能力 (修正版)
sns.boxplot(
    x='Churn',
    y='MonthlyCharges',
    data=df,
    ax=axes[1],
    hue='Churn',
    palette='Set2',
    legend=False,
)
axes[1].set_title('2. Monthly Charges vs Customer Churn', fontsize=12)
axes[1].set_xlabel('Churn (0 = Retained, 1 = Churned)')
axes[1].set_ylabel('Monthly Charges ($)')

plt.tight_layout()
plt.show()

這支程式分為三個 parts
Part 1, 建立模擬數據:電商客戶行為資料
Part 2, Pandas 高階數據聚合
Part 3, EDA 視覺化與 AI 標籤健康檢查

Leave a comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *