Skip to main content

A library to calculate Shapley values for feature importance in machine learning models.

Project description

Shapley Calculator

A library to calculate Shapley values for feature importance in machine learning models.

Installation

pip install shapley_calculator

## Пример использования

Вот пример того, как использовать `shapley_calculator` для расчета значений Шепли:

```python
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor
from shapley_calculator.shapley import ShapleyValueCalculator
from tqdm import tqdm  # для отображения прогресса
import matplotlib.pyplot as plt  # для визуализации

# Загружаем датасет California Housing
print("Loading California Housing dataset...")
housing = fetch_california_housing()
X = housing.data
y = housing.target
feature_names = housing.feature_names

# Создаем DataFrame для отображения данных
print("\nFirst 5 rows of the original dataset:")
df = pd.DataFrame(X, columns=feature_names)
df['Price'] = y
print(df.head().to_string())
print("\nFeature descriptions:")
for name, description in zip(feature_names, housing.feature_names):
    print(f"{name:10}: {description}")
print(f"Target     : House price in $100,000s")

# Берем подвыборку данных для ускорения примера
n_samples = 1000  # уменьшаем размер датасета
np.random.seed(42)  # фиксируем seed
indices = np.random.choice(len(X), n_samples, replace=False)
X = X[indices]
y = y[indices]

print("\nPreprocessing data...")
# Масштабируем признаки
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Разделяем данные на обучающую и тестовую выборки
X_train, X_test, y_train, y_test = train_test_split(
    X_scaled, y, test_size=0.2, random_state=42
)

print("Training Random Forest model...")
# Обучаем модель случайного леса
model = RandomForestRegressor(n_estimators=50, random_state=42)  # уменьшаем количество деревьев
model.fit(X_train, y_train)

print("Calculating Shapley values...")
# Берем только часть тестовой выборки для расчета значений Шепли
n_test_samples = 100  # количество примеров для анализа
X_test_sample = X_test[:n_test_samples]
y_test_sample = y_test[:n_test_samples]

# Создаем калькулятор значений Шепли
calculator = ShapleyValueCalculator(model, X_test_sample, y_test_sample, 
                                  num_samples=100, random_state=42)

# Вычисляем значения Шепли
shapley_values = calculator.get_shapley_values(normalize=True)

# Создаем DataFrame с результатами
results = pd.DataFrame({
    'Feature': feature_names,
    'Shapley Value': shapley_values
})

# Сортируем признаки по важности
results_sorted = results.sort_values('Shapley Value', ascending=False)

print("\nCalifornia Housing Dataset Analysis")
print("\nShapley Values (normalized, sorted by importance):")
print(results_sorted)

# Создаем и показываем визуализацию для общих значений Шепли
print("\nGenerating Shapley values visualization...")
calculator.plot_shapley_values(
    feature_names=feature_names,
    title='Общая важность признаков (усредненные значения Шепли)'
)
plt.show()

print("\nAnalyzing specific example...")
# Анализируем конкретный пример
sample_idx = 0
sample_shapley = calculator.get_shapley_values(sample_idx=sample_idx, normalize=True)

print("\nExample Analysis")
print("Sample features and their contributions:")
for name, value, shapley in zip(feature_names, X_test_sample[sample_idx], sample_shapley):
    actual_value = scaler.inverse_transform([X_test_sample[sample_idx]])[0][feature_names.index(name)]
    print(f"{name:10}: {actual_value:8.2f} (Shapley: {shapley:8.4f})")

# Создаем и показываем визуализацию для конкретного примера
print("\nGenerating Shapley values visualization for the specific example...")
calculator.plot_shapley_values(
    feature_names=feature_names,
    sample_idx=sample_idx,
    title=f'Важность признаков для примера #{sample_idx}'
)
plt.show()

# Оценка качества модели
train_score = model.score(X_train, y_train)
test_score = model.score(X_test, y_test)

print(f"\nModel Performance:")
print(f"R2 score (train): {train_score:.3f}")
print(f"R2 score (test): {test_score:.3f}")

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

shapley_calculator-0.1.2.tar.gz (9.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

shapley_calculator-0.1.2-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

Details for the file shapley_calculator-0.1.2.tar.gz.

File metadata

  • Download URL: shapley_calculator-0.1.2.tar.gz
  • Upload date:
  • Size: 9.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.6

File hashes

Hashes for shapley_calculator-0.1.2.tar.gz
Algorithm Hash digest
SHA256 26d8a5cf9e945c8c2f09bf99357c70019596b26c225ad2fc8d769d7919af3e1f
MD5 3aaae618de0ecd8f99a12c492e2811a0
BLAKE2b-256 bb78b4082303cff2fb5be1e4849830fadc346e2bb9fbbf142316f95e089f635c

See more details on using hashes here.

File details

Details for the file shapley_calculator-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for shapley_calculator-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 00f4f55afac4f47c8d5cae7c17fa1f58444a646d5a652d58b3d4c7f93722ed19
MD5 d538cca3f90f2b5515c951e37de4cef1
BLAKE2b-256 fc937217eb00be97c0a31032427f2757b08a062ba56a64a004cff63de53ba20f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page