use holdout with 5 random seeds: from sklearn.featureextraction.text import…
- User
use holdout with 5 random seeds: from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import classification_report from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay import matplotlib.pyplot as plt
Adjusting the function to accept pre-split data
def compare_classifiers(X_train, X_test, y_train, y_test):
# List of classifiers to compare classifiers = [ ('Logistic Regression', LogisticRegression(random_state=42)), ('Naive Bayes', MultinomialNB()), ('Random Forest', RandomForestClassifier(n_estimators=100, random_state=42)), ('KNN', KNeighborsClassifier(n_neighbors=5)) ] # Iterate over classifiers, train, predict, and display metrics for name, clf in classifiers: print(f'----- {name} -----') clf.fit(X_train, y_train) y_pred = clf.predict(X_test) # Classification Report print('Classification Report:') print(classification_report(y_test, y_pred)) # Confusion Matrix print('Confusion Matrix:') cm = confusion_matrix(y_test, y_pred) disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=clf.classes_) disp.plot() plt.show() print('\n')The function now expects four parameters:
X_train: The training data (text)
X_test: The test data (text)
y_train: The training labels
y_test: The test labels
Example usage (assuming pre-split data):
compare_classifiers(X_train, X_test, y_train, y_test)
- Assistant
- User
you have to modify the code so it prints the average over the 5 seeds
- Assistant
- User
porque train test split no es compatible con el parametro de compare sedds: from sklearn.model_selection import train_test_split
X_preprocessed = [preprocess_text(text) for text in df.text]
train_test_sets = []
for i in range(5): X_train, X_test, y_train, y_test = train_test_split(X_preprocessed, df.label, test_size=0.05, train_size=0.2, random_state=i, shuffle=True) train_test_sets.append((X_train, X_test, y_train, y_test))
Initialize a dictionary to hold all results def compare_seeds(train_test_sets, method='tfidf'): all_seeds_results = {}
for X_train, X_test, y_train, y_test, i in enumerate(train_test_sets): print(f"---- Random Seed: {i} ----") if method == 'tfidf': X_train, X_test = tfidf_features(X_train, X_test) else: X_train, X_test = embeddings_features(X_train, X_test) seed_results = compare_classifiers(X_train, X_test, y_train, y_test) - Assistant
The issue in your code snippet arises because of how you're using
enumeratein yourcompare_seedsfunction. Theenumeratefunction is meant to be applied directly to the list (or iterable) you're looping over, but in the way you've structured your loop, you're attempting to unpack the values from before enumerating them, which is leading to confusion about where the index is coming from and how the unpacking is done. - User
mejora este codigo: for name, clf in classifiers: if name == 'Neural Network': if method == 'tfidf': continue else: y_pred = train_nn(clf,X_train, y_train, X_test, y_test) else:
clf.fit(X_train, y_train) y_pred = clf.predict(X_test) - Assistant
The code snippet you have seems to be part of a larger function that trains different classifiers and makes predictions with them, handling a special case for a 'Neural Network' classifier which perhaps requires a different training function or does not work with 'tfidf' features. Let's improve its readability and efficiency by making the flow more clear and adding some comments for clarity:
for name, clf in classifiers: # Skip neural network training for tfidf method directly in the loop if name == 'Neural Network' and method == 'tfidf': print("Skipping Neural Network for TFIDF method.") continue # Skip this iteration if we're dealing with a neural network and using tfidf # Neural Network requires a different training approach if name == 'Neural Network': # Assuming train_nn() is predefined elsewhere y_pred = train_nn(clf, X_train, y_train, X_test, y_test) else: # For all other classifiers, use the standard fit/predict approach clf.fit(X_train, y_train) y_pred = clf.predict(X_test) - User
i dont care about every single seed metrics, i want to know each methods average after fitting them all:
Initialize a dictionary to hold all results
def compare_seeds(train_test_sets, method='tfidf'): all_seeds_results = {}
for i, (X_train, X_test, y_train, y_test) in enumerate(train_test_sets): print(f"---- Random Seed: {i} ----") if method == 'tfidf': X_train, X_test = tfidf_features(X_train, X_test) else: X_train, X_test = embeddings_features(X_train, X_test) seed_results = compare_classifiers(X_train, X_test, y_train, y_test,method) for clf_name, metrics in seed_results.items(): if clf_name not in all_seeds_results: all_seeds_results[clf_name] = {'precision': [], 'recall': [], 'fscore': []} # Accumulate results for metric_name, metric_values in metrics.items(): all_seeds_results[clf_name][metric_name] += metric_values # Compute and print averages for clf_name, metrics in all_seeds_results.items(): print(f'----- {clf_name} Average Metrics -----') for metric_name, metric_values in metrics.items(): print(f'{metric_name.capitalize()} Avg: {np.mean(metric_values):.4f}') print('\n') - Assistant