image_output_1.png
from sklearn.metrics import make_scorer

from sklearn.model_selection import GridSearchCV

from sklearn.preprocessing import LabelEncoder

from sklearn.preprocessing import MinMaxScaler

from sklearn.utils.class_weight import compute_sample_weight

import matplotlib.pyplot as plt

import numpy as np

import pandas as pd

train_data = pd.read_csv('/kaggle/input/playground-series-s3e13/train.csv')
test_data = pd.read_csv('/kaggle/input/playground-series-s3e13/test.csv')

plt.xticks(rotation=90)

train_data['symptom_sum'] = train_data.iloc[:, 1:-1].sum(axis=1)

X = train_data.drop(['id', 'prognosis'], axis=1).reset_index(drop=True)
y = train_data['prognosis'].reset_index(drop=True)
le = LabelEncoder()
y = le.fit_transform(y)
y = np.array(y)
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)

def map3_score(estimator, X_train, y_true):
    """
    Computes the mean Average Precision (MAP) at 3 score between the true labels and the predicted labels.
    Assumes that there is only one true label per sample.
    Args:
        y_true (array-like): True labels array, shape (n_samples,)
        y_pred (array-like): Predicted probabilities matrix, shape (n_samples, n_classes)
    Returns:
        float: MAP@3 score
    """
    score = 0.0
    y_pred_top3 = estimator.predict(X_train)[0]
    for i in range(len(y_true)):
        true_label = y_true[i]
        pred_labels = y_pred_top3[i]
        ap = 0.0
        for j in range(3):
            if pred_labels[j] == true_label:
                ap = 1.0 / (j + 1)
                break
        score += ap
    map3 = score / len(y_true)
    return map3
map3_scorer = make_scorer(map3_score, greater_is_better=True)

class_weights = compute_sample_weight('balanced', y=y)
svm_classifier = SVCTop3Classifier()
param_grid = {'C': [0.1, 1, 10], 'kernel': ['linear', 'poly', 'rbf', 'sigmoid'], 'gamma': ['scale', 'auto'], 'max_iter': [-1]}
grid_search = GridSearchCV(svm_classifier, param_grid, scoring=map3_score, cv=5, verbose=3)
grid_search.fit(X_scaled, y, sample_weight=class_weights)
print('Best Parameters: ', grid_search.best_params_)
print('Best Score: ', grid_search.best_score_)