特征提取(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. 特征编码和标准化

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

复制代码
# 数值型和类别型特征
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()
相关推荐
汤姆宝库7 小时前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
岁月宁静7 小时前
从零拆解 AI 语音模拟面试系统
人工智能·python·agent
武子康8 小时前
H3-World 接入 Game Agent:谁来判断门真的打开了?
人工智能·算法·机器学习
可乐ea9 小时前
MCP 和 CLI 差 42 倍:一次 GitHub 任务的上下文成本实测
人工智能·github·工具调用·ai智能体·openrouter·mcp协议·上下文优化
kyriewen9 小时前
编辑弹窗点了取消,列表里的数据怎么还是变了?
前端·javascript·人工智能
泯泷9 小时前
Multica 真正打动我的,不是更多 Agent,而是一种新的团队协作方式
人工智能·llm·agent
电科_银尘9 小时前
【深度学习项目实战·22】灰度图像着色:用小型U-Net学习从灰度到RGB
人工智能·深度学习·学习
阿里云大数据AI技术9 小时前
云栖实录|倍思科技 × 阿里云:让VOC洞察从“生成报告”走向“业务可用”
人工智能·elasticsearch·agent
XLYcmy10 小时前
基于大语言模型的智能漏洞检测与修复系统 作品报告评审分析报告 下
机器学习·llm·prompt·api·token·漏洞修复·漏洞检测
AllData公司负责人10 小时前
第九篇:AI大模型数据开发底座系列说明书:AllData集成BISHENG开源项目建设大模型应用开发底座,涵盖可视化编排/智能助手/一键API/模型接入!
人工智能·云原生·数据分析·视觉检测·知识图谱·大模型应用·bisheng