Modify the code below into using SVM classifier with grid search:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold
from sklearn.metrics import accuracy_score, f1_score, make_scorer
from sklearn.ensemble import RandomForestClassifier
from argparse import ArgumentParser
from analysis_utils import batch_data
from config import *
def participant_based_cross_validation(df, n_folds=5, random_state=42):
"""
Performs participant-based k-fold cross-validation and returns integer indices.
Args:
df (pd.DataFrame): The input DataFrame with a 'participant' column.
n_folds (int): The number of folds for cross-validation.
random_state (int): Random seed for shuffling participants.
Returns:
list: A list of tuples, where each tuple contains (train_indices, test_indices)
for each fold.
"""
participants = df['participant'].unique()
np.random.seed(random_state)
np.random.shuffle(participants)
fold_size = len(participants) // n_folds
remainder = len(participants) % n_folds
folds_indices = []
start = 0
for i in range(n_folds):
end = start + fold_size + (1 if i < remainder else 0)
test_participants = participants[start:end]
train_participants = np.concatenate([participants[:start], participants[end:]])
train_indices = df[df['participant'].isin(train_participants)].index.tolist()
test_indices = df[df['participant'].isin(test_participants)].index.tolist()
folds_indices.append((train_indices, test_indices))
start = end
return folds_indices
if name == "main":
with open('data.csv', 'r', encoding='utf-8') as f:
df = pd.read_csv(f)
df = df[df['action'] != 'Pick']
input_features = []
input_features += ['is_last_resolved']
input_features += ['is_level_decreased']
input_features += ['last_pos_speech_cnt', 'last_neg_speech_cnt']
# input_features += ['has_crossed_arms', 'has_arms_back']
# input_features += ['task_gaze_ratio', 'robot_gaze_ratio']
for emotion in SELECTED_LR_EMOTIONS:
input_features.append(f'{emotion}_mean_change')
# input_features = SELECTED_FEATURES
target = 'is_resolved'
# Split the data into training and testing sets based on participants
participants = df['participant'].unique()
train_participants, test_participants = train_test_split(
participants, test_size=0.2, random_state=42, shuffle=True
)
train_df = df[df['participant'].isin(train_participants)].copy()
test_df = df[df['participant'].isin(test_participants)].copy()
# Reset the index of the DataFrames
train_df.reset_index(drop=True, inplace=True)
test_df.reset_index(drop=True, inplace=True)
folds = participant_based_cross_validation(train_df, n_folds=5, random_state=42)
# Define the hyperparameters to tune and their possible values for Random Forest
param_grid = {
'n_estimators': [50, 100, 150],
'max_depth': [4, 5, 6, 7],
'min_samples_split': [4, 5, 6, 7],
'min_samples_leaf': [1, 2, 3, 4],
}
# Initialize the Random Forest classifier
rf = RandomForestClassifier(random_state=42, class_weight='balanced')
# Define the scoring metrics
scoring = {'accuracy': 'accuracy', 'f1': make_scorer(f1_score)}
# Perform grid search using participant-based cross-validation
grid_search = GridSearchCV(estimator=rf,
param_grid=param_grid,
scoring=scoring,
cv=folds, # Now passing the list of index tuples
refit='f1',
verbose=2,
n_jobs=-1)
# Prepare the full dataset for grid search
X = train_df[input_features]
y = train_df[target]
grid_search.fit(X, y)
print("Best hyperparameters found on the training set:")
print(grid_search.best_params_)
print(f"Best F1 score found on the training set: {grid_search.best_score_:.4f}")
# Train the best model on the entire training set
best_model = grid_search.best_estimator_
# Print feature importances
feature_importances = best_model.feature_importances_
feature_names = input_features
feature_importance_df = pd.DataFrame({
'Feature': feature_names,
'Importance': feature_importances
}).sort_values(by='Importance', ascending=False)
print("Feature importances:")
print(feature_importance_df)
# Evaluate the model on the test set
X_test = test_df[input_features]
y_test = test_df[target]
y_pred = best_model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
print(f"Test Accuracy: {accuracy:.4f}")
print(f"Test F1 Score: {f1:.4f}")
print(len(train_df), len(test_df))