机器学习手册学习笔记--处理数值型数据

232 阅读2分钟

仅供自己复习回顾使用,若有侵权可删除

from sklearn import preprocessing 
#缩放
preprocessing.MinMaxScaler(feature_range=(0, 1)) #在神经网络中则更推荐使用 min-max 缩放

#-11
preprocessing.MaxAbsScaler()

#标准化
preprocessing.StandardScaler() #在主成分分析中标准化方法更有用

#中值
preprocessing.RobustScaler() #有极端异常值时,使用中位数、四分位数缩放

#归一化
preprocessing.Normalizer() #主要应用于文本分类和聚类中
#norm='l2'  对观察值每一个特征进行缩放,使其拥有一致的范数(总长度是 1

生成多项式特征和交叉项

1.当特征和目标值(预测值)之间存在非线性关系时,就需要创建多项式特征。

2.这两个特征对目标值的作用是相互依赖的。生成一个交互特征(将两个特征相乘)

preprocessing.PolynomialFeatures(degree=2, include_bias=False) 
#阶数,是否包含偏差
#interaction_only 为 True,可以强制创建出来的特征只包含交互特征

特征转换  等价于apply()

def add_ten(x):
    return x + 10
ten_transformer =preprocessing.FunctionTransformer(add_ten)
ten_transformer.transform(features)

异常值处理

识别:

法一:按比例识别

from sklearn.covariance import EllipticEnvelope 
outlier_detector = EllipticEnvelope(contamination=.1) #contamination异常值比例
outlier_detector.fit(features)
outlier_detector.predict(features)

法二:按中位数识别

IQR 是数据集的第 1 个四分位数和第 3 个四分位数之差

异常值常常被定义为比第 1 个四分位数小 1.5 IQR(即 IQR 的 1.5 倍)的值,或比第 3 个四分位数大 1.5 IQR的值。

# 创建一个函数来返回异常值的下标
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.标记

houses["Outlier"] = np.where(houses["Bathrooms"] < 20, 0, 1)

3.转换

houses["Log_Of_Square_Feet"] = [np.log(x) for x in houses["Square_Feet"]]

数据离散化

二元离散

binarizer = preprocessing.Binarizer(18)

binarizer.fit_transform(age)

多元离散

np.digitize(age, bins=[20,30,64]) #每个区间的左边界(左闭右开)

聚类

from sklearn.cluster import KMeans #聚类

clusterer = KMeans(3, random_state=0)

缺失值处理

删除

features[~np.isnan(features).any(axis=1)] #删除带有缺失值的观察值

dataframe.dropna()

填充缺失值(平均、中值、众数等)

from sklearn.preprocessing import Imputer

mean_imputer = Imputer(strategy="mean", axis=0)

features_mean_imputed = mean_imputer.fit_transform(features)

预测缺失值

features_knn_imputed = KNN(k=5, verbose=0).complete(standardized_features)