Group Part I: Machine Learning

Q5: Ensemble Learning (Any one) A. Implement a Random Forest classifier to predict the safety of a car. Dataset link: https://www.kaggle.com/datasets/elikplim/car-evaluation-data-set B. Use different voting mechanisms and apply AdaBoost (Adaptive Boosting), Gradient Tree Boosting (GBM), and XGBoost classification on the Iris dataset. Compare the performance of the three models using different evaluation measures. Dataset link: https://www.kaggle.com/datasets/uciml/iris

Ensemble Learning (Any one)

Solution and implementation for Q5 from Machine Learning (ml).

5A_random_forest_car_safety.ipynb Download

ML Practical 5: Random Forest Classification (Car Evaluation Dataset)

Implement a Random Forest classifier to predict the safety/acceptability of a car. Preprocess categorical features, train the model, evaluate accuracy, and plot classification distribution.

Code Cell 1
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
Code Cell 2
# Load dataset
df = pd.read_csv("car_evaluation.csv", header=None)
df.columns = ["buying", "maint", "doors", "persons", "lug_boot", "safety", "class"]
print("Dataset Shape:", df.shape)
print("\nFirst 5 rows:")
print(df.head())
Dataset Shape: (1728, 7)

First 5 rows:
  buying  maint doors persons lug_boot safety  class
0  vhigh  vhigh     2       2    small    low  unacc
1  vhigh  vhigh     2       2    small    med  unacc
2  vhigh  vhigh     2       2    small   high  unacc
3  vhigh  vhigh     2       2      med    low  unacc
4  vhigh  vhigh     2       2      med    med  unacc
Code Cell 3
# Prepare features and labels
X = pd.get_dummies(df.drop("class", axis=1), drop_first=True, dtype=float)
y = df["class"]

print("Encoded Feature Matrix Shape:", X.shape)
print("Target Class Distribution:\n", y.value_counts())
Encoded Feature Matrix Shape: (1728, 15)
Target Class Distribution:
 class
unacc    1210
acc       384
good       69
vgood      65
Name: count, dtype: int64
Code Cell 4
# Split dataset
a, b, c, d = train_test_split(X, y, test_size=0.2, random_state=42)
print("Train samples:", a.shape[0], "Test samples:", b.shape[0])
Train samples: 1382 Test samples: 346
Code Cell 5
# Train the model and predict
m = RandomForestClassifier(n_estimators=100, random_state=42)
m.fit(a, c)
p = m.predict(b)

print("Accuracy:", round(accuracy_score(d, p), 4))
print("\nClassification Report:\n", classification_report(d, p))
Accuracy: 0.8873

Classification Report:
               precision    recall  f1-score   support

         acc       0.82      0.72      0.77        83
        good       0.33      0.45      0.38        11
       unacc       0.94      1.00      0.96       235
       vgood       1.00      0.47      0.64        17

    accuracy                           0.89       346
   macro avg       0.77      0.66      0.69       346
weighted avg       0.89      0.89      0.88       346

Code Cell 6
# Visualizations
fig, axes = plt.subplots(1, 2, figsize=(13, 5))

# Target Class Counts
y.value_counts().plot(kind="bar", ax=axes[0], color="#38bdf8", edgecolor="black")
axes[0].set_title("Car Evaluation Classes Distribution", fontsize=12, fontweight="bold")
axes[0].set_xlabel("Class", fontsize=10)
axes[0].set_ylabel("Count", fontsize=10)
axes[0].grid(axis="y", linestyle="--", alpha=0.5)

# Actual vs Predicted comparison
comparison = pd.DataFrame({"Actual": d.values[:50], "Predicted": p[:50]})
axes[1].scatter(range(50), comparison["Actual"], color="#2563eb", label="Actual", alpha=0.7, s=50)
axes[1].scatter(range(50), comparison["Predicted"], color="#dc2626", marker="x", label="Predicted", alpha=0.7, s=50)
axes[1].set_title("Actual vs Predicted (First 50 Test Samples)", fontsize=12, fontweight="bold")
axes[1].set_xlabel("Sample Index", fontsize=10)
axes[1].set_ylabel("Class", fontsize=10)
axes[1].legend()
axes[1].grid(True, linestyle="--", alpha=0.5)

