Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Added implementation of feature_permutation #91

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/ml_tooling/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import Union

import numpy as np
import pandas as pd
from sklearn import metrics

from .utils import _is_percent
Expand Down Expand Up @@ -70,6 +71,44 @@ def confusion_matrix(y_true: np.ndarray, y_pred: np.ndarray, normalized=True) ->
return cm


def permuted_feature_importance(model,
x,
y,
refit=True,
metric=None):
"""
Calculates feature importance by randomly permuting features and comparing result to baseline
:param y:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't y training/test target?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, changed the implementation without updating docs - still have some work to do on this feature 😄

DataFrame of trainining features
:param x:
DataFrame of testing features
:param model:
A sklearn-compatible estimator
:param refit:
Refit the model to get baseline score

:param metric:
Metric to use
:return:
"""

if refit:
model.fit(x, y)

baseline_score = model.score(x, y)
importances = {}

for column in x.columns:
original_data = x[column].copy()
x[column] = np.random.permutation(x[column])
column_score = model.score(x, y)
importances[column] = baseline_score - column_score
x[column] = original_data

importance_df = pd.DataFrame.from_dict(importances, orient='index', columns=['importance'])
return importance_df.sort_values(by='importance')


def sorted_feature_importance(labels: np.ndarray,
importance: np.ndarray,
top_n: Union[int, float] = None,
Expand Down