from sklearn import preprocessing?
縮放:preprocessing.MinMaxScaler(feature_range=(0, 1)) #在神經(jīng)網(wǎng)絡(luò)中則更推薦使用 min-max 縮放
-1到1:preprocessing.MaxAbsScaler()
標(biāo)準(zhǔn)化:preprocessing.StandardScaler() #在主成分分析中標(biāo)準(zhǔn)化方法更有用
中值:preprocessing.RobustScaler()? #有極端異常值時(shí)拓萌,使用中位數(shù)、四分位數(shù)縮放
歸一化:preprocessing.Normalizer() #norm='l2'??對觀察值每一個(gè)特征進(jìn)行縮放升略,使其擁有一致的范數(shù)(總長度是 1)主要應(yīng)用于文本分類和聚類中
生成多項(xiàng)式特征和交叉項(xiàng)
1.當(dāng)特征和目標(biāo)值(預(yù)測值)之間存在非線性關(guān)系時(shí)微王,就需要?jiǎng)?chuàng)建多項(xiàng)式特征屡限。
2.這兩個(gè)特征對目標(biāo)值的作用是相互依賴的。生成一個(gè)交互特征(將兩個(gè)特征相乘)
polynomial_interaction = preprocessing.PolynomialFeatures(degree=2, include_bias=False) #階數(shù)炕倘,是否包含偏差
#interaction_only 為 True囚霸,可以強(qiáng)制創(chuàng)建出來的特征只包含交互特征
特征轉(zhuǎn)換? 等價(jià)于apply()
def add_ten(x):
? ? return x + 10
ten_transformer =preprocessing.FunctionTransformer(add_ten)
ten_transformer.transform(features)
異常值處理
識(shí)別:
法一:按比例識(shí)別
from sklearn.covariance import EllipticEnvelope?
outlier_detector = EllipticEnvelope(contamination=.1) #contamination異常值比例
outlier_detector.fit(features)
outlier_detector.predict(features)
法二:按中位數(shù)識(shí)別
IQR 是數(shù)據(jù)集的第 1 個(gè)四分位數(shù)和第 3 個(gè)四分位數(shù)之差
異常值常常被定義為比第 1 個(gè)四分位數(shù)小 1.5 IQR(即 IQR 的 1.5 倍)的值,或比第 3 個(gè)四分位數(shù)大 1.5 IQR的值激才。
# 創(chuàng)建一個(gè)函數(shù)來返回異常值的下標(biāo)
def indicies_of_outliers(x):
? ? q1, q3 = np.percentile(x, [25, 75])
? ? iqr = q3 - q1
? ? lower_bound = q1 - (iqr * 1.5)
? ? upper_bound = q3 + (iqr * 1.5)
? ? return np.where((x > upper_bound) | (x < lower_bound))
處理
1.刪除
2.標(biāo)記
houses["Outlier"] = np.where(houses["Bathrooms"] < 20, 0, 1)
3.轉(zhuǎn)換
houses["Log_Of_Square_Feet"] = [np.log(x) for x in houses["Square_Feet"]]
數(shù)據(jù)離散化
二元離散
binarizer = preprocessing.Binarizer(18)
binarizer.fit_transform(age)
多元離散
np.digitize(age, bins=[20,30,64]) #每個(gè)區(qū)間的左邊界(左閉右開)
聚類
from sklearn.cluster import KMeans #聚類
clusterer = KMeans(3, random_state=0)
缺失值處理
刪除
features[~np.isnan(features).any(axis=1)] #刪除帶有缺失值的觀察值
dataframe.dropna()
填充缺失值(平均、中值额嘿、眾數(shù)等)
from sklearn.preprocessing import Imputer
mean_imputer = Imputer(strategy="mean", axis=0)
features_mean_imputed = mean_imputer.fit_transform(features)
預(yù)測缺失值
features_knn_imputed = KNN(k=5, verbose=0).complete(standardized_features)