请帮我写一段对df表所有特征列进行归一化处理,标签列为连续型变量,再对处理后的特征使用 RFECV(采用多种基模型)进行特征选择的python代码
时间: 2023-06-14 09:04:57 浏览: 63
以下是对df表所有特征列进行归一化处理,标签列为连续型变量,再对处理后的特征使用 RFECV 进行特征选择的 Python 代码:
```python
from sklearn.preprocessing import MinMaxScaler
from sklearn.feature_selection import RFECV
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.model_selection import StratifiedKFold
import pandas as pd
# 假设df为数据框,label为标签列名字
X = df.drop(label, axis=1)
y = df[label]
# 对特征进行归一化处理
scaler = MinMaxScaler()
X = scaler.fit_transform(X)
# 定义需要用到的模型
rf = RandomForestRegressor(n_estimators=10)
lr = LinearRegression()
svr = SVR(kernel='linear')
# 定义需要用到的交叉验证方式
cv = StratifiedKFold(n_splits=10)
# 对处理后的特征使用 RFECV 进行特征选择
rfecv_rf = RFECV(estimator=rf, cv=cv, scoring='r2')
rfecv_rf.fit(X, y)
rfecv_lr = RFECV(estimator=lr, cv=cv, scoring='r2')
rfecv_lr.fit(X, y)
rfecv_svr = RFECV(estimator=svr, cv=cv, scoring='r2')
rfecv_svr.fit(X, y)
# 获取特征选择结果
rfecv_result = pd.DataFrame({
'Feature': df.columns[:-1],
'Ranking_RandomForest': rfecv_rf.ranking_,
'Ranking_LinearRegression': rfecv_lr.ranking_,
'Ranking_SupportVectorRegression': rfecv_svr.ranking_
}).sort_values(by='Ranking_RandomForest')
print(rfecv_result)
```
上述代码中,使用了 `sklearn.preprocessing.MinMaxScaler` 对特征进行归一化处理,使用了 `sklearn.feature_selection.RFECV` 进行特征选择,采用了三种不同的基模型:`sklearn.ensemble.RandomForestRegressor`,`sklearn.linear_model.LinearRegression` 和 `sklearn.svm.SVR`,并使用了 `sklearn.model_selection.StratifiedKFold` 进行交叉验证。最后将特征选择结果存储在一个数据框中并排序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)