Metadata-Version: 2.2
Name: shapley_calculator
Version: 0.1.2
Summary: A library to calculate Shapley values for feature importance in machine learning models.
Home-page: https://github.com/AlekseevDS21/Shapley
Author: Andrew Alexeev
Author-email: andrey.alekseev8996@gmail.com
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.6
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: requires-python
Dynamic: summary

# Shapley Calculator

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

## Installation

```bash
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}")
