【特征工程】归一化/标准化/正则化
source link: https://www.guofei.site/2017/11/24/scale.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
【特征工程】归一化/标准化/正则化
2017年11月24日Author: Guofei
文章归类: 1-3-特征工程 ,文章编号: 99
版权声明:本文作者是郭飞。转载随意,但需要标明原文链接,并通知本人
原文链接:https://www.guofei.site/2017/11/24/scale.html
标准化
标准化1是对列操作
数据准备:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.uniform(size=(20, 3)), columns=list('abc'))
StandardScaler
# (Z-Score)
# 公式为:(X-mean)/std 计算时对每个属性/每列分别进行。
from sklearn import preprocessing as preprocessing
standard_scaler = preprocessing.StandardScaler()
standard_scaler.fit_transform(df)
standard_scaler.fit(df)
standard_scaler.transform(df)
MinMaxScaler
0-1标准化
使用这种方法的目的包括:
- 对于方差非常小的 feature 可以增强其稳定性。
- 如果是正的稀疏矩阵,可以维持为0的条目。
from sklearn import preprocessing
min_max_scaler = preprocessing.MinMaxScaler()
min_max_scaler.fit_transform(df)
min_max_scaler.fit(df)
min_max_scaler.transform(df)
MaxAbsScaler
列除以该列的最大值。优点是可以保持稀疏矩阵中的0不变。
from sklearn import preprocessing
max_abs_scaler = preprocessing.MaxAbsScaler()
max_abs_scaler.fit_transform(df)
max_abs_scaler.fit(df)
max_abs_scaler.transform(df)
RobustScaler
一种可以防止异常值的Scaler。算法是减去0.5分位数,然后除以0.75-0.25极差。
from sklearn import preprocessing
robust_scaler=preprocessing.RobustScaler(with_centering=True, with_scaling=True, quantile_range=(25.0, 75.0))
robust_scaler.fit_transform(df)
robust_scaler.fit(df)
robust_scaler.transform(df)
正则化(Normalization)
每个样本变成单位范数
from sklearn import preprocessing
normalizer = preprocessing.Normalizer(norm='l2') # l1, l2, max
normalizer.fit(df)
normalizer.transform(df)
OneHotEncoder
from sklearn import preprocessing
import pandas as pd
df = pd.DataFrame(np.random.randint(low=0, high=3, size=(10, 3)), columns=list('abc'))
onehotencoder = preprocessing.OneHotEncoder()
onehotencoder.fit(df)
onehotencoder.n_values_ # 每个feature有多少种value,例如 array([3, 3, 3])
onehotencoder.feature_indices_ # 第i个feature被映射到 feature_indices_[i] to feature_indices_[i+1]
onehotencoder.transform(df).toarray() # OneHotEncoder 的结果
PolynomialFeatures
在输入数据存在非线性特征时,这一操作对增加模型的复杂度十分有用。
例如,特征向量X=(X1, X2),最高项次数为2,被转化为(1, X1, X2, X1^2, X1X2, X2^2)
如果最高为n次方,有m个feature,那么转化后得到comb(n+m,m)个feature
(因为(∑mi=1xi)n(∑i=1mxi)n展开后有comb(m+n+1,n)项)
from sklearn import preprocessing
polynomial_features = preprocessing.PolynomialFeatures(degree=2) # 最高项的次数为2
# interaction_only=True 只产生相互作用项
polynomial_features.fit_transform(df)
polynomial_features.fit(df)
polynomial_features.transform(df)
FunctionTransformer
自定义预处理器
from sklearn import preprocessing
function_transformer=preprocessing.FunctionTransformer(lambda x:np.log(x+100))
function_transformer.fit_transform(df)
function_transformer.fit(df)
function_transformer.transform(df)
参考资料
您的支持将鼓励我继续创作!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK