大师兄的数据分析学习笔记(十一):特征预处理(二)

2022-06-03  本文已影响0人  superkmi

大师兄的数据分析学习笔记(十):特征预处理(一)
大师兄的数据分析学习笔记(十二):特征预处理(三)

三、特征选择

1. 过滤思想
>>>import os
>>>import pandas as pd
>>>from sklearn.feature_selection import SelectKBest

>>>df = pd.read_csv(os.path.join(".", "data", "WA_Fn-UseC_-HR-Employee-Attrition.csv"))
>>>X = df.loc[:, ["Age", "Education", "HourlyRate"]]  # 特征
>>>Y = df.loc[:, "JobSatisfaction"]  # 标注

>>>skb = SelectKBest(k=2)  # 过滤思想
>>>skb.fit(X, Y)  # 拟合
>>>print(skb.transform(X))
[[ 2 94]
 [ 1 61]
 [ 2 92]
 ...
 [ 3 87]
 [ 3 63]
 [ 3 82]]
2. 包裹思想

第一步:列出集合x。
第二步:构造简单的模型进行训练,根据系数去掉比较弱的特征。
第三步:余下的特征重复这个过程吗,直到评价指标下降较大或低于阈值。

>>>import os
>>>import pandas as pd
>>>from sklearn.svm import SVR
>>>from sklearn.feature_selection import RFE

>>>df = pd.read_csv(os.path.join(".", "data", "WA_Fn-UseC_-HR-Employee-Attrition.csv"))
>>>X = df.loc[:, ["Age", "Education", "HourlyRate"]]  # 特征
>>>Y = df.loc[:, "JobSatisfaction"]  # 标注

>>>rfe = RFE(estimator=SVR(kernel="linear"), n_features_to_select=2, step=1)  # 包括思想
>>>print(rfe.fit_transform(X,Y))
[[41  2]
 [49  1]
 [37  2]
 ...
 [27  3]
 [49  3]
 [34  3]]
3. 嵌入思想
>>>import os
>>>import pandas as pd
>>>from sklearn.tree import DecisionTreeRegressor
>>>from sklearn.feature_selection import SelectFromModel

>>>df = pd.read_csv(os.path.join(".", "data", "WA_Fn-UseC_-HR-Employee-Attrition.csv"))
>>>X = df.loc[:, ["Age", "Education", "HourlyRate"]]  # 特征
>>>Y = df.loc[:, "JobSatisfaction"]  # 标注

>>>sfm = SelectFromModel(estimator=DecisionTreeRegressor(), threshold=0.2)  # 嵌入思想
>>>print(sfm.fit_transform(X, Y))
[[41 94]
 [49 61]
 [37 92]
 ...
 [27 87]
 [49 63]
 [34 82]]
上一篇下一篇

猜你喜欢

热点阅读