基于随机森林的特征选择python
时间: 2023-10-16 14:07:36 浏览: 48
在Python中,可以使用sklearn库中的RandomForestClassifier来实现基于随机森林的特征选择。
首先,需要导入所需的库:
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
import numpy as np
```
然后,加载数据集,这里以鸢尾花数据集为例:
```python
iris = load_iris()
X = iris.data
y = iris.target
```
接着,创建随机森林分类器,并进行训练:
```python
rfc = RandomForestClassifier()
rfc.fit(X, y)
```
训练完成后,可以通过feature_importances_属性获取每个特征的重要性分数:
```python
importances = rfc.feature_importances_
```
如果想要选择重要性分数排名前k个的特征,可以按照如下代码实现:
```python
k = 2
indices = np.argsort(importances)[::-1][:k]
```
最后,可以输出选择的特征:
```python
print("Selected Features:")
for i in indices:
print(i, iris.feature_names[i])
```
完整代码如下:
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
import numpy as np
iris = load_iris()
X = iris.data
y = iris.target
rfc = RandomForestClassifier()
rfc.fit(X, y)
importances = rfc.feature_importances_
k = 2
indices = np.argsort(importances)[::-1][:k]
print("Selected Features:")
for i in indices:
print(i, iris.feature_names[i])
```
输出结果为:
```
Selected Features:
2 petal length (cm)
3 petal width (cm)
```
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.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)