Machine Learning Model Training and Evaluation

Step 1: Importing Required Libraries

  • Imported libraries:
    • pandas: For data manipulation and analysis.
    • numpy: For numerical operations.
    • matplotlib.pyplot: For plotting graphs.
    • seaborn: For data visualization.
    • time: For measuring execution time.
    • sklearn.datasets: To load datasets.
    • sklearn.model_selection: For splitting data and cross-validation.
    • sklearn.preprocessing: For standardizing data.
    • sklearn.linear_model: To use Logistic Regression model.
    • sklearn.tree: To use Decision Tree model.
    • sklearn.naive_bayes: To use Gaussian Naive Bayes model.
    • sklearn.svm: To use Support Vector Machine model.
    • sklearn.metrics: For model evaluation metrics (accuracy, confusion matrix, classification report).

Step 2: Loading the Data

  • Loading datasets from sklearn.datasets:
    • iris = datasets.load_iris(): Loads the Iris dataset.
    • breast_cancer = datasets.load_breast_cancer(): Loads the Breast Cancer dataset.
  • Converting datasets to Pandas DataFrames:
    • iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names): Creates a DataFrame for the Iris dataset.
    • iris_df['target'] = iris.target: Adds the target variable to the Iris DataFrame.
    • cancer_df = pd.DataFrame(data=breast_cancer.data, columns=breast_cancer.feature_names): Creates a DataFrame for the Breast Cancer dataset.
    • cancer_df['target'] = breast_cancer.target: Adds the target variable to the Breast Cancer DataFrame.
  • Displaying basic data:
    • Prints the head (first few rows) of both DataFrames using iris_df.head() and cancer_df.head().
    • Prints the sum of null values for both DataFrames using iris_df.isnull().sum().sum() and cancer_df.isnull().sum().sum().

Step 3: Data Preprocessing

  • Defining a function preprocess_data(df, target_column):
    • Splits the DataFrame into features (X) and target (y).
    • X = df.drop(columns=[target_column]): Drops the target column to create the feature set.
    • y = df[target_column]: Assigns the target column to the target variable.
    • Scales the features using StandardScaler.
    • scaler = StandardScaler(): Initializes the StandardScaler.
    • X_scaled = scaler.fit_transform(X): Fits the scaler to the features and transforms them.
    • Splits the data into training and testing sets using train_test_split.
    • X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42): Splits the data into 80% training and 20% testing sets with a fixed random state for reproducibility.
  • Applying the preprocessing function to both datasets:
    • iris_X_train, iris_X_test, iris_y_train, iris_y_test = preprocess_data(iris_df, 'target')
    • cancer_X_train, cancer_X_test, cancer_y_train, cancer_y_test = preprocess_data(cancer_df, 'target')

Step 4: Building the Models

  • Defining a dictionary of models to be trained:
    • models = { ... } contains:
      • "Logistic Regression": LogisticRegression(max_iter=1000): Logistic Regression model with a maximum of 1000 iterations.
      • "Decision Tree": DecisionTreeClassifier(random_state=42): Decision Tree model with a fixed random state.
      • "Naive Bayes": GaussianNB(): Gaussian Naive Bayes model.
      • "SVM": SVC(kernel='linear', random_state=42): Support Vector Machine model with a linear kernel and a fixed random state.
  • Defining a function train_evaluate_models(models, X_train, X_test, y_train, y_test):
    • Iterates through each model in the models dictionary.
    • Measures the training time using time.time().
    • Fits the model to the training data using model.fit(X_train, y_train).
    • Predicts on the training and testing sets using model.predict(X_train) and model.predict(X_test).
    • Calculates the training and testing accuracy using accuracy_score.
    • Stores the results (training accuracy, testing accuracy, training time) in a results dictionary.
  • Applying the training and evaluation function to both datasets:
    • Prints the results for the Iris dataset.
    • iris_results = train_evaluate_models(models, iris_X_train, iris_X_test, iris_y_train, iris_y_test)
    • Prints the results as a Pandas DataFrame using pd.DataFrame(iris_results).T.
    • Prints the results for the Breast Cancer dataset.
    • cancer_results = train_evaluate_models(models, cancer_X_train, cancer_X_test, cancer_y_train, cancer_y_test)
    • Prints the results as a Pandas DataFrame using pd.DataFrame(cancer_results).T.

Step 5: Evaluation

  • Defining a function plot_evaluation(model, X_test, y_test, model_name, dataset_name):
    • Predicts on the test set using model.predict(X_test).
    • Computes and displays the confusion matrix using confusion_matrix and ConfusionMatrixDisplay.
    • Prints the classification report using classification_report.
  • Evaluating all models on the Iris dataset:
    • Iterates through each model and calls plot_evaluation with the Iris data.
  • Evaluating all models on the Breast Cancer dataset:
    • Iterates through each model and calls plot_evaluation with the Breast Cancer data.

Step 6: Cross-Validation

  • Defining a function perform_cross_validation(models, X, y, cv=5):
    • Iterates through each model in the models dictionary.
    • Performs cross-validation using cross_val_score with the specified number of folds (cv).
      • The cross_val_score function returns an array of scores, one for each fold.
    • Calculates the mean and standard deviation of the cross-validation scores.
    • Stores the mean and standard deviation in a cv_results dictionary.
  • Applying cross-validation to both datasets:
    • Prints the cross-validation results for the Iris dataset.
    • iris_cv = perform_cross_validation(models, iris.data, iris.target)
    • Prints the results as a Pandas DataFrame.
    • Prints the cross-validation results for the Breast Cancer dataset.
    • cancer_cv = perform_cross_validation(models, breast_cancer.data, breast_cancer.target)
    • Prints the results as a Pandas DataFrame.

Step 7: Final Report

  • Merging the results from training/evaluation and cross-validation:
    • final_iris_report = pd.DataFrame(iris_results).join(iris_cv): Joins the Iris training results with the cross-validation results.
    • final_cancer_report = pd.DataFrame(cancer_results).join(cancer_cv): Joins the Breast Cancer training results with the cross-validation results.
  • Printing the final reports for both datasets:
    • Prints the final report for the Iris dataset.
    • Prints the final report for the Breast Cancer dataset.
  • Determining the best model for each dataset:
    • best_iris_model = final_iris_report['Test Accuracy'].idxmax(): Finds the model with the highest test accuracy for the Iris dataset.
    • best_cancer_model = final_cancer_report['Test Accuracy'].idxmax(): Finds the model with the highest test accuracy for the Breast Cancer dataset.
  • Comparing training times:
    • Creates a DataFrame to compare the training times for both datasets.
    • Prints the DataFrame.