plt.tight_layout()
plt.show()
Cell 6 output
<Figure size ...>
5B_boosting_voting_iris.ipynb Download
Code Cell 1
# Q5B: AdaBoost, Gradient Boosting, XGBoost, and hard/soft voting on Iris.
# Source: https://www.kaggle.com/datasets/uciml/iris
# Install xgboost in a new environment if needed: pip install xgboost
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, VotingClassifier
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from xgboost import XGBClassifier
Code Cell 2
# Load the existing Iris CSV and encode the three species as integers.
iris = pd.read_csv("Iris.csv")
X = iris.drop(columns=["Id", "Species"])
encoder = LabelEncoder()
y = encoder.fit_transform(iris["Species"])
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42
)
print("Training samples:", len(X_train), "Test samples:", len(X_test))
print("Species:", list(encoder.classes_))
Training samples: 112 Test samples: 38
Species: ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']
Code Cell 3
# Build the three requested boosting models.
models = {
    "AdaBoost": AdaBoostClassifier(n_estimators=60, random_state=42),
    "Gradient Boosting": GradientBoostingClassifier(n_estimators=80, random_state=42),
    "XGBoost": XGBClassifier(n_estimators=80, max_depth=3, learning_rate=0.1,
                              objective="multi:softprob", num_class=3,
                              eval_metric="mlogloss", n_jobs=1, random_state=42),
}
Code Cell 4
# Compare each model using the same held-out test set.
results = []
fitted_models = {}
for name, model in models.items():
    model.fit(X_train, y_train)
    fitted_models[name] = model
    predicted = model.predict(X_test)
    results.append({
        "Model": name,
        "Accuracy": accuracy_score(y_test, predicted),
        "Macro precision": precision_score(y_test, predicted, average="macro", zero_division=0),
        "Macro recall": recall_score(y_test, predicted, average="macro", zero_division=0),
        "Macro F1": f1_score(y_test, predicted, average="macro", zero_division=0),
    })
Code Cell 5
# Hard voting uses majority class labels; soft voting averages probabilities.
for voting in ["hard", "soft"]:
    ensemble = VotingClassifier(estimators=list(models.items()), voting=voting)
    ensemble.fit(X_train, y_train)
    predicted = ensemble.predict(X_test)
    fitted_models[f"{voting.title()} voting"] = ensemble
    results.append({
        "Model": f"{voting.title()} voting",
        "Accuracy": accuracy_score(y_test, predicted),
        "Macro precision": precision_score(y_test, predicted, average="macro", zero_division=0),
        "Macro recall": recall_score(y_test, predicted, average="macro", zero_division=0),
        "Macro F1": f1_score(y_test, predicted, average="macro", zero_division=0),
    })
comparison = pd.DataFrame(results).set_index("Model")
print(comparison.round(3).to_string())
comparison["Macro F1"].sort_values().plot.barh(figsize=(7, 4), xlim=(0, 1),
                                                 title="Iris model comparison")
plt.tight_layout()
plt.show()
                   Accuracy  Macro precision  Macro recall  Macro F1
Model                                                               
AdaBoost              0.921            0.925         0.923     0.923
Gradient Boosting     0.974            0.976         0.974     0.974
XGBoost               0.921            0.925         0.923     0.923
Hard voting           0.947            0.949         0.949     0.949
Soft voting           0.947            0.949         0.949     0.949
Cell 5 output
Code Cell 6
# Inspect predictions from the top-scoring model.
best_name = comparison["Macro F1"].idxmax()
best_predictions = fitted_models[best_name].predict(X_test)
print("Best model:", best_name)
ConfusionMatrixDisplay.from_predictions(y_test, best_predictions,
                                        display_labels=encoder.classes_, cmap="Blues")
plt.title(best_name + " confusion matrix")
plt.tight_layout()
plt.show()
Best model: Gradient Boosting
Cell 6 output

Other Questions in Machine Learning

See All Available Questions
Download