-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrf.py
93 lines (68 loc) · 2.77 KB
/
rf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# -*- coding: utf-8 -*-
"""RF.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/147U52vL-Luw6zJ7Aly3-5RMQ_chWOSbO
"""
# 安装必要的包
!pip install ucimlrepo matplotlib pandas scikit-learn
# 导入必要的库
from ucimlrepo import fetch_ucirepo
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
# 加载数据集
breast_cancer_wisconsin_diagnostic = fetch_ucirepo(id=17)
# 提取特征和目标
X = breast_cancer_wisconsin_diagnostic.data.features
y = breast_cancer_wisconsin_diagnostic.data.targets
# 查看数据的基本信息
print("Dataset Features:\n", X.head())
print("\nTarget Distribution:\n", y.value_counts())
# 训练随机森林模型以计算特征重要性
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X, y)
# 获取特征重要性分数
feature_importances = rf.feature_importances_
# 创建一个 DataFrame 保存特征名称和对应的重要性分数
rf_df = pd.DataFrame({'Feature': X.columns, 'Importance': feature_importances})
rf_df.sort_values(by='Importance', ascending=False, inplace=True)
# 打印最重要的前10个特征
print("\nTop 10 Features by Random Forest Importance:\n", rf_df.head(10))
# 绘制所有特征的重要性分数
plt.figure(figsize=(12, 6))
plt.bar(rf_df['Feature'], rf_df['Importance'])
plt.xticks(rotation=90)
plt.title('Feature Importance by Random Forest')
plt.xlabel('Features')
plt.ylabel('Importance Score')
plt.tight_layout()
plt.show()
# 选择重要性分数高于阈值的特征
threshold = 0.01 # 设定一个合理的阈值
selected_features = rf_df[rf_df['Importance'] > threshold]['Feature'].tolist()
print(f"\nSelected Features (Importance > {threshold}):\n", selected_features)
# 构建新的特征数据集
X_selected = X[selected_features]
# 分割数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_selected, y, test_size=0.2, random_state=42)
# 使用选定特征训练随机森林分类器
rf_selected = RandomForestClassifier(n_estimators=100, random_state=42)
rf_selected.fit(X_train, y_train)
# 测试模型并计算准确率
y_pred = rf_selected.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"\nAccuracy after Random Forest Feature Selection: {accuracy:.4f}")
# 按选定特征绘制柱状图
plt.figure(figsize=(10, 6))
selected_rf = rf_df[rf_df['Feature'].isin(selected_features)]
plt.bar(selected_rf['Feature'], selected_rf['Importance'], color='green')
plt.xticks(rotation=90)
plt.title('Selected Features by Random Forest')
plt.xlabel('Selected Features')
plt.ylabel('Importance Score')
plt.tight_layout()
plt.show()