# Required Libraries
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import IsolationForest
from sklearn.inspection import permutation_importance
import matplotlib.pyplot as plt
import seaborn as sns
import shap

# Load Data
file_path = 'Mcfc Mids.csv'  # Replace with your file path
data = pd.read_csv(file_path)

# Specify PlayerID to Analyze
selected_player_id = 16436

# Step 1: Prepare Data
feature_data = data.drop(columns=['Id', 'Player', 'Nation', 'Pos', 'Squad', 'Comp'], errors='ignore')
numerical_features = feature_data.select_dtypes(include=[np.number])

# Scale Features
scaler = StandardScaler()
scaled_features = scaler.fit_transform(numerical_features)
scaled_features_df = pd.DataFrame(scaled_features, columns=numerical_features.columns)

# Locate the Player
selected_player_row = data[data['Id'] == selected_player_id].index[0]

# Step 2: Train Isolation Forest Model
iso_forest = IsolationForest(n_estimators=100, contamination='auto', random_state=42)
iso_forest.fit(scaled_features)

# Step 3: Analyze Player Uniqueness
selected_player_features = scaled_features_df.iloc[selected_player_row]
selected_player_score = iso_forest.decision_function([selected_player_features])
selected_player_outlier = iso_forest.predict([selected_player_features])

# Display Results for Player
selected_player_details = {
    "Decision Score": selected_player_score[0],
    "Outlier Prediction": "Outlier" if selected_player_outlier[0] == -1 else "Normal"
}
print("Selected Player Details:", selected_player_details)

# Step 4: Feature Importance via Permutation
perm_importances = permutation_importance(
    iso_forest,
    scaled_features,
    scoring=lambda estimator, X: -estimator.decision_function(X),
    n_repeats=30,
    random_state=42
)

perm_importance_df = pd.DataFrame({
    'Feature': numerical_features.columns,
    'Importance': perm_importances.importances_mean
}).sort_values(by='Importance', ascending=False)

# Visualize Feature Importances
plt.figure(figsize=(12, 6))
sns.barplot(x='Importance', y='Feature', data=perm_importance_df.head(15))
plt.title('Top 15 Feature Importances')
plt.xlabel('Permutation Importance')
plt.ylabel('Feature')
plt.show()

# Step 5: SHAP Analysis
explainer = shap.TreeExplainer(iso_forest)
shap_values = explainer.shap_values(scaled_features)

# SHAP Summary Plot
shap.summary_plot(shap_values, scaled_features_df, feature_names=numerical_features.columns)

# SHAP Force Plot for the Selected Player
shap.force_plot(
    explainer.expected_value,
    shap_values[selected_player_row],
    scaled_features_df.iloc[selected_player_row],
    feature_names=numerical_features.columns
)

# Step 6: Contribution Analysis for Selected Player
feature_contributions = pd.Series(
    abs(selected_player_features * selected_player_score[0]),
    index=numerical_features.columns
).sort_values(ascending=False)

# Display Top Contributing Features
top_contributing_features = feature_contributions.head(10)
print("Top Contributing Features to Player's Uniqueness:")
print(top_contributing_features)


Selected Player Details: {'Decision Score': 0.07467976040772206, 'Outlier Prediction': 'Normal'}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-a417528dcdea> in <cell line: 47>()
     45 
     46 # Step 4: Feature Importance via Permutation
---> 47 perm_importances = permutation_importance(
     48     iso_forest,
     49     scaled_features,

2 frames
/usr/lib/python3.10/inspect.py in _bind(self, args, kwargs, partial)
   3099                             msg = 'missing a required argument: {arg!r}'
   3100                             msg = msg.format(arg=param.name)
-> 3101                             raise TypeError(msg) from None
   3102             else:
   3103                 # We have a positional argument to process

TypeError: missing a required argument: 'y'

Fix the error and do what all you have suggested