數(shù)據(jù)中不同特征的量綱可能不一致,數(shù)值間的差別可能很大,不進(jìn)行處理可能會(huì)影響到數(shù)據(jù)分析的結(jié)果,因此,需要對(duì)數(shù)據(jù)按照一定比例進(jìn)行縮放,使之落在一個(gè)特定的區(qū)域,便于進(jìn)行綜合分析。
常用的方法有兩種:
最大 - 最小規(guī)范化:對(duì)原始數(shù)據(jù)進(jìn)行線性變換,將數(shù)據(jù)映射到[0,1]區(qū)間
Z-Score標(biāo)準(zhǔn)化:將原始數(shù)據(jù)映射到均值為0、標(biāo)準(zhǔn)差為1的分布上
提升模型精度:標(biāo)準(zhǔn)化/歸一化后,不同維度之間的特征在數(shù)值上有一定比較性,可以大大提高分類器的準(zhǔn)確性。
加速模型收斂:標(biāo)準(zhǔn)化/歸一化后,最優(yōu)解的尋優(yōu)過程明顯會(huì)變得平緩,更容易正確的收斂到最優(yōu)解。
如下圖所示:
1)需要使用梯度下降和計(jì)算距離的模型要做歸一化,因?yàn)椴蛔鰵w一化會(huì)使收斂的路徑程z字型下降,導(dǎo)致收斂路徑太慢,而且不容易找到最優(yōu)解,歸一化之后加快了梯度下降求最優(yōu)解的速度,并有可能提高精度。比如說線性回歸、邏輯回歸、adaboost、xgboost、GBDT、SVM、NeuralNetwork等。需要計(jì)算距離的模型需要做歸一化,比如說KNN、KMeans等。
2)概率模型、樹形結(jié)構(gòu)模型不需要?dú)w一化,因?yàn)樗鼈儾魂P(guān)心變量的值,而是關(guān)心變量的分布和變量之間的條件概率,如決策樹、隨機(jī)森林。
#導(dǎo)入數(shù)據(jù)
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('Data.csv')
缺失值均值填充,處理字符型變量
df['Salary'].fillna((df['Salary'].mean()), inplace= True)
df['Age'].fillna((df['Age'].mean()), inplace= True)
df['Purchased'] = df['Purchased'].apply(lambda x: 0 if x=='No' else 1)
df=pd.get_dummies(data=df, columns=['Country'])
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(df)
scaled_features = scaler.transform(df)
df_MinMax = pd.DataFrame(data=scaled_features, columns=["Age", "Salary","Purchased","Country_France","Country_Germany", "Country_spain"])
Z-Score標(biāo)準(zhǔn)化
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
sc_X = sc_X.fit_transform(df)
sc_X = pd.DataFrame(data=sc_X, columns=["Age", "Salary","Purchased","Country_France","Country_Germany", "Country_spain"])
import seaborn as sns
import matplotlib.pyplot as plt
import statistics
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
fig,axes=plt.subplots(2,3,figsize=(18,12))
sns.distplot(df['Age'], ax=axes[0, 0])
sns.distplot(df_MinMax['Age'], ax=axes[0, 1])
axes[0, 1].set_title('歸一化方差:% s '% (statistics.stdev(df_MinMax['Age'])))
sns.distplot(sc_X['Age'], ax=axes[0, 2])
axes[0, 2].set_title('標(biāo)準(zhǔn)化方差:% s '% (statistics.stdev(sc_X['Age'])))
sns.distplot(df['Salary'], ax=axes[1, 0])
sns.distplot(df_MinMax['Salary'], ax=axes[1, 1])
axes[1, 1].set_title('MinMax:Salary')
axes[1, 1].set_title('歸一化方差:% s '% (statistics.stdev(df_MinMax['Salary'])))
sns.distplot(sc_X['Salary'], ax=axes[1, 2])
axes[1, 2].set_title('StandardScaler:Salary')
axes[1, 2].set_title('標(biāo)準(zhǔn)化方差:% s '% (statistics.stdev(sc_X['Salary'])))
可以看出歸一化比標(biāo)準(zhǔn)化方法產(chǎn)生的標(biāo)準(zhǔn)差小,使用歸一化來縮放數(shù)據(jù),則數(shù)據(jù)將更集中在均值附近。這是由于歸一化的縮放是“拍扁”統(tǒng)一到區(qū)間(僅由極值決定),而標(biāo)準(zhǔn)化的縮放是更加“彈性”和“動(dòng)態(tài)”的,和整體樣本的分布有很大的關(guān)系。所以歸一化不能很好地處理離群值,而標(biāo)準(zhǔn)化對(duì)異常值的魯棒性強(qiáng),在許多情況下,它優(yōu)于歸一化。
參考:https://towardsdatascience.com/data-transformation-standardisation-vs-normalisation-a47b2f38cec2
加入機(jī)器學(xué)習(xí)、Python微信群
聯(lián)系客服