特征重要性分析

Python数据分析入门Python

问题

如何分析哪些特征对预测结果影响最大?

答题要点

import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

# 准备数据
df = pd.read_csv('user_data.csv')
features = ['age', 'income', 'order_count', 'active_days', 'avg_order_value']
X = df[features]
y = df['is_churned']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 训练模型
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# 方法1:模型内置特征重要性
importances = model.feature_importances_
feature_importance = pd.DataFrame({
    'feature': features,
    'importance': importances
}).sort_values('importance', ascending=False)

print("特征重要性:")
print(feature_importance)

# 可视化
plt.figure(figsize=(10, 6))
plt.barh(feature_importance['feature'], feature_importance['importance'])
plt.xlabel('重要性')
plt.title('特征重要性分析')
plt.tight_layout()
plt.show()

# 方法2:排列重要性(更准确)
from sklearn.inspection import permutation_importance

perm_importance = permutation_importance(
    model, X_test, y_test, n_repeats=10, random_state=42
)

perm_importance_df = pd.DataFrame({
    'feature': features,
    'importance': perm_importance.importances_mean,
    'std': perm_importance.importances_std
}).sort_values('importance', ascending=False)

print("\n排列重要性:")
print(perm_importance_df)

# 方法3:SHAP值(最佳)
import shap

# 创建SHAP解释器
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_test)

# 特征重要性摘要
shap.summary_plot(shap_values[1], X_test, feature_names=features)

# 单个样本解释
shap.force_plot(
    explainer.expected_value[1],
    shap_values[1][0],
    X_test.iloc[0],
    feature_names=features
)

# 依赖图(特征与目标关系)
shap.dependence_plot('age', shap_values[1], X_test, feature_names=features)

# 运营洞察
print("\n运营建议:")
top3_features = feature_importance.head(3)['feature'].tolist()
print(f"关键影响因素: {', '.join(top3_features)}")
print(f"优化建议: 重点关注{top3_features[0]}指标的提升")

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题