資料前處理 — 標準化、偏態

Michael Chen
數據領航員
Published in
12 min readJun 26, 2022

前言 —
本篇文章將介紹在特徵處理中針對單一特徵的
規一化 & 標準化、偏態的介紹與以及如何在 python 中使用這些方法,它們是機器學習中必不可少的一個重點,千萬不要錯過哦~

🗺️目錄

機器學習為何需要特徵縮放與轉換?

在機器學習領域中,某些演算法對特徵範圍以及分布非常敏感,換句話說,是否執行這些前處理對於模型的性能影響很大,舉例來說:

  • Gradient Descent Based Algorithms
  • Distance-Based Algorithms

👉詳細介紹在這

規一化 Normalization & 標準化 Standardization

規一化 Normalization

歸一化(Normalization)是一種縮放技術,將資料值縮放在固定的區間中。最常見的方法是將資料縮放後介於 0 和 1 之間,稱作 Min-Max scaling。

Min-Max scaling 公式如下:

圖片取自 — COCOAR操作說明 (coco-ar.com)
  • Xmax 和 Xmin 分別是特徵的最大值和最小值
  • 當 X 的值為該資料維度中的最小值時,分子為 0, 則 X’ 的值為 0
  • 當 X 的值為該列中的最大值時,分子等於分母,則 X’ 的值為 1
  • 當 X 的值介於最小值和最大值之間,則 X’ 的值介於 0 和 1 之間

標準化 Standardization

標準化(Standardization)是另一種縮放技術,目的是將資料值從原始尺度轉換為標準差單位的分數,這意味著資料的均值變為零並且結果分佈具有單位標準差(平均值 = 0、標準差 = 1),稱為 Z score。

Z score 公式如下:

圖片來源 — Basics: Standardization and the Z score | Fred Clavel, Ph.D.
  • X = 原始分數
  • µ = 總體平均
  • σ = 總體標準差

Normalization & Standardization 的使用時機

對於機器學習新手來說,何時應該使用歸一化,何時應該使用標準化是常見的問題,這裡簡單提出兩個觀點:

  • 當資料的分佈不符合常態分佈時,規一化可以有效的將資料縮放。在不需要任何資料分布假設的演算法上很有用,e.g. K-Nearest Neighbors 和神經網絡。
  • 當資料符合常態分佈時,標準化則會有幫助。此外,在最大值與最小值未知,或存在超出觀察範圍的離群值時,離群值不會被 standardization 降低影嚮力。

但歸根究底,選擇使用規一化還是標準化將取決於你的問題和機器學習算法。除非你的機器學習算法須符合某些基本假設以外,你可以去分別訓練並測試 raw score、normalized score、standardized score 三種分數的模型,比較性能後取得最佳的結果。

Normalization & Standardization 的方法

以下使用 Kaggle Amazon Top 50 Bestselling Books 2009–2022 的資料集中的 User Rating 欄位資料,示範如何使用 python & sklearn 套件進行 Normalization & Standardization 轉換。

👏所有書本的原始用戶評分落在 3.3 ~ 4.9 分之間。

# view User Rating distribution
df['User Rating'].describe()

Normalization

# data normalization with sklearn
from sklearn.preprocessing import MinMaxScaler
# fit scaler on User Rating col (must be 2d array)
norm = MinMaxScaler().fit(df[['User Rating']])
df['norm User Rating'] = norm.transform(df[['User Rating']])
# print out
df[['Name', 'User Rating', 'norm User Rating']].head()
raw score vs. normalized score
df['norm User Rating'].describe()
normalized score distribution

透過 sklearn 提供的 MinMaxScaler 方法將所有評分縮放在 0~1 之間。

Init Score vs. Normalized Score

Standardization

# data standardization with sklearn
from sklearn.preprocessing import StandardScaler
# fit scaler on User Rating col (must be 2d array)
scale = StandardScaler().fit(df[['User Rating']])
df['stand User Rating'] = scale.transform(df[['User Rating']])
# print out
df[['Name', 'User Rating', 'stand User Rating']].head()
raw score vs. standardized score
df['stand User Rating'].describe().apply(lambda x: format(x, 'f'))
standardized score distribution

透過 sklearn 提供的 StandardScaler 方法將評分 mean 調整為 0、std 為 1。

Init Score vs. Standardized Score

偏態(度) Skewness

偏度是指一組資料中偏離對稱分布的失真或不對稱。 如果曲線向左或向右移動,則稱為傾斜。 偏度可以量化為給定資料的分佈與對稱分佈的偏差。

