特征提取(Feature Extraction)特征评估(五)

下面我们将通过一个具体的代码实例来演示特征评估的过程。我们使用经典的"泰坦尼克号生存预测"数据集作为示例,通过特征重要性分析、递归特征消除(RFE)、基于模型的方法(例如:随机森林的重要性评分和SHAP值)来评估特征。

1. 导入必要的库

首先,我们需要导入必要的Python库:

复制代码
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import RFE
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

import shap

2. 加载和预处理数据

我们将使用Pandas来加载数据,并进行必要的预处理,包括处理缺失值和编码类别型变量。

复制代码
# 加载数据集
url = 'https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv'
data = pd.read_csv(url)

# 简单的数据预处理
# 填补年龄中的缺失值
data['Age'].fillna(data['Age'].median(), inplace=True)

# 填补登船港口中的缺失值
data['Embarked'].fillna(data['Embarked'].mode()[0], inplace=True)

# 删除不必要的列
data.drop(['Cabin', 'Ticket', 'Name'], axis=1, inplace=True)

# 显示数据集的前几行
print(data.head())

3. 特征和目标变量

我们将"Survived"列作为目标变量,其他列作为特征。

复制代码
# 定义特征和目标变量
X = data.drop('Survived', axis=1)
y = data['Survived']

4. 特征编码和标准化

我们使用ColumnTransformerPipeline来处理数值型和类别型特征。

复制代码
# 数值型和类别型特征
numeric_features = ['Age', 'Fare', 'SibSp', 'Parch']
categorical_features = ['Pclass', 'Sex', 'Embarked']

# 创建预处理器:数值特征标准化,类别特征One-Hot编码
preprocessor = ColumnTransformer(
    transformers=[
        ('num', StandardScaler(), numeric_features),
        ('cat', OneHotEncoder(), categorical_features)])

# 构建预处理和模型的Pipeline
model = Pipeline(steps=[('preprocessor', preprocessor),
                        ('classifier', RandomForestClassifier(random_state=42))])

5. 特征重要性分析

首先,我们使用随机森林来评估特征的重要性。

复制代码
# 拆分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model.fit(X_train, y_train)

# 提取特征名(包括One-Hot编码后的)
feature_names = numeric_features + list(model.named_steps['preprocessor'].transformers_[1][1].get_feature_names_out(categorical_features))

# 获取特征重要性
importances = model.named_steps['classifier'].feature_importances_

# 创建特征重要性DataFrame
feature_importances = pd.DataFrame({'Feature': feature_names, 'Importance': importances})
feature_importances = feature_importances.sort_values(by='Importance', ascending=False)

# 可视化特征重要性
plt.figure(figsize=(10, 6))
sns.barplot(x='Importance', y='Feature', data=feature_importances)
plt.title('Feature Importance')
plt.show()

6. 递归特征消除(RFE)

我们将使用RFE来评估和选择最重要的特征。

复制代码
# 使用逻辑回归作为基模型进行RFE
rfe_model = RFE(estimator=LogisticRegression(), n_features_to_select=5, step=1)
rfe_model = Pipeline(steps=[('preprocessor', preprocessor),
                            ('selector', rfe_model)])

# 训练RFE模型
rfe_model.fit(X_train, y_train)

# 获取选择的特征
selected_features = np.array(feature_names)[rfe_model.named_steps['selector'].support_]

# 打印选择的特征
print("Selected Features by RFE:")
print(selected_features)

7. 使用SHAP值评估特征

SHAP值可以帮助我们理解每个特征如何影响模型的预测。

复制代码
# 创建SHAP解释器
explainer = shap.TreeExplainer(model.named_steps['classifier'])

# 对测试集进行预测
X_test_preprocessed = model.named_steps['preprocessor'].transform(X_test)

# 计算SHAP值
shap_values = explainer.shap_values(X_test_preprocessed)

# 可视化SHAP值
shap.summary_plot(shap_values[1], X_test_preprocessed, feature_names=feature_names)

8. 模型评估

最后,我们评估模型在测试集上的表现。

复制代码
# 在测试集上进行预测
y_pred = model.predict(X_test)

# 打印分类报告
print("Classification Report:")
print(classification_report(y_test, y_pred))

# 显示混淆矩阵
conf_matrix = confusion_matrix(y_test, y_pred)
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.show()
相关推荐
feasibility.几秒前
AI 编程助手进阶指南:从 Claude Code 到 OpenCode 的工程化经验总结
人工智能·经验分享·设计模式·自动化·agi·skills·opencode
程序猿追几秒前
深度剖析 CANN ops-nn 算子库:架构设计、演进与代码实现逻辑
人工智能·架构
灰灰勇闯IT3 分钟前
领域制胜——CANN 领域加速库(ascend-transformer-boost)的场景化优化
人工智能·深度学习·transformer
灰灰勇闯IT4 分钟前
从零到一——CANN 社区与 cann-recipes-infer 实践样例的启示
人工智能
小白狮ww7 分钟前
要给 OCR 装个脑子吗?DeepSeek-OCR 2 让文档不再只是扫描
人工智能·深度学习·机器学习·ocr·cpu·gpu·deepseek
lili-felicity9 分钟前
CANN优化LLaMA大语言模型推理:KV-Cache与FlashAttention深度实践
人工智能·语言模型·llama
程序猿追11 分钟前
深度解码昇腾 AI 算力引擎:CANN Runtime 核心架构与技术演进
人工智能·架构
金融RPA机器人丨实在智能11 分钟前
Android Studio开发App项目进入AI深水区:实在智能Agent引领无代码交互革命
android·人工智能·ai·android studio
lili-felicity15 分钟前
CANN异步推理实战:从Stream管理到流水线优化
大数据·人工智能
做人不要太理性15 分钟前
CANN Runtime 运行时组件深度解析:任务下沉执行、异构内存规划与全栈维测诊断机制
人工智能·神经网络·魔珐星云