intial commit (forked from private repo)
This commit is contained in:
65
extracted_cells/cell17.py
Normal file
65
extracted_cells/cell17.py
Normal file
@ -0,0 +1,65 @@
|
||||
# Erkläre die Vorhersage mit LIME
|
||||
|
||||
def analyze_lime_feature_importance(instance, rf_model, lime_explainer, num_features=5):
|
||||
"""
|
||||
Analysiert die Feature-Wichtigkeiten der LIME-Erklärung.
|
||||
"""
|
||||
# LIME-Erklärung generieren
|
||||
exp = lime_explainer.explain_instance(
|
||||
instance,
|
||||
rf_model.predict_proba,
|
||||
num_features=num_features
|
||||
)
|
||||
|
||||
# Random Forest Vorhersage (nur zur Information)
|
||||
feature_names = rf_model.feature_names_in_
|
||||
instance_df = pd.DataFrame([instance], columns=feature_names)
|
||||
rf_prediction = rf_model.predict_proba(instance_df)[0, 1]
|
||||
|
||||
# Feature-Wichtigkeiten aus LIME extrahieren
|
||||
feature_importance = exp.as_list()
|
||||
|
||||
# Visualisierung der Feature-Wichtigkeiten
|
||||
plt.figure(figsize=(10, 6))
|
||||
|
||||
# Features und ihre Wichtigkeiten trennen
|
||||
features, importances = zip(*feature_importance)
|
||||
|
||||
# Balkendiagramm erstellen
|
||||
colors = ['red' if imp < 0 else 'green' for imp in importances]
|
||||
y_pos = np.arange(len(features))
|
||||
|
||||
plt.barh(y_pos, importances, color=colors)
|
||||
plt.yticks(y_pos, features)
|
||||
|
||||
plt.xlabel('Feature-Einfluss')
|
||||
plt.title('LIME Feature-Wichtigkeiten')
|
||||
|
||||
# Vertikale Linie bei 0 für bessere Lesbarkeit
|
||||
plt.axvline(x=0, color='black', linestyle='-', alpha=0.3)
|
||||
|
||||
plt.grid(alpha=0.3)
|
||||
plt.tight_layout()
|
||||
plt.savefig('output/lime_feature_importance.png', dpi=300)
|
||||
plt.show()
|
||||
|
||||
# Ausgabe der Ergebnisse
|
||||
print("\nLIME Feature-Wichtigkeiten Analyse:")
|
||||
print("-" * 50)
|
||||
print(f"Random Forest Vorhersage für diese Instanz: {rf_prediction:.4f}")
|
||||
print("\nFeature-Einflüsse:")
|
||||
for feature, importance in feature_importance:
|
||||
print(f"{feature}: {importance:+.4f}")
|
||||
|
||||
return {
|
||||
'rf_prediction': rf_prediction,
|
||||
'feature_importance': dict(feature_importance)
|
||||
}
|
||||
|
||||
# Analysiere wie gut LIME die RF-Vorhersage erklärt
|
||||
importance_analysis = analyze_lime_feature_importance(
|
||||
instance=instance,
|
||||
rf_model=best_rf_model,
|
||||
lime_explainer=lime_explainer,
|
||||
num_features=20
|
||||
)
|
||||
Reference in New Issue
Block a user