圖片取自 — Skewness — Overview, Types, How to Measure and Interpret (corporatefinanceinstitute.com)
  • 給定資料分佈尾部在右側,則它是一個正偏態分佈,平均值>中位數
  • 給定資料分佈尾部在左側,則它是一個負偏態分佈,平均值<中位數

偏態的重要性
在許多統計分析與機器學習方法中的基本假設時提到資料必須屬於常態分布,若是資料存在偏態而未去除的情況下,則很有可能影響模型性能,e.g. linear regression 。

How transformation can remove skewness and increase accuracy of Linear Regression Model | by Anshika Saxena | Medium

檢查偏態 & 修正偏態的方法

以下使用 Kaggle Amazon Top 50 Bestselling Books 2009–2022 的資料集中的 Reviews 欄位資料,示範如何使用 python 檢查並且修正偏態分布的資料。

✍️不同書籍之間回覆數量(Reviews)分布

# calculate skewness
skewness = round(df['Reviews'].skew(), 2)
print(f"Skewness of Reviews col: {skewness}")
# plot distribution
sns.histplot(df['Reviews'], kde=True)
plt.show()

可以觀察到在 Reviews 欄位呈現正偏態分布(Positive Skew)。

💡常見的修正偏態方法有幾種:

  • 對數去偏(Log Transform)
  • 方根去偏(Square Root Transform)
  • BOX-COX 去偏(Box-Cox Transform)

Log Transform

# fit log transform to Reviews col
df['log_Reviews'] = np.log(df['Reviews'])
# skewness after log transform
skewness = round(df['log_Reviews'].skew(), 2)
print(f"Skewness of Reviews col after log transform: {skewness}")
# plot distribution after log transform
sns.histplot(df['log_Reviews'], kde=True)
plt.show()

Square Root Transform

# fit sqrt transform to Reviews col
df['sqrt_Reviews'] = df['Reviews']**(1/2)
# skewness after sqrt transform
skewness = round(df['sqrt_Reviews'].skew(), 2)
print(f"Skewness of Reviews col after sqrt transform: {skewness}")
# plot distribution after sqrt transform
sns.histplot(df['sqrt_Reviews'], kde=True)
plt.show()

Box-Cox Transform

from scipy.stats import boxcox# fit box cox transform to Reviews col
df['box_cox_Reviews'], lam = boxcox(df['Reviews'])
# skewness after box cox transform
skewness = round(df['box_cox_Reviews'].skew(), 2)
print(f"偏度(Skewness): {skewness}")
# plot distribution after box cox transform
sns.histplot(df['box_cox_Reviews'], kde=True)
plt.show()

結語 —
最後,我們來複習一下本篇文章中提及的內容。包含了為何我們需要
對資料進行處理的理由、標準化 & 規一化的介紹以及方法使用時機與方法、偏態的型態以及檢查與修正的方法。當然,你也可以透過下方參考文章的連結,去一探這些方法背後更深奧的原理!

參考文章

教育部補助大專院校STEM領域及女性研發人才培育計畫目標為建構一個「以智慧物聯技術與實務應用為基礎的教育環境和實作場域」,並規劃出符合此STEM教育領域的創新特色課程,以畢業前進入企業實習的方式,讓學生了解相關產業界所面對的問題,再輔以業界實作場域的教育訓練活動,共同帶領學生發展出動手做、判斷與解決問題的相關技能;本計畫也規劃讓學生以專題實作的組隊方式,跟業界協力領導學生對外參與智慧物聯技術的應用競賽,不僅可以累積學生實務開發的能力,更能激發其潛能來幫助企業解決所面臨的難題。

Data Science Meetup 台灣資料科學社群的使命是「為資料科學人士與企業創建經濟機會」。我們相信大數據蘊藏著巨量的信息和價值,如何處理好大數據並發掘其潛藏的商業價值,就要靠資料科學有效的應用。21世紀是資料科學決勝時代,我們社群將為大家提供與資料科學相關的最新技術和資訊實戰攻略,並透過全球業界人士和學者幫助相關職業規劃與挑戰,社群活動包含

  • 台北實體版聚
  • 線上版聚
  • Mentorship Program

歡迎加入我們社團瞭解更多資訊: https://www.facebook.com/groups/datasciencemeetup/

--

--

Michael Chen
數據領航員

MEng CS Student @ Virginia Tech / Ex Data Engineer @ Merkle / 📩️Email:0429shen@gmail.com