Skip to content

Week9 Demo Standard Scaling & Min-Max Scaling

建立一個 Week9_demo1.py 的檔案

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler, StandardScaler

# 1. 建立模擬數據 (年齡 vs 年薪)
np.random.seed(42)
n = 300
age = np.random.normal(loc=35, scale=10, size=n)
income = np.random.exponential(scale=50000, size=n) + 22000

df = pd.DataFrame({"Age": age, "Income": income})

# 2. Min-Max Scaling (縮放到 0 ~ 1)
minmax_scaler = MinMaxScaler()
df[["Age_MinMax", "Income_MinMax"]] = minmax_scaler.fit_transform(
    df[["Age", "Income"]]
)

# 3. Standard Scaling (Z-Score, 平均0, 標準差1)
std_scaler = StandardScaler()
df[["Age_Std", "Income_Std"]] = std_scaler.fit_transform(df[["Age", "Income"]])

# 4. 繪製對比圖
fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))

# 原始資料
axes[0].scatter(df["Age"], df["Income"], alpha=0.7, color="#3498db")
axes[0].set_title("1. Original Data (Scale Mismatch)")
axes[0].set_xlabel("Age (15~65)")
axes[0].set_ylabel("Income (20k~250k)")

# Min-Max 縮放結果
axes[1].scatter(
    df["Age_MinMax"], df["Income_MinMax"], alpha=0.7, color="#2ecc71"
)
axes[1].set_title("2. Min-Max Scaling [0, 1]")
axes[1].set_xlabel("Scaled Age")
axes[1].set_ylabel("Scaled Income")

# Standard Scaling 結果
axes[2].scatter(df["Age_Std"], df["Income_Std"], alpha=0.7, color="#e74c3c")
axes[2].set_title("3. Standard Scaling (Z-Score)")
axes[2].set_xlabel("Standardized Age")
axes[2].set_ylabel("Standardized Income")

plt.tight_layout()
plt.show()

Leave a comment

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