Certainly! Below is a Python program that uses scikit-learn to load the breast cancer dataset, fits the specified machine learning algorithms to the data, evaluates them with the given performance metrics, and visualizes the confusion matrices using matplotlib.
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report, precision_score, recall_score, f1_score, confusion_matrix
from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from xgboost import XGBClassifier
import seaborn as sns
# Load the dataset
data = load_breast_cancer()
X = data.data
y = data.target
# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Initialize classifiers
classifiers = {
'Ada Boost': AdaBoostClassifier(),
'XG Boost': XGBClassifier(use_label_encoder=False, eval_metric='logloss'),
'Random Forest': RandomForestClassifier(),
'Decision Tree': DecisionTreeClassifier()
}
# Train models, predict and evaluate
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
fig.subplots_adjust(hspace=0.4, wspace=0.4)
for i, (name, clf) in enumerate(classifiers.items()):
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
# Evaluation metrics
accuracy = accuracy_score(y_test, y_pred)
clf_report = classification_report(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
# Print metrics
print(f"Classifier: {name}")
print(f"Accuracy: {accuracy}")
print(f"Classification report:\n{clf_report}")
print(f"Precision: {precision}")
print(f"Recall: {recall}")
print(f"F1 score: {f1}")
print("-" * 30)
# Confusion matrix
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True, fmt="d", ax=axes[i // 2, i % 2])
axes[i // 2, i % 2].set_title(f"{name} Confusion Matrix")
axes[i // 2, i % 2].set_xlabel('Predicted')
axes[i // 2, i % 2].set_ylabel('True')
# Show plot
plt.show()
Make sure that you have scikit-learn, matplotlib, seaborn, and xgboost installed in your environment. You can install them via pip if you haven't already:
pip install scikit-learn matplotlib seaborn xgboost
The above code snippet will:
- Load the breast cancer dataset from
sklearn.
- Split the dataset into training and testing sets.
- Initialize the AdaBoost, XGBoost, RandomForest, and DecisionTree classifiers.
- Fit the classifiers on the training data.
- Evaluate each classifier on test data using accuracy, classification report, precision, recall, and F1 score.
- Print the performance metrics for each classifier.
- Plot the confusion matrix for each classifier in a subplot.
Please note that real-world machine learning workflow would include additional steps such as feature scaling, parameter tuning, cross-validation, etc., to ensure robust performance and avoid overfitting or other issues.