import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.metrics import roc_curve, auc # Generate synthetic data for binary classification X, y = make_classification(n_samples=1000, n_features=20, n_informative=10, n_redundant=10, random_state=42) # Standardize the data using StandardScaler scaler = StandardScaler() X = scaler.fit_transform(X) # Split the data into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Fit the train set with classifiers rf_classifier = RandomForestClassifier(random_state=42) knn_classifier = KNeighborsClassifier() svm_classifier = SVC(probability=True, random_state=42) rf_classifier.fit(X_train, y_train) knn_classifier.fit(X_train, y_train) svm_classifier.fit(X_train, y_train) # Generate predictions for the test set rf_probs = rf_classifier.predict_proba(X_test)[:, 1] knn_probs = knn_classifier.predict_proba(X_test)[:, 1] svm_probs = svm_classifier.predict_proba(X_test)[:, 1] # Calculate false positive rate, true positive rate, # and area under the curve for ROC curve rf_fpr, rf_tpr, _ = roc_curve(y_test, rf_probs) rf_auc = auc(rf_fpr, rf_tpr) knn_fpr, knn_tpr, _ = roc_curve(y_test, knn_probs) knn_auc = auc(knn_fpr, knn_tpr) svm_fpr, svm_tpr, _ = roc_curve(y_test, svm_probs) svm_auc = auc(svm_fpr, svm_tpr) # Plot the ROC curve plt.figure() plt.plot(rf_fpr, rf_tpr, label=f'Random Forest (AUC = {rf_auc:.2f})') plt.plot(knn_fpr, knn_tpr, label=f'KNN (AUC = {knn_auc:.2f})') plt.plot(svm_fpr, svm_tpr, label=f'SVM (AUC = {svm_auc:.2f})') plt.plot([0, 1], [0, 1], 'k--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic') plt.legend(loc='lower right') plt.show()